前端:微信先授權(quán)登錄后再授權(quán)獲取手機號碼
后端:先微信登錄獲取openid返回前端,前端再傳遞手機號碼code給后端獲取手機號碼并在本地數(shù)據(jù)量注冊用戶信息,需提供2個接口
第一步:先通過code微信授權(quán)登錄獲取openid
$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $this->appid . '&secret=' . $this->app_secret . '&js_code=' . $code . '&grant_type=authorization_code';
$this->curl->get($url);
if ($this->curl->error) {
return ['status' => 0, 'msg' => '微信獲取授權(quán)失敗'];
}
$result = json_decode($this->curl->response,true);
if (isset($result['openid']) && $result['openid'] != '') {
return ['status' => 1, 'msg' => '成功', 'data' => $result];
}else{
return ['status' => 0, 'msg' => '微信獲取授權(quán)失敗-' . $result['errmsg']];
}
第二步:根據(jù)app_id和app_secret獲取access_token文章來源:http://www.zghlxwxcb.cn/news/detail-529905.html
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->appid . '&secret=' . $this->app_secret;
$this->curl->get($url);
if ($this->curl->error) {
return ['status' => 0, 'msg' => '微信獲取access_token失敗'];
}
$result = json_decode($this->curl->response,true);
第三步:根據(jù)前端獲取到的允許獲取手機號的code和后端獲取到的access_token通過api獲取手機號碼文章來源地址http://www.zghlxwxcb.cn/news/detail-529905.html
$access_token = $this->getAccessToken($openid);
if($access_token['status'] == 0){
return ['status' => 0, 'msg' => $access_token['msg']];
}
$token = $access_token['data']['token'];
$url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $token;
$data['code'] = $code;
$this->curl->post($url, json_encode($data));
if ($this->curl->error) {
return ['status' => 0, 'msg' => '微信獲取用戶手機號失敗'];
}
$result = json_decode($this->curl->response, true);
if (isset($result['errcode']) && $result['errcode'] == 0) {
return ['status' => 1, 'msg' => '成功', 'data' => $result['phone_info']];
} else {
return ['status' => 0, 'msg' => '微信獲取用戶手機號失敗-' . $result['errmsg']];
}
到了這里,關(guān)于微信小程序登錄及獲取手機號碼的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!