基於 PHP 的微信公眾平臺開發

jiazhuamh發表於2017-05-18

一、伺服器配置
申請微信公眾平臺,進入管理介面。開發 -> 基本配置,在伺服器配置皮膚中點選修改配置,URL是你的伺服器地址(http://myserver/index.php),Token隨便設定一個字串(hello2017),EncodingAESKey隨機生成,訊息加密方式選擇“明文模式”。
二、測試
在web伺服器訪問目錄下建立index.php檔案,內容如下:

<?php
define("TOKEN", "YoonPer"); //TOKEN值
$wechatObj = new wechat();
$wechatObj->valid();
class wechat {
  public function valid() {
    $echoStr = $_GET["echostr"];
    if($this->checkSignature()){
      echo $echoStr;
      exit;
    }
  }
  private function checkSignature() {
    $signature = $_GET["signature"];
    $timestamp = $_GET["timestamp"];
    $nonce = $_GET["nonce"];
    $token = TOKEN;
    $tmpArr = array($token, $timestamp, $nonce);
    sort($tmpArr);
    $tmpStr = implode( $tmpArr );
    $tmpStr = sha1( $tmpStr );
    if( $tmpStr == $signature ) {
      return true;
    } else {
      return false;
    }
  }
}
?>

點選提交,驗證成功的話回到配置介面,點選“開啟”。如果提示“token驗證失敗”,可以在echo $echoStr;語句前加入ob_clean()。因為在輸出$echoStr之前可能會有一些快取內容,需要先清除,否則影響微信公眾平臺的識別。
三、通訊
微信公眾平臺與後臺伺服器採用xml格式通訊:

粉絲髮給公眾號訊息格式
<xml>
<ToUserName><![CDATA[公眾號]]></ToUserName>
<FromUserName><![CDATA[粉絲號]]></FromUserName>
<CreateTime>1460537339</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[歡迎開啟公眾號開發者模式]]></Content>
<MsgId>6272960105994287618</MsgId>
</xml> 

公眾號發給粉絲訊息格式
 <xml>
<ToUserName><![CDATA[粉絲號]]></ToUserName>
<FromUserName><![CDATA[公眾號]]></FromUserName>
<CreateTime>1460541339</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[test]]></Content>
</xml>

例子:

<?php
//   index.php [ 微信公眾平臺介面 ]

$wechatObj = new wechat();
$wechatObj->responseMsg();
class wechat {
 public function responseMsg() {
  //---------- 接 收 數 據 ---------- //
  $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //獲取POST資料
  //用SimpleXML解析POST過來的XML資料
  $postObj = simplexml_load_string($postStr,'SimpleXMLElement',LIBXML_NOCDATA);
  $fromUsername = $postObj->FromUserName; //獲取傳送方帳號(OpenID)
  $toUsername = $postObj->ToUserName; //獲取接收方賬號
  $keyword = trim($postObj->Content); //獲取訊息內容
  $time = time(); //獲取當前時間戳
  //---------- 返 回 數 據 ---------- //
  //返回訊息模板
  $textTpl = "<xml>
  <ToUserName><![CDATA[%s]]></ToUserName>
  <FromUserName><![CDATA[%s]]></FromUserName>
  <CreateTime>%s</CreateTime>
  <MsgType><![CDATA[%s]]></MsgType>
  <Content><![CDATA[%s]]></Content>
  <FuncFlag>0</FuncFlag>
  </xml>";
  $msgType = "text"; //訊息型別
  $contentStr = 'hello'; //返回訊息內容
  //格式化訊息模板
  $resultStr = sprintf($textTpl,$fromUsername,$toUsername,$time,$msgType,$contentStr);
  echo $resultStr; //輸出結果
 }
}
?>
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章