HTML静态页面通过Ajax使用微信JS-SDK获取返回信息,会提示config:invalid signature错误。这是因为签名不匹配,微信官方的演示代码中url是获取的php当前url,并不是html静态页面的url。(以下为微信JS-SDK使用权限签名算法)
签名生成规则如下:参与签名的字段包括noncestr(随机字符串), 有效的jsapi_ticket, timestamp(时间戳), url(当前网页的URL,不包含#及其后面部分) 。对所有待签名参数按照字段名的ASCII 码从小到大排序(字典序)后,使用URL键值对的格式(即key1=value1&key2=value2…)拼接成字符串string1。这里需要注意的是所有参数名均为小写字符。对string1作sha1加密,字段名和字段值都采用原始值,不进行URL 转义。
注意:把url作为参数进行ajax传递时需要进行urlencode,js-sdk接收后再urldecode。
一、静态文件,如index.html
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script>
var localurl=URLEncode(location.href);
$.ajax({
type : "get",
url : "wxsdk/wxjs.php?url="+localurl,//替换网址
dataType : "jsonp",
jsonp: "callback",
jsonpCallback:"success_jsonpCallback",
success : function(data){
wx.config({
debug: false,
appId: data.appId,
timestamp: data.timestamp,
nonceStr: data.nonceStr,
signature: data.signature,
jsApiList: [
'checkJsApi', //判断当前客户端版本是否支持指定JS接口
'onMenuShareTimeline', //分享给好友
'onMenuShareAppMessage', //分享到朋友圈
'onMenuShareQQ', //分享到QQ
'onMenuShareWeibo' //分享到微博
]
});
wx.ready(function () {
wx.onMenuShareTimeline({ //例如分享到朋友圈的API
title: '第二届河北农业品牌系列评选', // 分享标题
link: window.location.href, // 分享链接
imgUrl: 'http://apps.hebnews.cn/hudong/tp/images/header.jpg', // 分享图标
success: function () {
// 用户确认分享后执行的回调函数
},
cancel: function () {
// 用户取消分享后执行的回调函数
}
});
wx.onMenuShareAppMessage({// 分享给微信好友
title: '第二届河北农业品牌系列评选', // 分享标题
desc: '为贯彻落实2017年省委一号文件精神和《河北省农产品品牌建设推进方案》的要求,建立河...', // 分享描述
link: window.location.href, // 分享链接
imgUrl: 'http://apps.hebnews.cn/hudong/tp/images/header.jpg', // 分享图标
type: '', //此项无需填写(分享类型,music、video或link,不填默认为link)
dataUrl: '', //此项无需填写(如果type是music或video,则要提供数据链接,默认为空)
success: function () { // 分享成功后的事件
//window.location.href="http://跳转的网址";
},
cancel: function () {
}
});
wx.onMenuShareQQ({// 分享到QQ
title: '第二届河北农业品牌系列评选', // 分享标题
desc: '为贯彻落实2017年省委一号文件精神和《河北省农产品品牌建设推进方案》的要求,建立河...', // 分享描述
link: window.location.href, // 分享链接
imgUrl: 'http://apps.hebnews.cn/hudong/tp/images/header.jpg', // 分享图标
success: function () { // 分享成功后的事件
//window.location.href="http://跳转的网址";
},
cancel: function () {
}
});
});
/*
wx.error(function (res) {
alert(res.errMsg); //打印错误消息。及把 debug:false,设置为debug:ture就可以直接在网页上看到弹出的错误提示
});
*/
},
error:function(data){
alert("连接失败!");
}
});
function URLEncode (clearString) {
var output = '';
var x = 0;
clearString = clearString.toString();
var regex = /(^[a-zA-Z0-9-_.]*)/;
while (x < clearString.length) {
var match = regex.exec(clearString.substr(x));
if (match != null && match.length > 1 && match[1] != '') {
output += match[1];
x += match[1].length;
} else {
if (clearString.substr(x, 1) == ' ') {
//原文在此用 clearString[x] == ' ' 做判断, 但ie不支持把字符串当作数组来访问,
//修改后两种浏览器都可兼容
output += '+';
}
else {
var charCode = clearString.charCodeAt(x);
var hexVal = charCode.toString(16);
output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
}
x++;
}
}
return output;
}
</script>
二、微信JS-SDK,如wxjs.php
<?php
class JSSDK {
private $appId;
private $appSecret;
private $url;
public function __construct($appId, $appSecret,$url) {
$this->appId = $appId;
$this->appSecret = $appSecret;
$this->url = $url;
}
public function getSignPackage() {
$jsapiTicket = $this->getJsApiTicket();
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
// $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$url =$this->url;
$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(file_get_contents("jsapi_ticket.json"));
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("jsapi_ticket.json", "w");
fwrite($fp, json_encode($data));
fclose($fp);
}
} else {
$ticket = $data->jsapi_ticket;
}
return $ticket;
}
private function getAccessToken() {
// access_token 应该全局存储与更新,以下代码以写入到文件中做示例
$data = json_decode(file_get_contents("access_token.json"));
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("access_token.json", "w");
fwrite($fp, json_encode($data));
fclose($fp);
}
} 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);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_URL, $url);
$res = curl_exec($curl);
curl_close($curl);
return $res;
}
}
$url = urldecode($_GET['url']); //请注意进行sql注入、特殊字符等安全处理。
$jssdk = new JSSDK("wxf01f8b81f36100f0d", "cf1de7a441ea490d3d1518d010668217",$url);
$signPackage = $jssdk->GetSignPackage();
$tmp=json_encode(array ('appId'=>$signPackage["appId"],'timestamp'=>$signPackage["timestamp"],'nonceStr'=>$signPackage["nonceStr"],'signature'=>$signPackage["signature"],'url'=>$signPackage["url"]));
$callback = $_GET['callback'];
echo $callback.'('.$tmp.')';
exit;
?>
静态页微信分享Demo |
除非注明,均为湛蓝天空原创,转载请注明本文网址:http://skyhome.cn/php/510.html