前端:微信先授权登录后再授权获取手机号码
后端:先微信登录获取openid返回前端,前端再传递手机号码code给后端获取手机号码并在本地数据量注册用户信息,需提供2个接口
第一步:先通过code微信授权登录获取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' => '微信获取授权失败'];
}
$result = json_decode($this->curl->response,true);
if (isset($result['openid']) && $result['openid'] != '') {
return ['status' => 1, 'msg' => '成功', 'data' => $result];
}else{
return ['status' => 0, 'msg' => '微信获取授权失败-' . $result['errmsg']];
}
第二步:根据app_id和app_secret获取access_token文章来源:https://www.toymoban.com/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);
第三步:根据前端获取到的允许获取手机号的code和后端获取到的access_token通过api获取手机号码文章来源地址https://www.toymoban.com/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']];
}
到了这里,关于微信小程序登录及获取手机号码的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!