PhoneLogin.php
2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
/**
* Created by PhpStorm.
* Login: Kevin
* Date: 2022/06/12
* Time: 15:34
*/
namespace app\api\controller\v1;
use lib\WXBizDataCrypt;
use think\Db;
use think\Request;
header('Access-Control-Allow-Origin:*');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');
class PhoneLogin extends Base
{ /**
* 12.小程序授权注册用户、返回用户信息
*/
public function get_user_by_shouquan()
{
$user_id=$this->auth->id;
$appid = $this->AppID;
$AppSecret = $this->AppSecret;
$post = $this->request->post();
$code = $post['code'];// I('post.code');
$AccessToken=$this->getwxAccessToken($appid,$AppSecret);
$phone=$this->getwxPhoneNumber($code,$AccessToken);
$phone=json_decode($phone,true);
$moblie=$phone['phoneNumber'];
if($moblie){
Db::name("user")->where("id", $user_id)->update(["moblie" => $moblie]);
}else{
$this->error("无法获取手机号,登录失败");
}
}
//获取accesstoken
function getwxAccessToken($appid,$AppSecret){
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$AppSecret."";
$res = json_decode(http_request($url), true);
return $res;
}
//获取手机号
function getwxPhoneNumber($code,$token)
{
$token =$token['access_token'];
$data['code'] = $code;//前端获取code
$url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";
$info = $this->Post(json_encode($data),$url);
// 一定要注意转json,否则汇报47001错误
$tmpinfo = json_decode($info);
$code = $tmpinfo->errcode;
$phone_info = $tmpinfo->phone_info;
//手机号
$phoneNumber = $phone_info->phoneNumber ;
if ($code == '0') {
return json_encode(['code' => 1, 'msg' => '请求成功', 'phoneNumber' => $phoneNumber]);
} else {
return json_encode($tmpinfo);
}
}
function Post($curlPost, $url, $ssl = false)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
if (!$ssl) {
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
}
$return_str = curl_exec($curl);
curl_close($curl);
return $return_str;
}
}