PHP 微信授权地址设置多个 多域名授权

本文详细解析了微信OAuth2.0授权登录流程,包括如何设置参数获取授权码(code),以及如何通过获取的code进行后续的用户信息获取。文章通过具体的PHP代码示例,展示了如何根据不同的设备类型(如PC或手机)调整授权URL,以及如何处理回调中的code和state参数。
public function get_code() {
        $appid = '';
        $scope = 'snsapi_userinfo';
        $state = '';
        $code = '';
        $redirect_uri = '';
        $device = '';
        $protocol = 'https';

        if (isset($_GET['device'])) {
            $device = $_GET['device'];
        }

        if (isset($_GET['appid'])) {
            $appid = $_GET['appid'];
        }
        if (isset($_GET['state'])) {
            $state = $_GET['state'];
        }
        if (isset($_GET['redirect_uri'])) {
            $redirect_uri = $_GET['redirect_uri'];
        }
        if (isset($_GET['code'])) {
            $code = $_GET['code'];
        }
        if (isset($_GET['scope'])) {
            $scope = $_GET['scope'];
        }

        if ($code == 'test') {
            exit;
        }

        if (empty($code)) {
            $authUrl = '';
            if ($device == 'pc') {
                $authUrl = 'https://open.weixin.qq.com/connect/qrconnect';
            } else {
                $authUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize';
            }

            $options = [
                $authUrl,
                '?appid=' . $appid,
                '&redirect_uri=' . urlencode($protocol . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '/'),
                '&response_type=code',
                '&scope=' . $scope,
                '&state=' . $state,
                '#wechat_redirect'
            ];

            //把redirect_uri先写到 session
            $this->session->set_userdata('redirect_uri', $redirect_uri);

            header('Location: ' . implode('', $options));
        } else {
            if (isset($_COOKIE['redirect_uri'])) {
                $back_url = $this->session->userdata('redirect_uri');
                header('Location: ' . implode('', [
                            $back_url,
                            strpos($back_url, '?') ? '&' : '?',
                            'code=' . $code,
                            '&state=' . $state
                ]));
            }
        }
    }

调用代码

http://****.com?appid=***&redirect_uri=******&response_type=code&scope=snsapi_userinfo&state=****

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值