微信网页授权-函数封装

具体而言,网页授权流程分为四步:
1、引导用户进入授权页面同意授权,获取code 
2、通过code换取网页授权access_token(与基础支持中的access_token不同) 
3、如果需要,开发者可以刷新网页授权access_token,避免过期 
4、通过网页授权access_token和openid获取用户基本信息(支持UnionID机制) 
目录
1 第一步:用户同意授权,获取code
2 第二步:通过code换取网页授权access_token
3 第三步:刷新access_token(如果需要)
4 第四步:拉取用户信息(需scope为 snsapi_userinfo)

// ************************** OAuth *****************

    public function getOAuthConnectUri($redirect_uri, $state = '', $scope = 'snsapi_base') {

        $redirect_uri = urlencode($redirect_uri);

        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->_CONFIG['weixin']['appid']}&redirect_uri={$redirect_uri}&response_type=code&scope={$scope}&state={$state}#wechat_redirect";
        
        return $url;

    }



    public function getAccessTokenByCode($code) {

        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->_CONFIG['weixin']['appid']}&secret={$this->_CONFIG['weixin']['appsecret']}&code=$code&grant_type=authorization_code";
        
        $res = json_decode($this->curlGet($url), true);

        return $res;

    }



    public function refreshAccessTocken($refresh_token) {

        $url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={$this->_appid}&grant_type=refresh_token&refresh_token=$refresh_token";

        $res = json_decode($this->curlGet($url), true);

        return $res;

    }



    public function getUserInfoByAuth($access_token, $openid, $lang = 'zh_CN') {

        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=$lang";

        $res = json_decode($this->curlGet($url), true);

        return $res;

    }



    // ************************** OAuth End*****************


    function curlGet($url,$data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值