1. 程式人生 > 程式設計 >Yii Framework框架開發微信公眾平臺示例

Yii Framework框架開發微信公眾平臺示例

本文例項講述了Yii Framework框架開發微信公眾平臺。分享給大家供大家參考,具體如下:

1. 先到微信公眾平臺註冊帳號

http://mp.weixin.qq.com

2. 下載demo

微信公眾平臺提供了一個十分“樸素”的demo,說明如何呼叫訊息介面的。程式碼真的很樸素,具體內容可到官網下載。

3. 按照Yii的規則,做一個extension。

這裡命名為 weixin,目錄結構如下:

▾ extensions/
▾ weixin/
Weixin.php*

Weixin.php程式碼內容:

<?php
 
/**
 * WeixinCallback 
 * 
 * @package 
 * @version $id$
 * @copyright 1997-2005 The PHP Group
 * @author [email protected]
 * {@link <a href="http://www.sharefamily.net" rel="external nofollow" target="_blank">http://www.sharefamily.net</a>}
 */
class Weixin
{
  //$_GET引數
  public $signature;
  public $timestamp;
  public $nonce;
  public $echostr;
  //
  public $token;
  public $debug = false;
  public $msg = array();
  public $setFlag = false;
 
  /**
   * __construct 
   * 
   * @param mixed $params 
   * @access public
   * @return void
   */
  public function __construct($params)
  {
    foreach ($params as $k1 => $v1)
    {
      if (property_exists($this,$k1))
      {
        $this->$k1 = $v1;
      }
    }
  }
   
  /**
   * valid 
   * 
   * @access public
   * @return void
   */
  public function valid()
  {
    //valid signature,option
    if($this->checkSignature()){
      echo $this->echostr;
      Yii::app()->end();
    }
  }
 
  /**
   * 獲得使用者發過來的訊息(訊息內容和訊息型別 ) 
   * 
   * @access public
   * @return void
   */
  public function init()
  {
    $postStr = empty($GLOBALS["HTTP_RAW_POST_DATA"]) ? '' : $GLOBALS["HTTP_RAW_POST_DATA"];
    if ($this->debug) 
    {
      $this->log($postStr);
    }
    if (!empty($postStr)) {
      $this->msg = simplexml_load_string($postStr,'SimpleXMLElement',LIBXML_NOCDATA);
    }
  }
 
  /**
   * makeEvent 
   * 
   * @access public
   * @return void
   */
  public function makeEvent()
  {
     
  }
 
  /**
   * 回覆文字訊息 
   * 
   * @param string $text 
   * @access public
   * @return void
   */
  public function makeText($text='')
  {
    $createTime = time();
    $funcFlag = $this->setFlag ? 1 : 0;
    $textTpl = "<xml>
      <ToUserName><![CDATA[{$this->msg->FromUserName}]]></ToUserName>
      <FromUserName><![CDATA[{$this->msg->ToUserName}]]></FromUserName>
      <CreateTime>{$createTime}</CreateTime>
      <MsgType><![CDATA[text]]></MsgType>
      <Content><![CDATA[%s]]></Content>
      <FuncFlag>%s</FuncFlag>
      </xml>";
    return sprintf($textTpl,$text,$funcFlag);
  }
   
  /**
   * 根據陣列引數回覆圖文訊息 
   * 
   * @param array $newsData 
   * @access public
   * @return void
   */
  public function makeNews($newsData=array())
  {
    $createTime = time();
    $funcFlag = $this->setFlag ? 1 : 0;
    $newTplHeader = "<xml>
      <ToUserName><![CDATA[{$this->msg->FromUserName}]]></ToUserName>
      <FromUserName><![CDATA[{$this->msg->ToUserName}]]></FromUserName>
      <CreateTime>{$createTime}</CreateTime>
      <MsgType><![CDATA[news]]></MsgType>
      <ArticleCount>%s</ArticleCount><Articles>";
    $newTplItem = "<item>
      <Title><![CDATA[%s]]></Title>
      <Description><![CDATA[%s]]></Description>
      <PicUrl><![CDATA[%s]]></PicUrl>
      <Url><![CDATA[%s]]></Url>
      </item>";
    $newTplFoot = "</Articles>
      <FuncFlag>%s</FuncFlag>
      </xml>";
    $content = '';
    $itemsCount = count($newsData['items']);
    //微信公眾平臺圖文回覆的訊息一次最多10條
    $itemsCount = $itemsCount < 10 ? $itemsCount : 10;
    if ($itemsCount) {
      foreach ($newsData['items'] as $key => $item) {
        if ($key<=9) {
          $content .= sprintf($newTplItem,$item['title'],$item['description'],$item['picurl'],$item['url']);
        }
      }
    }
    $header = sprintf($newTplHeader,$itemsCount);
    $footer = sprintf($newTplFoot,$funcFlag);
    return $header . $content . $footer;
  }
 
  /**
   * reply 
   * 
   * @param mixed $data 
   * @access public
   * @return void
   */
  public function reply($data)
  {
    if ($this->debug) 
    {
      $this->log($data);
    }
    echo $data;
  }
 
  /**
   * checkSignature 
   * 
   * @access private
   * @return void
   */
  private function checkSignature()
  {
    $tmpArr = array($this->token,$this->timestamp,$this->nonce);
    sort($tmpArr);
    $tmpStr = implode( $tmpArr );
    $tmpStr = sha1( $tmpStr );
     
    if( $tmpStr == $this->signature ){
      return true;
    }else{
      return false;
    }
  }
 
  /**
   * log 
   * 
   * @access private
   * @return void
   */
  private function log($log)
  {
    if ($this->debug)
    {
      file_put_contents(Yii::getPathOfAlias('application').'/runtime/weixin_log.txt',var_export($log,true)."\n\r",FILE_APPEND);
    }
  }
}

使用方法,這裡舉例在SiteController裡面

/**
   * actionIndex 
   * 
   * @access public
   * @return void
   */
  public function actionIndex()
  {
    $weixin = new Weixin($_GET);
    $weixin->token = $this->_weixinToken;
    //$weixin->debug = true;
 
    //網址接入時使用
    if (isset($_GET['echostr']))
    {
      $weixin->valid();
    }
     
    $weixin->init();
    $reply = '';
    $msgType = empty($weixin->msg->MsgType) ? '' : strtolower($weixin->msg->MsgType);
    switch ($msgType)
    {
    case 'text':
      //你要處理文字訊息程式碼
      break;
    case 'image':
      //你要處理圖文訊息程式碼
      break;
    case 'location':
      //你要處理位置訊息程式碼
      break;
    case 'link':
      //你要處理連結訊息程式碼
      break;
    case 'event':
      //你要處理事件訊息程式碼
      break;
    default: 
      //無效訊息情況下的處理方式
      break;
    }
    $weixin->reply($reply);
  }

至此,基本的邏輯都實現了

更多關於Yii相關內容感興趣的讀者可檢視本站專題:《Yii框架入門及常用技巧總結》、《php優秀開發框架總結》、《smarty模板入門基礎教程》、《php面向物件程式設計入門教程》、《php字串(string)用法總結》、《php+mysql資料庫操作入門教程》及《php常見資料庫操作技巧彙總》

希望本文所述對大家基於Yii框架的PHP程式設計有所幫助。