网站使用JS-SDK自定义微信分享内容实例
发布日期:2019年01月04日,网站分类:网站新闻
前几天朋友需要自定义微信分享内容,那时候没时间搞,大概的发了个微信的官方文档。今天来套简单的调用微信自带的JS-SDK,现在的思路已经很明确了,就是通过调用微信的JS-SDK实现自定义分享效果。
但是这个调用过程比较繁琐,需要提前准备如下东西:
1.微信认证服务号,2.网站域名
这个域名需要设置为微信公众号后台的JS接口安全域名,否则微信仍然不允许调用它的接口。

然后我们需要到公众号获取查看AppId,AppSecret以及绑定域名IP。

这里需要注意是http还是https,如果生产环境是https,务必前缀是https,都则会出现mix content这样的错误,导致引入失败。
<script typet="text/javascript" src="//res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
通过AppId和AppSecret请求accessToken,然后通过accessToken获取jsapi_ticket,生成config接口所需参数。
jssdk.php:
<?php
class wx_share {
private $appId;
private $appSecret;
public function __construct($appId, $appSecret) {
$this->appId = $appId;
$this->appSecret = $appSecret;
}
public function getSignPackage() {
$jsapiTicket = $this->getJsApiTicket();
// 注意 URL 一定要动态获取,不能 hardcode.
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$timestamp = time();
$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,
"rawString" => $string
);
return $signPackage;
}
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;
}
private function getJsApiTicket() {
global $zbp;
$file_path = $zbp->host.'zb_users/plugin/wx_share/jsapi_ticket.json';
//$json = file_get_contents($file_path);
$ajax = Network::Create();
if (!$ajax) {
throw new Exception('主机没有开启网络功能');
}
$ajax->open('GET', $file_path);
$ajax->setRequestHeader('Content-Type', 'text/plain');
$ajax->send($file_path);
$json =$ajax->responseText;
$data =json_decode($json,true);
if ($data['expire_time'] < time()) {
$accessToken = $this->getAccessToken();
// 如果是企业号用以下 URL 获取 ticket
// $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
$res = json_decode($this->httpGet($url));
$ticket = $res->ticket;
if ($ticket) {
$data['expire_time'] = time() + 7000;
$data['jsapi_ticket'] = $ticket;
$fp = fopen($zbp->path."zb_users/plugin/wx_share/jsapi_ticket.json", "w");
fwrite($fp, json_encode($data));
fclose($fp);
}
} else {
$ticket = $data['jsapi_ticket'];
}
return $ticket;
}
private function getAccessToken() {
global $zbp;
$file_path = $zbp->host.'zb_users/plugin/wx_share/access_token.json';
//$json = file_get_contents($file_path);
$ajax = Network::Create();
if (!$ajax) {
throw new Exception('主机没有开启网络功能');
}
$ajax->open('GET', $file_path);
$ajax->setRequestHeader('Content-Type', 'text/plain');
$ajax->send($file_path);
$json =$ajax->responseText;
$data =json_decode($json,true);
if ($data['expire_time'] < time()) {
// 如果是企业号用以下URL获取access_token
// $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
$res = json_decode($this->httpGet($url));
$access_token = $res->access_token;
if ($access_token) {
$data['expire_time'] = time() + 7000;
$data['access_token'] = $access_token;
$fp = fopen($zbp->path."zb_users/plugin/wx_share/access_token.json", "w");
fwrite($fp, json_encode($data));
fclose($fp);
}
} else {
$access_token = $data['access_token'];
}
return $access_token;
}
private function httpGet($url) {
$ajax = Network::Create();
if (!$ajax) {
throw new Exception('主机没有开启网络功能');
}
$ajax->open('POST', $url);
$ajax->setRequestHeader('Content-Type', 'text/plain');
$ajax->send($url);
$res =$ajax->responseText;
return $res;
}
}getPageType.php,接口处理:
$jssdk = new wx_share($zbp->Config('wx_share')->AppID, $zbp->Config('wx_share')->AppSecret);
$signPackage = $jssdk->GetSignPackage();
echo "
<script>
var pageUrl = window.location.href,
pageTitle = document.title,
meta = document.getElementsByTagName('meta'),
pageDesc = '';
for(i in meta){
if(typeof meta[i].name!='undefined'&&meta[i].name.toLowerCase()=='description'){
pageDesc = meta[i].content;
}
}
wx.config({
debug: false,
appId: '{$signPackage['appId']}',
timestamp: {$signPackage['timestamp']},
nonceStr: '{$signPackage['nonceStr']}',
signature: '{$signPackage['signature']}',
jsApiList: [
'checkJsApi', //判断当前客户端版本是否支持指定JS接口
'onMenuShareTimeline', //分享给好友
'onMenuShareAppMessage', //分享到朋友圈
'onMenuShareQQ', //分享到QQ
'onMenuShareWeibo' //分享到微博
]
});
wx.ready(function () {
//分享到朋友圈
wx.onMenuShareTimeline({
title: pageTitle,
desc: pageDesc,
link: pageUrl,";
if($type=='article'||$type=='page'){
$pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/";
$content = $article->Content;
preg_match_all($pattern,$content,$matchContent);
if(isset($matchContent[1][0])){
echo 'imgUrl: "'.$matchContent[1][0].'",';
}else{
echo 'imgUrl: "'.$zbp->Config('wx_share')->WxImage.'",';
}
}else{
echo 'imgUrl: "'.$zbp->Config('wx_share')->WxImage.'",';
}
echo "success: function () {
// 用户确认分享后执行的回调函数
},
cancel: function () {
// 用户取消分享后执行的回调函数
}
});
//分享给朋友
wx.onMenuShareAppMessage({
title: pageTitle,
desc: pageDesc,
link: pageUrl,";
if($type=='article'||$type=='page'){
$pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/";
$content = $article->Content;
preg_match_all($pattern,$content,$matchContent);
if(isset($matchContent[1][0])){
echo 'imgUrl: "'.$matchContent[1][0].'",';
}else{
echo 'imgUrl: "'.$zbp->Config('wx_share')->WxImage.'",';
}
}else{
echo 'imgUrl: "'.$zbp->Config('wx_share')->WxImage.'",';
}
echo "success: function () {
// 用户确认分享后执行的回调函数
},
cancel: function () {
// 用户取消分享后执行的回调函数
}
});
//分享到QQ
wx.onMenuShareQQ({
title: pageTitle,
desc: pageDesc,
link: pageUrl,";
if($type=='article'||$type=='page'){
$pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/";
$content = $article->Content;
preg_match_all($pattern,$content,$matchContent);
if(isset($matchContent[1][0])){
echo 'imgUrl: "'.$matchContent[1][0].'",';
}else{
echo 'imgUrl: "'.$zbp->Config('wx_share')->WxImage.'",';
}
}else{
echo 'imgUrl: "'.$zbp->Config('wx_share')->WxImage.'",';
}
echo "success: function () {
// 用户确认分享后执行的回调函数
},
cancel: function () {
// 用户取消分享后执行的回调函数
}
});
//分享到腾讯微博
wx.onMenuShareWeibo({
title: pageTitle,
desc: pageDesc,
link: pageUrl,";
if($type=='article'||$type=='page'){
$pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/";
$content = $article->Content;
preg_match_all($pattern,$content,$matchContent);
if(isset($matchContent[1][0])){
echo 'imgUrl: "'.$matchContent[1][0].'",';
}else{
echo 'imgUrl: "'.$zbp->Config('wx_share')->WxImage.'",';
}
}else{
echo 'imgUrl: "'.$zbp->Config('wx_share')->WxImage.'",';
}
echo "success: function () {
// 用户确认分享后执行的回调函数
},
cancel: function () {
// 用户取消分享后执行的回调函数
}
});
//分享到QQ空间
wx.onMenuShareQZone({
title: pageTitle,
desc: pageDesc,
link: pageUrl,";
if($type=='article'||$type=='page'){
$pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/";
$content = $article->Content;
preg_match_all($pattern,$content,$matchContent);
if(isset($matchContent[1][0])){
echo 'imgUrl: "'.$matchContent[1][0].'",';
}else{
echo 'imgUrl: "'.$zbp->Config('wx_share')->WxImage.'",';
}
}else{
echo 'imgUrl: "'.$zbp->Config('wx_share')->WxImage.'",';
}
echo "success: function () {
// 用户确认分享后执行的回调函数
},
cancel: function () {
// 用户取消分享后执行的回调函数
}
});
});
wx.error(function (res) {
alert(res.errMsg);
});
</script>
";制作成功后的效果图:

代码为核心代码,基本修改都是通用的,小白跳过,不要用客服系统问我,jsapi_ticket.json,access_token.json自己去搞,不多解释!
关键词:网站优化
转载请注明来自:https://www.kufan.cn/news/241.html
