1:绑定JS安全域名
登陆微信公众平台,点击"公众号设置"->"功能设置"->"设置"。(测试号绑定方法:进入测试号管理页面,找到JS接口安全域名项绑定)
绑定域名前,首先根据公众平台的提示将指定的txt文件上传到将要设置的域名对应的目录下,并给777权限。
域名格式:这里填写的是一级域名,不带www和http;最多可以设置三个域名;如果你的项目域名是http://test.domain.com,那么JS接口安全域名为test.domain.com;设置完后点击确定。
域名绑定失败或者域名不存在会报错误:invalid url domain
JS接口安全域名官方说法是:开发者可在该域名下调用微信开放的JS接口
(相比以前的分享没有任何域名限制,这里设置安全域名,目的是为了当发现此公众平台发现诱导分享行为时,可以根据此域名追溯到所有分享出去的链接,以及通过这些链接增加的粉丝。这样,微信就可以牢牢控制了你的微信平台,一旦发现违规,让分享链接失效,删除掉诱导行为增加的粉丝,是瞬间就可以完成的。)
2:在开发者中心中获取AppID和AppSecret(作为获取令牌使用)
注意:生成AppSecret后,关闭当前页面之后,公众平台将不再储存和显示AppSecrec,请妥善保存。
3:前端代码
<!--分享代码开始-->
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script>
var res = {liveflag:"true","title":"今日话题:“天降”芒果雨 小车砸大坑 酸爽!","globalid":"1012743","url":"","image":"http://liuxin.com.cn/images/2018/6/29/20186291530249564644_31.jpg","summary":"今日话题:“天降”芒果雨 小车砸大坑 酸爽!"};
function item_info(){
return JSON.stringify(res);
}
try {
window.share.shareData(JSON.stringify(res));
} catch(e) {
}
//微信相关代码
wx.error(function (res) {
//alert(res.errMsg);
});
wx.ready(function () {
// 获取“分享到朋友圈”按钮点击状态及自定义分享内容接口
wx.onMenuShareTimeline({
title: '今日话题:“天降”芒果雨 小车砸大坑 酸爽!', // 分享标题
desc: "今日话题:“天降”芒果雨 小车砸大坑 酸爽!",
link: "",
imgUrl: "http://liuxin.com.cn/images/2018/6/29/20186291530249564644_31.jpg", // 分享图标
success: function () {
alert("分享成功!");
}
});
// 获取“分享给朋友”按钮点击状态及自定义分享内容接口
wx.onMenuShareAppMessage({
title: '今日话题:“天降”芒果雨 小车砸大坑 酸爽!',
desc: "今日话题:“天降”芒果雨 小车砸大坑 酸爽!",
link: "",
imgUrl: "http://liuxin.com.cn/images/2018/6/29/20186291530249564644_31.jpg",
type: 'link',
success: function () {
alert("分享成功!");
}
});
// 获取“分享到QQ好友”按钮点击状态及自定义分享内容接口
wx.onMenuShareQQ({
title: '今日话题:“天降”芒果雨 小车砸大坑 酸爽!',
desc: '今日话题:“天降”芒果雨 小车砸大坑 酸爽!',
link: '',
imgUrl: 'http://liuxin.com.cn/images/2018/6/29/20186291530249564644_31.jpg',
success: function (res) {
alert('已分享');
}
});
});
var pImg = "http://liuxin.com.cn/images/2018/6/29/20186291530249564644_31.jpg";
$.ajax({
type: "GET",
data: " ",
url: "http://liuxin.com.cn/apiv1.2/wx_sign.php?callback=?",
dataType: 'jsonp',
success: function (data) {
console.log(data.status);
console.log(data);
wx.config({
debug: false,
appId: data.result.appId,
timestamp: data.result.timestamp,
nonceStr: data.result.nonceStr,
signature: data.result.signature,
jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone']
});
},
error: function () {
alert("接口请求失败!");
}
});
</script>
<!--分享代码结束-->
4:php代码
wx_sign.php
<?php
$callback=empty($_REQUEST['callback'])?"":$_REQUEST['callback'];
require_once "jssdk.php";
$jssdk = new JSSDK(YOURAPPID, YOURAPPSECRET);
$signPackage = $jssdk->GetSignPackage();
echo_arr(array("status"=>1,"message"=>"成功","result"=>$signPackage));
jssdk.php
<?php
class JSSDK {
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]";
if($_SERVER["HTTP_REFERER"]){
$url = $_SERVER["HTTP_REFERER"];
}
$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() {
// jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
$data = json_decode($this->get_php_file("jsapi_ticket.php"));
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;
$this->set_php_file("jsapi_ticket.php", json_encode($data));
}
} else {
$ticket = $data->jsapi_ticket;
}
return $ticket;
}
private function getAccessToken() {
// access_token 应该全局存储与更新,以下代码以写入到文件中做示例
$data = json_decode($this->get_php_file("access_token.php"));
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;
$this->set_php_file("access_token.php", json_encode($data));
}
} else {
$access_token = $data->access_token;
}
return $access_token;
}
private function httpGet($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
// 为保证第三方服务器与微信服务器之间数据传输的安全性,所有微信接口采用https方式调用,必须使用下面2行代码打开ssl安全校验。
// 如果在部署过程中代码在此处验证失败,请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
curl_setopt($curl, CURLOPT_URL, $url);
$res = curl_exec($curl);
curl_close($curl);
return $res;
}
private function get_php_file($filename) {
return trim(substr(file_get_contents($filename), 15));
}
private function set_php_file($filename, $content) {
$fp = fopen($filename, "w");
fwrite($fp, "<?php exit();?>" . $content);
fclose($fp);
}
}
PS:做完以上步骤之后,分享还是不能显示分享信息怎么办呢?
首先:打开微信分享的调试模式,在上边写的js代码中(注意调试结束后要记得关掉哦)
然后点击分享就会调试信息啦
常见的问题有:
1、invalid url domain:
js接口安全域名错误
2、invalid signature:
要么是jsapi_ticket错误,要么是签名算法问题,要么是算法的参数有问题,注意noncestr中的's'是小写的,再就是查看html页面中调用的php接口地址的返回值,将对应的返回值填到 微信JS接口签名校验工具中看最终返回值和接口中的返回值是否一致。
微信 JS 接口签名校验工具
https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign
3、permission denied:
这个问题一般是没有接口权限的问题,有的接口是要认证之后才可以使用,当然,测试号不会有这个问题
4、配置完毕之后,分享出来显示【操作过于频繁,可稍后再试。】
此时需要查看,分享出来页面地址是否为域名访问的(并且域名是否为微信公众平台中配置的安全域名),需要使用正确的域名访问才可使用微信二次分享