微信公衆平臺OAuth2.0受權登錄(PHP)

文件1:index.phpphp

//換成本身的接口信息html

$appid = 'XXXXX';sql

header('location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri=127.0.0.1/oauth.php&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect');json

參數說明:api

參數數組

是否必須微信

說明app

appid 公衆號的惟一標識
redirect_uri 受權後重定向的回調連接地址,請使用urlencode對連接進行處理
response_type 返回類型,請填寫code
scope 應用受權做用域,snsapi_base (不彈出受權頁面,直接跳轉,只能獲取用戶openid),snsapi_userinfo (彈出受權頁面,可經過openid拿到暱稱、性別、所在地。而且,即便在未關注的狀況下,只要用戶受權,也能獲取其信息
state 重定向後會帶上state參數,開發者能夠填寫a-zA-Z0-9的參數值
#wechat_redirect 不管直接打開仍是作頁面302重定向時候,必須帶此參數

 


文件二:oauth.php微信公衆平臺

 代碼以下 複製代碼
<?php
$code = $_GET['code'];
$state = $_GET['state'];
//換成本身的接口信息
$appid = 'XXXXX';
$appsecret = 'XXXXX';
if (empty($code)) $this->error('受權失敗');
$token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
$token = json_decode(file_get_contents($token_url));
if (isset($token->errcode)) {
    echo '<h1>錯誤:</h1>'.$token->errcode;
    echo '<br/><h2>錯誤信息:</h2>'.$token->errmsg;
    exit;
}
$access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;
//轉成對象
$access_token = json_decode(file_get_contents($access_token_url));
if (isset($access_token->errcode)) {
    echo '<h1>錯誤:</h1>'.$access_token->errcode;
    echo '<br/><h2>錯誤信息:</h2>'.$access_token->errmsg;
    exit;
}
$user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';
//轉成對象
$user_info = json_decode(file_get_contents($user_info_url));
if (isset($user_info->errcode)) {
    echo '<h1>錯誤:</h1>'.$user_info->errcode;
    echo '<br/><h2>錯誤信息:</h2>'.$user_info->errmsg;
    exit;
}
//打印用戶信息
echo '<pre>';
print_r($user_info);
echo '</pre>';
?>

 

參數this

描述

openid 用戶的惟一標識
nickname 用戶暱稱
sex 用戶的性別,值爲1時是男性,值爲2時是女性,值爲0時是未知
province 用戶我的資料填寫的省份
city 普通用戶我的資料填寫的城市
country 國家,如中國爲CN
headimgurl 用戶頭像,最後一個數值表明正方形頭像大小(有0、4六、6四、9六、132數值可選,0表明640*640正方形頭像),用戶沒有頭像時該項爲空
privilege 用戶特權信息,json 數組,如微信沃卡用戶爲(chinaunicom)
unionid 只有在用戶將公衆號綁定到微信開放平臺賬號後,纔會出現該字段。詳見:獲取用戶我的信息(UnionID機制)

 

----------------------------我的封裝----------------------

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Wap_oauth extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->load->library('wap_admin');
    }
    public function accredit()
    {
        $call_url = "http://www.ivymei.com/wxapi/index.php?/Wap_oauth/url_shift/"; 
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->config->item('appid').'&redirect_uri='.urlencode($call_url).'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
        header("Location:".$url);  
    }

    public function url_shift()
    {
        $str = $_SERVER['REQUEST_URI'];
        $temp = explode('&', $str);
        $code = substr($temp[1], 5);
        $state = substr($temp[2], 6);
        // $call_url = 'http://m.ivymei.com/index.php?/Wap_oauth/get_token/&code='.$code.'&state='.$state; 
        $call_url = 'http://m.ivymei.com/index.php?/Wap_oauth/get_token/'.$code.'/'.$state; 
        header('Location:'.$call_url);
    }


    public function get_token($code = '', $state = '')
    {   
        //公衆號信息
        $appid = $this->config->item('appid');
        $appsecret = $this->config->item('appsecret');
        if (empty($code)){ 
            die(json_encode(array('error' => '受權失敗!')));
        }
        $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
        $token = json_decode(file_get_contents($token_url));
        if (isset($token->errcode)) {
            die(json_encode(array('error' => $token->errcode, 'msg' => $token->errmsg)));
        }

        //appid 和 更新token 獲取 access_token 和 openid 的組合URL
        $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;

        //轉成對象
        $access_token = json_decode(file_get_contents($access_token_url));
        if (isset($access_token->errcode)) {
            die(json_encode(array('error' => $access_token->errcode, 'msg' => $access_token->errmsg)));
        }

        //access_token 和 openid 獲取用戶信息的組合URL
        $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';

        //轉成對象
        // $userinfo = get_object_vars(json_decode(file_get_contents($user_info_url)));
        $userinfo = json_decode(file_get_contents($user_info_url));
        
        if (isset($user_info->errcode)) {
            die(json_encode(array('error' => $user_info->errcode, 'msg' => $user_info->errmsg)));
        }
        //轉成數組
        $user_info = is_object($userinfo) ? get_object_vars($userinfo) :  $userinfo;
        echo '<pre>';

        print_r($user_info);

        echo '</pre>';

//根據openid 查找是否有註冊
        $sql = "SELECT id,nick_name,avatar,sex,province,city,mobile FROM im_member WHERE openid = '".$user_info['openid']."'";
        $combo_userinfo = $this->db->query($sql);
        $userinfoFind = $combo_userinfo->result_array();
        if(empty($userinfoFind)){
            $_SESSION['wx_landing_info'] = $user_info;
            $this->load->view('message.html');
        }else{
            //將微信信息跟用戶信息綁定
            $add_data = array();
            //暱稱
            if(empty($userinfoFind[0]['nick_name']))
                $data['nick_name'] = $user_info['nickname'];
            //性別
            if(empty($userinfoFind[0]['sex']))
                $add_data['sex'] = $user_info['sex'];
            //省
            if(empty($userinfoFind[0]['province']))
                $add_data['province'] = $user_info['province'];
            //市
            if(empty($userinfoFind[0]['city']))
                $add_data['city'] = $user_info['city'];

            if(!empty($add_data)){
                $this->db->where('id',$userinfoFind[0]['id']); 
                $resUserinfo = $this->db->update('member',$add_data);
            }

            $_SESSION['wap_user']['mobile'] = $userinfoFind[0]['mobile'];
            $_SESSION['wap_user']['id'] = $userinfoFind[0]['id'];
            $_SESSION['wap_user']['name'] = $userinfoFind[0]['name'];

            //跳轉首頁  默認登陸了
            header("Location: ".$this->config->item('base_url'));
        }

    }

}

上面之因此轉了一次跳轉,是由於第一個域名m.ivymei.com不是受權域名,因此只能先跳到受權域名下面,在調轉回來,若是是同一個域名,便可減小url_shift這一步。

受權域名設置:登陸微信公衆平臺---接口權限---找到網頁帳號--網頁受權獲取用戶基本信息旁邊有一個修改,裏面添受權域名。

相關文章
相關標籤/搜索