网页授权

参考文档

官方获取用户基本信息(UnionID机制)

官方网页授权

easywechat插件获取用户的相关

easywechat插件网页授权

参考代码

<?php

namespace app\official\controller;

use think\Controller;

// 微信公众号封装类
use EasyWeChat\Factory;
// 微信公众号配置
use addons\wechat\library\Config;

class Auth extends Controller
{
    // 微信类对象
    protected $weChat = null;

    public function __construct()
    {
        // 手动继承父级的构造函数
        parent::__construct();

        // 初始化
        $this->weChat = Factory::officialAccount(Config::load());
    }

    // 网页授权
    public function index()
    {
        // 判断是否授权
        if(empty(session('wechat_user')))
        {
            $result = $this->weChat->oauth->scopes(['snsapi_userinfo'])->redirect();

            return $result->send();
        }else{
             echo '欢迎回来';
        }
    }

    // 登录回调
    public function login()
    {
        // 获取对应微信的 OPENID
        $openid = $this->weChat->oauth->user()->getId();

        if(empty($openid))
        {
            $this->error('获取openid失败');
        }

        // 通过openid获取用户基本信息
        $user = $this->weChat->user->get($openid);

        // 设置session
        session('wechat_user',$user);

        $this->success('授权成功',url('/official/auth/index'));

    }
}
powered by GitbookEdit Time: 2024-06-06 18:25:40