微信小程序要获取用户的openid,首先要获取到code,再用code获取openid
第一步:小程序调用wx.login方法获取到code
wx.login({
success (res) {
if (res.code) {
//发起网络请求
wx.request({
url: 'https://test.com/onLogin',
data: {
code: res.code
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
success (res) {
if (res.code) {
//发起网络请求
wx.request({
url: 'https://test.com/onLogin',
data: {
code: res.code
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
第二步:用code去获取openid
//请求接口地址的方法
function http_Get($url){
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,trim($url));
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl,CURLOPT_HEADER,0);
curl_setopt($curl,CURLOPT_CUSTOMREQUEST,'GET');//需要要传送的内容
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
$return_str = curl_exec($curl);
curl_close($curl);
return $return_str;
}
$appid = 'wxf4809253b0aefcd2';//这里换成自己小程序的appid
$secret = 'db908f78f695e21e21a02fe4dd67a8f8';//这里换成自己小程序的secret
$url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';//url里的$code就是第一步获取的code
$json = http_Get($url);
$arr = json_decode($json,true);
$openid = $arr['openid'];//用户的openid
function http_Get($url){
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,trim($url));
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl,CURLOPT_HEADER,0);
curl_setopt($curl,CURLOPT_CUSTOMREQUEST,'GET');//需要要传送的内容
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
$return_str = curl_exec($curl);
curl_close($curl);
return $return_str;
}
$appid = 'wxf4809253b0aefcd2';//这里换成自己小程序的appid
$secret = 'db908f78f695e21e21a02fe4dd67a8f8';//这里换成自己小程序的secret
$url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';//url里的$code就是第一步获取的code
$json = http_Get($url);
$arr = json_decode($json,true);
$openid = $arr['openid'];//用户的openid
注意事项:
第二步非常要注意的一点就是,网页授权获取openid的接口地址和小程序获取openid的接口地址不一样,这里要特别注意,不然小程序会报errcode:48001错误
网页授权获取openid的接口地址:
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
小程序获取openid的接口地址:
https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code