PhoneLogin.php 2.8 KB
<?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;
    }

}