说明:本方法是PHP版本的,java 等类似步骤实现即可!
1、注册账号 https://mp.weixin.qq.com ,获取 appID appSecret
2、配置 appID appSecret LoginUrl
//1、配置
$AppID = '***';
$AppSecret = '***';
$LoginUrl = "https://api.weixin.qq.com/sns/jscode2session?" .
"appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
2、获取code,此code由小程序传递过来
$code = $_GET['code']; //此code为小程序提供
3、拼接LoginUrl
$wxLoginUrl = sprintf($LoginUrl,$AppID,$AppSecret,$code);
4、通过curl获取 openid session_key
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//不做证书校验,部署在linux上环境下需要改为true
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
$file_contents = curl_exec($curl);
$httpCode = curl_getinfo($curl,CURLINFO_HTTP_CODE);
curl_close($curl);
5、获取到 openid session_key
$wxResult = json_decode($file_contents,true);
6、判断wxResult是否含有errcode字段,如果有则返回false,没有则继续
//Array ( [errcode] => 40029 [errmsg] => invalid code, hints: [ req_id: oFAcqZyFe-8MWOTa ] )//错误的返回信息会包含errcode字段
if (array_key_exists('errcode',$wxResult);){
return false;
}
7、如果没有错误,则获取openid
//Array ( [session_key] => /+Xq0PzVXvBzxL3Xz/zzjA== [expires_in] => 7200 [openid] => oPPr80M******umQ5g86*****k )//正确返回信息包含 session_key openid expires_in
$openid = $wxResult['openid'];
8、判断数据库中是否存在openid 存在则忽略,不存在则创建
$user = User::where('openid'$openid)->find();
if ($user){
$uid = $user->id;
}else{
$user = UserModel::create(['openid',$openid]);
$uid = $user->id
}
9、准备要缓存的数据
$cachedValue = $wxResult;
$cachedValue['uid'] = $uid;
$cachedValue['scope'] = 16;
10、写入缓存
$key = md5(getRandChar(32).$_SERVER['REQUEST_TIME_FLOAT'].config('secure.token_salt')); //生成随机Token
$value = json_encode($cachedValue); //转为json对象
$expire_in = config('setting.token_expire_in'); //设置过期时间
$request = cache($key,$value,$expire_in); //缓存数据
附:code获取方式(小程序中)
wxml
<button type="primary" bindtap="getToken">申请令牌</button>
index.js中
var app = getApp()
var baseUrl = 'https://thinkp.cn/api/v1'; //thinkp.cn为配置的合法request域名
Page({
onLoad: function () {
},
getToken: function () {
//调用登录接口
wx.login({
success: function (res) {
var code = res.code;
console.log('code');
console.log(code); //打印出code
wx.request({
url: baseUrl + '/token/user', // 路由
data: {
code: code
},
method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
success: function (res) {
console.log(res.data);
wx.setStorageSync('token', res.data.token);
},
fail: function (res) {
console.log(res.data);
}
})
}
})
},
})
注:
code只能使用1次:
如果使用多次则会报错:
{"msg":"code been used, hints: [ req_id: TFAcn6yFe-_aD_aa ]","error_code":40163,"request_url":"\/api\/v1\/token\/user?code=08*555Yp0a9pam1mGidm1OV4di"}