微信公衆平臺OAuth2.0 認證

第一步:引導用戶打開以下連接 (詳細介紹見OAuth2.0)php

$url = urlencode('http://xxx.com/xxx');
$newurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9c807c944920c501&redirect_uri=$url&response_type=code&scope=snsapi_base&state=123#wechat_redirect";

注意這裏須要去配置redirect_uri 回調URL的受權域名
若是用戶贊成受權,頁面將跳轉至 redirect_uri/?code=CODE&state=STATE。若用戶禁止受權,則重定向後不會帶上code參數,僅會帶上state參數redirect_uri?state=STATEjson

OAuth2.0
點擊修改
修改受權域名segmentfault

第二步:封裝拉取用戶信息類api

public function Oauth($code='',$mode=0){
    $appid = $this->AppId ;  //公共帳號 appid
    $secret = $this->AppSecret ;  //公衆帳號AppSecret 
    if($code=='') $code = $_REQUEST['code'] ; //接收參數
    if(!$code) return false ;
    $cul = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code' ;
    $cx = file_get_contents($cul) ;
    $bx = json_decode($cx,true) ;
    if($bx['errcode']){
        //第一步 根據code獲取refresh_token
        $this->restat = 0 ;
        $this->errmsg = $bx ;  return  ;
    }
    $rtoken = $bx['refresh_token'] ;
    $rurl = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$rtoken ;
    $rr = file_get_contents($rurl) ;
    $rr = json_decode($rr,true) ;
    if($rr['errcode']){
        //第二步 根據refresh_token獲取的access_token和openid
        $this->restat = 0 ;
        $this->errmsg = $bx ;  return  ;
    }
    $acct = $rr['access_token'] ;
    //file_put_contents('abc.txt', $acct);
    $this->auth_access_token = $acct ; //存放認證的token

    $openid = $rr['openid'] ;
    if($mode == 0 ) return  ;
    //第三步拉取信息
    $purl = "https://api.weixin.qq.com/sns/userinfo?access_token=$acct&openid=$openid&lang=zh_CN" ;
    $xv = file_get_contents($purl) ;
    //file_put_contents('xv.txt', $xv);
    /*$xv返回數據格式
        {"openid":"XXX","nickname":"Mini_Ren","sex":1,"language":"zh_CN","city":"鄭州","province":"河南","country":"中國","headimgurl":"","privilege":[]}
    */
    $xv = json_decode($xv,true) ;
    if($xv['errcode']){
        $this->restat = 0 ;
        $this->errmsg = $bx ;  return  ;
    }
    $this->res = $xv ;
    return $xv ; //帶有用戶信息數組
}

PS:微信Oauth認證類下載 Oauth認證下載數組

相關文章
相關標籤/搜索