一、使用wx.login获取code值,wx.getUserInfo获取encryptedData、rawData、signature,使用wx.request去php请求数据。(如果你的小程序没有绑定微信开放平台,解密的数据中不包含unionid参数)
wx.login({
success:function(res){
var code = res.code;
wx.getUserInfo({
success: function (res) {
var encryptedData = res.encryptedData;
var rawData = res.rawData;
var signature = res.signature;
var iv = res.iv;
wx.request({
url: 'https链接,请求地址',
data: {
encryptedData: encryptedData,
code: code,
signature: signature,
rawData: rawData,
iv:iv
},
method: "POST",
header: { 'content-type':'application/x-www-form-urlencoded' },
success: function (res) {
console.log(res.data);
},
fail: function (e) {
cosole.log(e);
}
});
}
});
}
})
二、php处理代码(wxBizDataCrypt.php注意php7以上版本需要修改)
<?php
include_once "wxBizDataCrypt.php";
$js_code=$_POST["code"];
$encryptedData=$_POST["encryptedData"];
$signature=$_POST["signature"];
$rawData=$_POST["rawData"];
$iv = $_POST["iv"];
$appid = 'appid';
$appSecret="appSecret";
$str = file_get_contents('https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$appSecret.'&js_code='.$js_code.'&grant_type=authorization_code');
$str=json_decode($str);
/*print_r($str);*/
$sessionKey=$str->session_key;
$signature2=sha1($rawData.$sessionKey);
if($signature!=$signature2){
$arr=array("code"=>3);
exit(json_encode($arr));
}
$pc = new WXBizDataCrypt($appid, $sessionKey);
$errCode = $pc->decryptData($encryptedData, $iv, $data );
if ($errCode == 0) {
print($data);
} else {
print($errCode);
}
注:wxBizDataCrypt.php可以在开发者文档里面找到下载链接(框架-开放数据校验与解密)
wxBizDataCrypt.php下载:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/demo/aes-sample.zip