本帖最后由 moremorefun 于 2015-8-18 14:39 编辑
现在我们尝试首次调用微信提供给我们的API.
微信的API大部分是需要`access_token`作为验证字段了, 那我们首先尝试获取`access_token`.
我们这次帖子的主要目的是在用户发送给我们的公众号一个文本消息的时候返回给用户我们获取到的access_token.
根据我们在[回复简单的文本消息 - 傻瓜式微信开发教程4 - 耗子原创]中的说明, 我们对用户的文本消息在`index.php`页面中的`onText()`函数中进行处理. 微信关于获取`access token`的说明在这里: http://mp.weixin.qq.com/wiki/11/0e4b294685f817b95cbed85ba5e82b8f.html
在说明中我们可以看到,获取`access_token`需要提供`appid`和`secret`两个参数, 而之前我们的Wechat-php库中没有写入secret参数,所以我们还要对`Wechat.php`做一些修改, 主要是为了保存`appid`和`secret`两个字段.
所以我们修改的`Wechat.php`的代码为:
- <?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'];
- // ...
- // ...
- // ...
- }
- }
复制代码 我们的调用函数为:
- <?php
- /**
- * 微信开发者社区: http:// 原创首发
- *
- * 微信公众平台 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 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
- // 构建http请求并执行
- $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}'\nexpires_in: '{$expires_in}'");
- }
- }
- // 这里调用新的
- $wechat = new TestWechat(array(
- 'token' => 'xxxx', // 更新为自己的
- 'aeskey' => 'xxxx', // 更新为自己的
- 'appid' => 'xxxx', // 更新为自己的
- 'appsecret' => 'xxxx', // 更新为自己的
- 'debug' => true
- ));
- $wechat->run();
复制代码 附件中有整个代码的压缩包
|