關于 access_token
access_token 是公眾號的全局唯一接口調(diào)用憑據(jù)柔滔,公眾號調(diào)用各接口時都需使用 access_token兼耀。
access_token 的存儲至少要保留 512 個字符空間狠半。access_token 的有效期目前為 2 個小時奏夫。
接口調(diào)用說明
https 請求方式:GET
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
參數(shù)
參數(shù) | 是否必須 | 說明 |
---|---|---|
grant_type | Y | 獲取access_token填寫client_credential |
appid | Y | 第三方用戶唯一憑證 |
secret | Y | 第三方用戶唯一憑證密鑰,即 appsecret |
代碼塊
- 方法一 :curl_init() 函數(shù)
<?php
$appid = "";
$appsecret = "";
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
/*
* curl_init() 為 PHP 函數(shù)
* curl_setopt 設置 cURL 的傳輸選項
**/
$ch = curl_init(); // 創(chuàng)建一個 cURL 資源
curl_setopt($ch, CURLOPT_URL, $url); // CURLOPT_URL 目標 url 地址
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // CURLOPT_SSL_VERIFYPEER False: 終止 cURL 在服務器進行驗證
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // CURLOPT_RETURNTRANSFER 返回原生的(Raw)輸出
$output = curl_exec($ch);
var_dump($output);
curl_close($ch);
/*
* 想帥的可以利用 JSON 函數(shù) json_decode(僅處理 UTF-8 編碼數(shù)據(jù)) 來美化輸出
* 當函數(shù) assoc 參數(shù)為 true 返回的是 array, 反之是 object, 默認為 false
* */
$json_output = json_decode($output);
var_dump($json_output);
- 方法二 :file_get_contents 函數(shù)
<?php
$appid = "";
$appsecret = "";
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
// file_get_contents 將整個文件讀入一個字符串中。
$output = file_get_contents($url);
$json_output = json_decode($output, true);
var_dump($json_output);
效果圖
- $output
string(194) "{"access_token":"11_-S30IWoUhYZvZw2Qe......","expires_in":7200}"
- json_decode($output)
object(stdClass)#6 (2) { ["access_token"]=> string(157) "11_AkasWeD0okdTqXDyqw4......" ["expires_in"]=> int(7200) }
- json_decode($output, true)
array(2) { ["access_token"]=> string(136) "11_OuFwGg-aW8y6EC1Gt1dVi......" ["expires_in"]=> int(7200) }