首先在官网下载示例代码, 选php的,
这里有个坑
官方的php文件,编码是UTF-8+的, 所以要把文件改为UTF-8
然后在Thinkphp5 extend文件夹下建立Wxxcx命名空间,把官方的几个类文件放进去(这里要注意文件夹名, 命名空间名, 类名的, 大小写,一定要一样,官方的文件名和类名大小写不一样)
然后是自己的thinkphp接口代码:
-
<?php
-
-
-
-
-
-
-
-
namespace app\api\controller\v1;
-
-
-
use think\Loader;
-
use think\Request;
-
use Workerman\Protocols\Http;
-
use Wxxcx\WXBizDataCrypt;
-
use first\second\Foo;
-
-
class Index
-
{
-
public function index($id)
-
{
-
-
return json(['msg' => $id]);
-
}
-
-
public function dologin()
-
{
-
$code = Request::instance()->param('code');
-
$encryptedData = Request::instance()->param('encryptedData');
-
$iv = Request::instance()->param('iv');
-
-
$appid = "你的小程序appid";
-
$secret = "你的小程序secret";
-
-
$param = array(
-
'appid' => $appid,
-
'secret' => $secret,
-
'js_code' => $code,
-
'grant_type' => 'authorization_code'
-
);
-
-
$res = http("https://api.weixin.qq.com/sns/jscode2session", $param, 'post');
-
-
$arr = json_decode($res, true);
-
-
$result = $this->wxdecode($encryptedData, $iv, $arr['session_key'], $appid);
-
-
-
if ($result) {
-
return json(['code' => 1]);
-
} else {
-
return json(['code' => -1]);
-
}
-
-
}
-
-
public function wxdecode($encryptedData, $iv, $sessionKey, $appid)
-
{
-
-
$pc = new WXBizDataCrypt($appid, $sessionKey);
-
$data = null;
-
$errCode = $pc->decryptData($encryptedData, $iv, $data);
-
-
-
$data = json_decode($data);
-
-
if ($errCode == 0) {
-
-
-
return $data;
-
} else {
-
-
-
return $errCode;
-
}
-
-
}
-
}
http封装函数:
-
-
-
-
-
-
-
-
function http($url, $params, $method = 'GET', $header = array(), $multi = false){
-
$opts = array(
-
CURLOPT_TIMEOUT => 30,
-
CURLOPT_RETURNTRANSFER => 1,
-
CURLOPT_SSL_VERIFYPEER => false,
-
CURLOPT_SSL_VERIFYHOST => false,
-
CURLOPT_HTTPHEADER => $header
-
);
-
-
switch(strtoupper($method)){
-
case 'GET':
-
$opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
-
break;
-
case 'POST':
-
-
$params = $multi ? $params : http_build_query($params);
-
$opts[CURLOPT_URL] = $url;
-
$opts[CURLOPT_POST] = 1;
-
$opts[CURLOPT_POSTFIELDS] = $params;
-
break;
-
default:
-
throw new Exception('不支持的请求方式!');
-
}
-
-
$ch = curl_init();
-
curl_setopt_array($ch, $opts);
-
$data = curl_exec($ch);
-
$error = curl_error($ch);
-
curl_close($ch);
-
if($error) throw new Exception('请求发生错误:' . $error);
-
return $data;
-
}
然后是小程序的代码:
-
-
wx.getSetting({
-
success: res => {
-
if (res.authSetting['scope.userInfo']) {
-
-
wx.getUserInfo({
-
success: res => {
-
console.log(res);
-
var encryptedData = res.encryptedData
-
var iv = res.iv
-
wx.request({
-
url: "https://你的服务器地址/dologin",//dologin是访问后端的方法
-
method: "post",
-
data: {
-
code: code,
-
encryptedData: encryptedData,
-
iv: iv
-
},
-
success: function (ret) {
-
console.log(ret);
-
}
-
})
-
-
-
-
this.globalData.userInfo = res.userInfo
-
-
-
-
if (this.userInfoReadyCallback) {
-
this.userInfoReadyCallback(res)
-
}
-
}
-
})
-
}
-
}
-
})
-
},
如果有报错, 自己调试一下, 看看哪里的变量有问题 查找原因.