[公众号]微信分享网页显示图片(个人号)
本文主页介绍如何在微站里面实现分享网页给朋友和朋友圈,显示图片和简介,这么简单的功能是如何实现的。
申请公众号
2、特别注意!个人帐号无法微信认证!必须是企业或者个体工商户!
<?php
define("TOKEN","注册时候自定义的Token");
function checkSignature()
{
//从GET参数中读取三个字段的值
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
//读取预定义的TOKEN
$token = TOKEN;
//对数组进行排序
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
//对三个字段进行sha1运算
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
//判断我方计算的结果是否和微信端计算的结果相符
//这样利用只有微信端和我方了解的token作对比,验证访问是否来自微信官方.
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
if(checkSignature()){
echo $_GET["echostr"];
}
else{
echo 'error';
}
附加逻辑流程图
使用微信的jssdk
先需要在微信公众号后台进行设置:公众号设置-->功能设置-->JS接口安全域名。打开这个页面之后你会看到下面的提示。需要先下载这个文件并上传到指定域名的根目录。
这个文件里面是一个字符串,是用来校验用的。先上传了这个文件,你才能保存成功。之后就可以使用jssdk了(注意需要确保txt文件可以被访问到,服务器不能做TXT文件的禁止访问)。
注意:将下载下来的txt文件放在域名www.wubin.work/mywx/xxx.txt的目录下,之后填写www.wubin.work/mywx即可
添加微信白名单
要申请access_token必须要先将服务器地址以及开发者IP地址添加入白名单
添加好之后,发送的请求才可以接收到回执。(IP地址之间用回车分割!)
获取access_token
首先编写两个PHP文件
1、jssdk.class.php(功能正常 但非完全版 根据情况进行修改)
<?php
class JSSDK {
// https://www.cnblogs.com/LXJ416/p/6133536.html
//微信公众号的id
private $appId;
//微信公众号密码
private $appSecret;
// 存储的access_token.json的文件名
private $accessTokenFile = 'access_token.json';
// 存储的jsapi_ticket.json的文件名
private $jdkTicketFile = 'jsapi_ticket.json';
// 当前的时间戳
private $nowTime;
// 返回的结果是一个数组
private $result;
public function __construct($appId, $appSecret)
{
$this->appId = $appId;
$this->appSecret = $appSecret;
$this->nowTime = time();
}
// 获取微信的配置信息
public function getSignPackage($url)
{
$jsapiTicket = $this->getJsApiTicket();
// $url = "https://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$timestamp = $this->nowTime;
$nonceStr = $this->createNonceStr();
// 这里参数的顺序要按照 key 值 ASCII 码升序排序
$string = "jsapi_ticket={$jsapiTicket}&noncestr={$nonceStr}×tamp={$timestamp}&url={$url}";
$signature = sha1($string);
$signPackage = array(
"appId" => $this->appId,
"nonceStr" => $nonceStr,
"timestamp" => $timestamp,
"url" => $url,
"signature" => $signature,
// 加密前的字符串不返回
// "rawSting" => $string
);
return $signPackage;
}
// 请求微信的jdk,jsapi_ticket 应该全局存储与更新
private function getJsApiTicket() {
$data = $this->getJsonFile($this->jdkTicketFile);
if (!$data || $data['expire_time'] < $this->nowTime) {
// 获取access_token
$accessToken = $this->getAccessToken();
$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=";
$url = $url . $accessToken;
$res = json_decode($this->httpGet($url), true);
$ticket = $res['ticket'];
if ($ticket) {
$data = array(
'expire_time' => $this->nowTime + $res['expires_in'],
'jsapi_ticket' => $ticket
);
!$this->saveFile($this->jdkTicketFile, $data) && $this->showError();
}
} else {
$ticket = $data['jsapi_ticket'];
}
return $ticket;
}
// 请求微信接口的access_token,access_token 应该全局存储与更新
private function getAccessToken() {
$data = $this->getJsonFile($this->accessTokenFile);
if (!$data || $data['expire_time'] < $this->nowTime) {
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
$url = $url."{$this->appId}&secret={$this->appSecret}";
// 将获取到token-JSON字符串转化为数组
$res = json_decode($this->httpGet($url), true);
// 获取返回的access_token
$access_token = $res['access_token'];
if ($access_token) {
// $data是一个数组
$data = array(
// 过期时间 = 当前时间 + 返回的有效期
'expire_time' => $this->nowTime + $res['expires_in'],
'access_token' => $access_token
);
!$this->saveFile($this->accessTokenFile, $data) && $this->showError();
}
} else {
$access_token = $data['access_token'];
}
return $access_token;
}
private function createNonceStr($length = 16) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$str = "";
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
// 使用curl请求地址
private function httpGet($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
curl_setopt($curl, CURLOPT_URL, $url);
// 请求的是https需要加上下面2句
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
$res = curl_exec($curl);
if (!$res) {
echo 'Curl error: ' . curl_error($curl);
exit();
}
curl_close($curl);
return $res;
}
// 打开JSON文件
private function getJsonFile($filename)
{
// 如果文件不存在 抑制报错
$resource = @file_get_contents($filename);
return $resource ? json_decode($resource, true) : false;
}
/**
* [saveFile 保存文件]
* @DateTime 2021-03-04T14:07:01+0800
* @param [string] $filename [文件名]
* @param [array] $data [将要写入文件的数组]
* @return [boolean] [文件写入成功或者失败]
*/
private function saveFile($filename, $data)
{
$fp = fopen($filename, 'w');
$fwrite_res = fwrite($fp, json_encode($data));
fclose($fp);
return $fwrite_res ? true : false;
}
private function showError($msg = '')
{
$this->result = array(
'error' => true,
'msg' => $msg
);
exit($this->result);
}
}
2、同级目录下,再新建wx_share.php(仅基本功能,具体需要根据情况修改)
<?php
header('content-type:application/json;charset=utf8');
require('jssdk.class.php');
$appId = 'xxxxxxxxxxx';
$appSecret = 'xxxxxxxxxxxxxxxxxxx';
// 要分享的页面的链接
$url = isset($_GET['url']) ? $_GET['url'] : false;
if (!$url) {
exit('请输入url');
}
$jssdk = new JSSDK($appId, $appSecret);
$signPackage = $jssdk->getSignPackage($url);
echo json_encode($signPackage);
至此,访问 https://www.wubin.work/mychat/wx_share.php 可以拿到返回的json数据
前台页面进行获取
1、HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>微信分享测试</title>
<meta name="description" content="分享希望成功!!">
</head>
<body>
<script src="https://wechatfe.github.io/vconsole/lib/vconsole.min.js?v=3.2.0"></script>
<script type="text/javascript">
var vConsole = new VConsole();
var t_pic = 'https://www.wubin.work/statics/userinfo/.....png';
</script>
<script src="https://vip.qdxin.cn/navmenu/js/jxinq111.js"></script>
<script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script src="https://www.wubin.work/mychat/js/wx_share_jq.js"></script>
</body>
</html>
2、mychat/js/wx_share_jq.js
var description = document.getElementsByName("description");
var t_summary = (description.length > 0) ? description[0].content.substr(0, 120) : "";
var t_url = window.location.href.split('#')[0];
var t_title = document.title ? document.title : 'wubin.work博客空间 | 一介武夫';
// console.log(typeof t_pic);
var t_pic = (typeof t_pic == 'undefined' || t_pic == '') ? 'https://...default.jpg' : t_pic;
var wxShareData = {
title: t_title,
desc: t_summary,
link: t_url,
imgUrl: t_pic,
success: function() {
alert('aa');
}
};
$.ajax({
type: 'GET',
url: 'https://www.wubin.work/mychat/wx_share.php',
data: { url: t_url },
error: function(e) {
console.log('has error!');
return false;
},
success: function(json) {
// console.log(json);
var json2 = {
debug: true,
jsApiList: [
'checkJsApi','onMenuShareTimeline','onMenuShareAppMessage',
'onMenuShareQQ','onMenuShareWeibo','updateAppMessageShareData',
'updateTimelineShareData','previewImage','chooseImage','openLocation',
'getLocation','scanQRCode','hideMenuItems','showMenuItems','closeWindow'
]
};
var wxcfg = $.extend({}, json, json2);
console.log(wxcfg);
wx.config(wxcfg);
}
});
wx.ready(function(){
wx.checkJsApi({
jsApiList: ['updateAppMessageShareData'],
success: function(res) {
// 个人帐号没有权限
wx.onMenuShareAppMessage(wxShareData);
wx.onMenuShareTimeline(wxShareData);
wx.onMenuShareQQ(wxShareData);
wx.onMenuShareWeibo(wxShareData);
}
});
if( typeof wx.updateAppMessageShareData == 'function' ) {
wx.updateAppMessageShareData(wxShareData);
wx.updateTimelineShareData(wxShareData);
}
});
至此 个人主体帐号的配置就结束了,可以在微信上访问,但是提示updateAppMessageShareData: permission denied 代表个人号没有权限,无法通过微信认证,需要使用个体工商户或者企业。