微信公衆號網頁授權,獲取用戶信息以及openid -- PHP後臺

微信公衆號網頁授權,獲取用戶信息以及openid

這幾天做項目,想通過公衆號的appid獲取用戶的openid就,然後在網上查資料,問朋友,最後找到了方法,就是這個網頁授權。
起初一直很蒙,這個怎麼弄,又是需要code,又是需要允許授權的,我怎麼獲取這個code,在哪裏出發這個網頁授權的事件呢,最後弄明白了,其實很簡單。

首先我們先寫一個html網頁,比如這樣的:
在這裏插入圖片描述
點擊·確認授權·,執行下面php代碼裏面的request_wechat1方法就ok了。

對,沒錯,這就完成了,簡單嗎,是不是很簡單,只需要一步

PHP代碼:

public function request_wechat1(){
	$app_id  = '微信公衆號appid';
    // 回調地址
    $redirect_url = 'https://www.tjhaizhixian.com/seafood/public/index/base/get_open_id1';
    $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $app_id . "&redirect_uri=" . $redirect_url . "&response_type=code&scope=snsapi_base&state=0#wechat_redirect";
    header("Location:{$url}");
    die;
}
/**
 * 微信回調地址,以獲取openid
 */
public function get_open_id1(){
    $code = Request::instance()->param('code');
    $app_id  = '微信公衆號appid';
    $app_secret = '微信公衆號app_secret';
    //第一步:取全局access_token
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$app_id}&secret={$app_secret}";
    $token = $this->get_json($url);
 
    //第二步:取得openid
    $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$app_id}&secret={$app_secret}&code={$code}&grant_type=authorization_code";
    $oauth2 = $this->get_json($oauth2Url);
 
    //第三步:根據全局access_token和openid查詢用戶信息
    $access_token = $token["access_token"];
    $openid = $oauth2['openid'];
    $get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
    $userinfo = $this->get_json($get_user_info_url);
    print_r($userinfo);
}

protected function get_json($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    curl_close($ch);
    return json_decode($output, true);
}

謝謝觀看,有建議可以私信

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章