1. 程式人生 > >PHP獲得微信用戶的OpenID,然後再通過OpenID和access_token查詢用戶信息

PHP獲得微信用戶的OpenID,然後再通過OpenID和access_token查詢用戶信息

csdn lac 輸出 這一 獲取 nsf ppi content 進行

PHP獲得微信用戶的OpenID,然後再通過OpenID和access_token查詢用戶信息大致如下步驟:

前提是必須要知道的有公眾帳號的:appid和secret

* 1、拼成一個鏈接
* 2、把鏈接拋出去返回一個code echo $_GET[‘code‘]
* 3、根據code換取access_token和openid
* 4. 使用access_token和openid來獲取用戶信息
* 5、
*

一、第一步寫個頁面去進行請求微信API獲取code

<?php
//$APPID=‘*******‘;
//$REDIRECT_URI=‘wx.qq.com/c/m1020.php‘;
//$scope=‘snsapi_base‘;如果要獲取所有的信息請用$scope = snsapi_userinfo;
//$state = 120;

//需要授權的域名 wx.qq.com這一步是在公眾後臺進行添加的,然後這個域名下的所有頁面都可以獲得授權比如我的:http://wx.qq.com/c/m1020a.php
header("Location: https://open.weixin.qq.com/connect/oauth2/authorize?appid=***********&redirect_uri=http://wx.qq.com/c/m1020a.php&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect");

?>

二、第二步寫另外一個頁面獲得微信用戶的OpenID,然後再通過OpenID和access_token查詢用戶信息代碼如下:

<?php
//wx.mtgdfs.com/c/m1020.php
$appid = "你的公眾帳號appid";
$secret = "你的公眾帳號秘鑰";
$code = $_GET["code"];
$get_token_url = ‘https://api.weixin.qq.com/sns/oauth2/access_token?appid=‘.$appid.‘&secret=‘.$secret.‘&code=‘.$code.‘&grant_type=authorization_code‘;
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$get_token_url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$res = curl_exec($ch);
curl_close($ch);
$json_obj = json_decode($res,true);
//根據openid和access_token查詢用戶信息
$access_token = $json_obj[‘access_token‘];
$openid = $json_obj[‘openid‘];
$get_user_info_url = ‘https://api.weixin.qq.com/sns/userinfo?access_token=‘.$access_token.‘&openid=‘.$openid.‘&lang=zh_CN‘;

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$get_user_info_url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$res = curl_exec($ch);
curl_close($ch);


//echo "<hr>ddd<hr>";
//$code = $_GET[‘code‘];//獲取code
//$weixin = file_get_contents("https://api.weixin.qq.com/sns/oauth2 /access_token?appid=wxba922caddc6700a8& secret=9f47a54b26ab9ed1a01fa71ae2e82f27&code=".$code."& grant_type=authorization_code");//通過code換取網頁授權access_token
//$jsondecode = json_decode($weixin); //對JSON格式的字符串進行編碼
//$array = get_object_vars($jsondecode);//轉換成數組
//print_r($array);exit;
//$openid = $array[‘openid‘];//輸出openid



//解析json
$user_obj = json_decode($res,true);
$_SESSION[‘user‘] = $user_obj;
print_r($user_obj);
?>

PHP獲得微信用戶的OpenID,然後再通過OpenID和access_token查詢用戶信息