微信開發中,access_token的獲取是一種非常常見的功能,通過公眾號的appid和appsecret來向微信公眾平台請求一個臨時通行憑證:access_token。公眾平台上的絕大部分操作都會需要這個臨時通行憑證的授權,以php為例,access_token的獲取方法:
<?php define("APPID", $appid); define("APPSECRET", $appsecret); // 獲取access_token $token_access_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . APPID . "&secret=" . APPSECRET; $res = file_get_contents($token_access_url); //獲取文件內容或獲取網絡請求的內容 $result = json_decode($res, true); //接受一個 JSON 格式的字符串並且把它轉換為 PHP 變量 $access_token = $result['access_token']; ?>
返回的參數中除了我們需要的access_token以外,還會有一個這個臨時通行憑證的有效期。由於每天向公眾平台獲取access_token的次數是有限的,所以建議將獲取的access_token存入數據里,超出有效期了再進行請求獲取。