微信网页授权-函数封装

具体而言,网页授权流程分为四步:
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;
    }

猜你喜欢

转载自blog.csdn.net/zhc2006/article/details/51374809
今日推荐