App({
globalData:{
appid:'XXXX',
secret:'XXXX',
},
onLaunch: function () {
var that = this
var userInfo=wx.getStorageSync('userInfo') || {};
wx.login({
success: function(res){
if(res.code) {
var c = res.code;
var l='https://api.XXXX.com/openid/index.php';
wx.request({
url: l,
data: {
code:res.code,
},
method: 'GET',
success: function(res){
console.log(res);
var openid = res.data['openid'];
wx.setStorageSync('openid', openid);
}
});
}else {
console.log('获取用户登录态失败!' + res.errMsg)
}
}
});
}
})
index.php
<?php
$appid = "xxx";
$secret = "xxx";
$code = $_GET["code"];
$url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
// 为保证第三方服务器与微信服务器之间数据传输的安全性,所有微信接口采用https方式调用,必须使用下面2行代码打开ssl安全校验。
// 如果在部署过程中代码在此处验证失败,请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
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);
$json_obj = json_decode($res,true);
$openid=$json_obj["openid"];
$data['openId']=$openid;
die(json_encode($data));
?>