移动应用微信登录接口

作者: wxfeng 分类: php,web前端 发布时间: 2022-04-29 13:46    阅读 272 次
    /**
     * 微信登录
     *
     * @ApiTitle    (微信登录)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/custom/user/welogin)
     * @ApiParams   (name="platform", type="string", required=true, description="平台名称")
     * @ApiParams   (name="code", type="string", required=true, description="Code码")
     */
    public function welogin()
    {
        $code                  = $this->request->post("code");
        $wechatTool            = new WeChatTool();
        $wechat_token_callback = $wechatTool->get_token($code);
        if (false == $wechat_token_callback || isset($wechat_token_callback['errcode'])) {
            $this->error('请求出错,请重试');
        }
        $wechat_user_callback = $wechatTool->get_user_info($wechat_token_callback['access_token'], $wechat_token_callback['openid']);
        if (false == $wechat_user_callback || isset($wechat_user_callback['errcode'])) {
            $this->error('获取用户数据出错,请重试');
        }
        $userinfo = \app\common\model\User::where(['app_openid' => $wechat_token_callback['openid']])->find();

        if ($userinfo) {
            $userinfo->nickname = $wechat_user_callback['nickname'];
            $userinfo->avatar   = $wechat_user_callback['headimgurl'];
            $userinfo->gender   = $wechat_user_callback['sex'];
            $userinfo->city     = $wechat_user_callback['city'];
            $userinfo->province = $wechat_user_callback['province'];
            $userinfo->country  = $wechat_user_callback['country'];
            $userinfo->save();
            $this->auth->direct($userinfo['id']);
        } else {
            $user = new \app\common\model\User();
            $user->data([
                'nickname'   => $wechat_user_callback['nickname'],
                'avatar'     => $wechat_user_callback['headimgurl'],
                'gender'     => $wechat_user_callback['sex'],
                'city'       => $wechat_user_callback['city'],
                'province'   => $wechat_user_callback['province'],
                'country'    => $wechat_user_callback['country'],
                'status'     => 'normal',
                'app_openid' => $wechat_user_callback['openid'],
                'unionid'    => $wechat_user_callback['unionid'],
            ]);
            $user->save();
            $this->auth->direct($user->id);
        }
        $this->success('登录成功', $this->auth->getUserinfo());
    }
use GuzzleHttp\Client;

class WeChatTool
{
    protected $config;

    public function __construct()
    {
        $this->config = [
            // 移动应用
            'app_id'            => 'wx***c52d',
            'app_secret'        => 'b72****8b35',
            'get_token_url'     => 'https://api.weixin.qq.com/sns/oauth2/access_token',// 获取token基础url
            'get_user_info_url' => 'https://api.weixin.qq.com/sns/userinfo',//获取到用户信息
        ];
    }
    // 属于移动应用掉起登录方法

    /**
     * 使用开放平台信息获取到token
     * @param $code app返回的code
     * @return bool|string
     */
    public function get_token($code)
    {
        if (is_array($this->config)) {
            $configs = $this->config;
            $result  = $this->start_get_request($configs['get_token_url'], [
                'appid'      => $configs['app_id'],
                'secret'     => $configs['app_secret'],
                'code'       => $code,
                'grant_type' => 'authorization_code'
            ]);
            if (false == $result) {
                return false;
            }
            return $result;
        }
    }

    /**
     * 根据accesstoken和openid获取到授权登录的用户信息
     * @param $access_token
     * @param $openid
     * @return bool|string
     */
    public function get_user_info($access_token, $openid)
    {
        $result = $this->start_get_request($this->config['get_user_info_url'], [
            'access_token' => $access_token,
            'openid'       => $openid
        ]);
        if (false == $result) {
            return false;
        }
        return $result;
    }
    // 工具类方法

    /**
     * 发起Get请求并且返回结果
     * @param $uri 请求地址
     * @param $query 请求参数
     * @return string
     */
    public function start_get_request($uri, $query)
    {
        $body = (new Client())->request('GET', $uri, [
            'query'   => $query,
            'timeout' => 3.14
        ]);
        if ($body->getStatusCode() != 200) {
            return false;
        }
        return json_decode($body->getBody(), true, 512, JSON_BIGINT_AS_STRING);
    }
}

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!

发表评论

您的电子邮箱地址不会被公开。