一、Access Token
access_token是公眾號的全局唯一票據(jù)蛾绎,公眾號調(diào)用各接口時(shí)都需使用access_token薄啥。正常情況下access_token有效期為7200秒,重復(fù)獲取將導(dǎo)致上次獲取的access_token失效似扔。
公眾號可以使用AppID和AppSecret調(diào)用本接口來獲取access_token吨些。AppID和AppSecret可在開發(fā)模式中獲得(需要已經(jīng)成為開發(fā)者,且?guī)ぬ枦]有異常狀態(tài))炒辉。注意調(diào)用所有微信接口時(shí)均需使用https協(xié)議豪墅。
接口調(diào)用請求說明
http請求方式: GET
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
參數(shù)說明
參數(shù) | 是否必須 | 說明 |
---|---|---|
grant_type | 是 | 獲取access_token填寫client_credential |
appid | 是 | 第三方用戶唯一憑證 |
secret | 是 | 第三方用戶唯一憑證密鑰,既appsecret |
返回說明
正常情況下黔寇,微信會返回下述JSON數(shù)據(jù)包給公眾號:
{"access_token":"ACCESS_TOKEN","expires_in":7200}
參數(shù) | 說明 |
---|---|
access_token | 獲取到的憑證 |
expires_in | 憑證有效時(shí)間偶器,單位:秒 |
代碼示例:(使用Tp5.0框架)
1.在config.php
配置文件中,配置wechat
的參數(shù)
image.png
2.獲取Access Token
新建wechat.php
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/8/6
* Time: 22:41
*/
namespace app\index\controller;
use think\Controller;
class Wechat extends Controller
{
protected $accessTokenUrl = 'https://api.weixin.qq.com/cgi-bin/token';
protected $appId;
protected $secret;
/**
* 加載微信配置
*/
protected function _initialize(){
$this->appId = config('wechat.appId');
$this->secret = config('wechat.secret');
}
/**
* 獲取微信access_token
* @return mixed|null
*/
public function getAccessToken(){
$accessToken = cache('accessToken');
if($accessToken)
return $accessToken;
$param = [
'grant_type' => 'client_credential',
'appid' => $this->appId,
'secret' => $this->secret,
];
$result = httpGuzzle('get',$this->accessTokenUrl,$param); // 使用Guzzle
$accessToken = $result['access_token'];
cache('accessToken',$accessToken,($result['expires_in']-10));
return $accessToken;
}
}