1. 程式人生 > >頁面獲取微信使用者資訊

頁面獲取微信使用者資訊

獲取使用者基本資訊需要以下三步:

  1. 獲取code

    使用以下地址請求code:

    https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect

     

  2. 以上地址需要的引數解釋:

    appid: 你的公眾開發平臺的appid

    redirect_uri: 你的回撥地址, 獲得code後會把code作為引數傳入此地址中

    response_type: 直接填寫code就行了

    scope: 如果獲取使用者資訊的code就用snsapi_userinfo就行了

    state: (非必須)用於保持請求和回撥的狀態,授權請求後原樣帶回給第三方。該引數可用於防止csrf攻擊(跨站請求偽造攻擊),建議第三方帶上該引數,可設定為簡單的隨機數加session進行校驗

  3.  
  4. 通過code獲取access_tokenopenid

    如果第一步沒有問題的話, 在第一步中的redirect_uri引數地址中會接收到code資訊;

    使用以下地址請求access_token和openid:

    https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

    以上地址需要的引數解釋:

    appid: 你的公眾開發平臺的appid

    secret: 你的公眾開發平臺的AppSecret

    code: 第一步傳過來的code

    grant_type: 填寫authorization_code就OK

  5.  
  6. 通過access_tokenopenid獲取使用者基本資訊:

    使用以下地址請求使用者基本資訊:

    https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN';

    以上地址需要的引數解釋:

    access_token

    : 通過第二步獲取的access_token

    openid: 通過第二步獲取的openid

    lang: 填寫zh_CN就ok

  7.  

通過以上3步就能獲取使用者資訊, 下面附上php程式碼的實現: 

// 入口函式
function main() {
$appid = "wxf445027deded67b7";
$redirect_uri=urlencode("http://XXXXXX/redirect); // 這裡的回撥地址為下面的函式
$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
header('location:'.$url);
}
// 回撥地址
function redirect() {
$info = $_REQUEST;
// 獲取access_token和openid
$appid="wxf445027deded789"; // 公眾平臺的appid
$secret = "2e3a89b8de95d123213213"; // 公眾平臺的secret
$code = $info['code'];
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
$data = getCurl($url);
// 獲取使用者資訊
$access_token = $data->access_token;
$openid = $data->openid;
$url1 = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
$data1 = getCurl($url1);
echo json_encode($data1);
}
// curl請求資料函式
function getCurl($url) {
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10);
$data = json_decode(curl_exec($ch));
curl_close($ch);
return $data;
}