首先在官網(wǎng)下載示例代碼, 選php的,
這里有個(gè)坑
官方的php文件,編碼是UTF-8+的, 所以要把文件改為UTF-8
然后在Thinkphp5 extend文件夾下建立Wxxcx命名空間,把官方的幾個(gè)類文件放進(jìn)去(這里要注意文件夾名, 命名空間名, 類名的, 大小寫,一定要一樣,官方的文件名和類名大小寫不一樣)
然后是自己的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封裝函數(shù):
-
-
-
-
-
-
-
-
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('不支持的請(qǐng)求方式!');
-
}
-
-
$ch = curl_init();
-
curl_setopt_array($ch, $opts);
-
$data = curl_exec($ch);
-
$error = curl_error($ch);
-
curl_close($ch);
-
if($error) throw new Exception('請(qǐng)求發(fā)生錯(cuò)誤:' . $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://你的服務(wù)器地址/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)
-
}
-
}
-
})
-
}
-
}
-
})
-
},
如果有報(bào)錯(cuò), 自己調(diào)試一下, 看看哪里的變量有問題 查找原因.