| 本帖最后由 moremorefun 于 2015-8-18 14:39 編輯 
 現(xiàn)在我們嘗試首次調(diào)用微信提供給我們的API.
 
 
 微信的API大部分是需要`access_token`作為驗證字段了,
 那我們首先嘗試獲取`access_token`.
 
 
 我們這次帖子的主要目的是在用戶發(fā)送給我們的公眾號一個文本消息的時候返回給用戶我們獲取到的access_token.
 
 
 根據(jù)我們在[回復(fù)簡單的文本消息 - 傻瓜式微信開發(fā)教程4 - 耗子原創(chuàng)]中的說明,
 我們對用戶的文本消息在`index.php`頁面中的`onText()`函數(shù)中進(jìn)行處理.
 微信關(guān)于獲取`access token`的說明在這里: http://mp.weixin.qq.com/wiki/11/0e4b294685f817b95cbed85ba5e82b8f.html
 
 
 在說明中我們可以看到,獲取`access_token`需要提供`appid`和`secret`兩個參數(shù),
 而之前我們的Wechat-php庫中沒有寫入secret參數(shù),所以我們還要對`Wechat.php`做一些修改,
 主要是為了保存`appid`和`secret`兩個字段.
 
 
 所以我們修改的`Wechat.php`的代碼為:
 
 
復(fù)制代碼
<?php
  class Wechat {
    // ....
    // ....
    // ....
    protected $encrypted = false;
    protected $appid = '';
    protected $appsecret = '';
    // 添加appsecret參數(shù)
    public function __construct($config=array('token'=>'', 'aeskey'=>'', 'appid'=>'', 'appsecret'=>'', 'debug' => FALSE)) {
      $token = $config['token'];
      $aeskey = $config['aeskey'];
      $appid = $config['appid'];
      $debug = $config['debug'];
      // 將兩個參數(shù)儲存在實例中
      $this->appid = $config['appid'];
      $this->appsecret = $config['appsecret'];
      // ...
      // ...
      // ...
    }
  }
 我們的調(diào)用函數(shù)為:
 
 
復(fù)制代碼
<?php
/**
* 微信開發(fā)者社區(qū): http:// 原創(chuàng)首發(fā)
*
* 微信公眾平臺 PHP SDK 示例文件
*/
  require('wechat/Wechat.php');
  /**
   * 微信公眾平臺演示類
   */
  class TestWechat extends Wechat {
    /**
     * 收到文本消息時觸發(fā),回復(fù)收到的文本消息內(nèi)容
     *
     * @return void
     */
    protected function onText() {
      // 獲取到 appid 和 appsecret
      $appid = $this->appid;
      $appsecret = $this->appsecret;
      // 構(gòu)建獲取access_token的url
      $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
      // 構(gòu)建http請求并執(zhí)行
      $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數(shù)據(jù)
      $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}'");
    }
  }
  // 這里調(diào)用新的
  $wechat = new TestWechat(array(
    'token'     => 'xxxx',              // 更新為自己的
    'aeskey'    => 'xxxx',             // 更新為自己的
    'appid'     => 'xxxx',              // 更新為自己的
    'appsecret' => 'xxxx',          // 更新為自己的
    'debug'     => true
    ));
  $wechat->run();
 附件中有整個代碼的壓縮包
 
 
 
 |