微信公众号怎么获取access_token?
微信公众号怎么获取access_token?微信公众号里的很多地方都需要用到access_token,那么微信公众号access_token是怎么获取的呢?下面小编就来为大家讲解一下。
我们这次的主要目的是在用户发送给我们的公众号一个文本消息的时候返回给用户我们获取到access_token.根据我们在[回复简单的文本消息 - 傻瓜式微信开发教程4 - 耗子原创]中的说明,我们对用户的文本消息在`index.php`页面中的`onText()`函数中进行处理.微信关于获取`access token`的说明在这里: mp.weixin.qq/wiki/11/ ... bed85ba5e82b8f.html在说明中我们可以看到,获取`access_token`需要提供`appid`和`secret`两个参数,而之前我们的Wechat-php库中没有写入secret参数,所以我们还要对`Wechat.php`做一些修改,主要是为了保存`appid`和`secret`两个字段.所以我们修改的`Wechat.php`的代码为:
class Wechat {
// ....
// ....
// ....
protected $encrypted = false;
protected $appid = '';
protected $appsecret = '';
// 添加appsecret参数
public function __construct($config=array('token'=>'', 'aeskey'=>'', 'appid'=>'', 'appsecret'=>'', 'debug' => FALSE)) {
$token = $config['token'];
$aeskey = $config['aeskey'];
$appid = $config['appid'];
$debug = $config['debug'];
// 将两个参数储存在实例中
$this->appid = $config['appid'];
$this->appsecret = $config['appsecret'];
// ...
// ...
// ...
}
}
我们的调用函数为:
/**
* 微信开发者社区: weixin 原创首发
*
* 微信公众平台 PHP SDK 示例文件
*/
require('wechat/Wechat.php');
/**
* 微信公众平台演示类
*/
class TestWechat extends Wechat {
/**
* 收到文本消息时触发,回复收到的文本消息内容
*
* @return void
*/
protected function onText() {
// 获取到 appid 和 appsecret
$appid = $this->appid;
$appsecret = $this->appsecret;
// 构建获取access_token的url
$url = "api.weixin.qq/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
// 构建请求并执行
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result=curl_exec($ch);
curl_close($ch);
// 解析返回的json数据
$jsoninfo = json_decode($result);
// 读取json中的access_token字段
$access_token = $jsoninfo->access_token;
$expires_in = $jsoninfo->expires_in;
// 将获取到的access_token作为文本信息返回
$this->responseText("access_token: '{$access_token}' expires_in: '{$expires_in}'");
}
}
// 这里调用新的
$wechat = new TestWechat(array(
'token' => 'xxxx', // 更新为自己的
'aeskey' => 'xxxx', // 更新为自己的
'appid' => 'xxxx', // 更新为自己的
'appsecret' => 'xxxx', // 更新为自己的
'debug' => true
));
$wechat->run();
以上就是小编为大家整理的关于微信公众号怎么获取access_token的内容。更多更精彩的内容请持续关注微信素材网。
相关阅读:
微信场景如何开发?
微信小程序开发将带来哪些创业机会?
微信分享接口开发是什么?