PHP對接微信公眾平台訊息介面開發流程教程_PHP教程

來源:互聯網
上載者:User
一、寫好介面程式

在你的伺服器上上傳好一個介面程式檔案,如http://www.yourdomain.com/weixin.php 內容如下:

複製代碼 代碼如下:define("TOKEN", "weixin");//自己定義的token 就是個通訊的私密金鑰
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();
//$wechatObj->responseMsg();
class wechatCallbackapiTest
{
public function valid()
{
$echoStr = $_GET["echostr"];
if($this->checkSignature()){
echo $echoStr;
exit;
}
}
public function responseMsg()
{
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
if (!empty($postStr)){
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$keyword = trim($postObj->Content);
$time = time();
$textTpl = "
%s
%s
%s
%s
%s
0
";
if(!empty( $keyword ))
{
$msgType = "text";
$contentStr = '你好啊,屌絲';
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}else{
echo '咋不說哈呢';
}
}else {
echo '咋不說哈呢';
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;
}
}
}
?>


二、配置公眾平台回複介面


設定回複介面,填好URL和Token(url填上面的http://www.yourdomain.com/weixin.php,token必須跟上面程式裡面定義的Token一致)



三、驗證介面

用自己的個人關注下你的公眾帳號,給這個帳號發一條訊息過去,收到原樣的訊息返回,即驗證成功了。

四、開始自訂回複

注釋掉$wechatObj->valid(); 這行,同時去掉//$wechatObj->responseMsg();這行的注釋。
你可以修改responseMsg函數裡面的代碼,根據使用者的訊息類型('text','image','location')和訊息內容來回複使用者不同的內容。
訊息介面就可以使用了,發個訊息試試看吧?

1.封裝weixin.class.php

由於公眾平台的通訊使用的是特定格式的XML資料,每次接受和回複都要去做一大堆的資料處理。
我們就考慮在這個基礎上做一次封裝,weixin.class.php,代碼如下:
複製代碼 代碼如下:class Weixin
{
public $token = '';//token
public $debug = false;//是否debug的狀態標示,方便我們在調試的時候記錄一些中間資料
public $setFlag = false;
public $msgtype = 'text'; //('text','image','location')
public $msg = array();

public function __construct($token,$debug)
{
$this->token = $token;
$this->debug = $debug;
}
//獲得使用者發過來的訊息(訊息內容和訊息類型 )
public function getMsg()
{
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
if ($this->debug) {
$this->write_log($postStr);
}
if (!empty($postStr)) {
$this->msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$this->msgtype = strtolower($this->msg['MsgType']);
}
}
  //回複簡訊
public function makeText($text='')
{
$CreateTime = time();
$FuncFlag = $this->setFlag ? 1 : 0;
$textTpl = "
{$this->msg['FromUserName']}
{$this->msg['ToUserName']}
{$CreateTime}
1
]>
%s
%s
";
return sprintf($textTpl,$text,$FuncFlag);
}
//根據數組參數回複圖文訊息
public function makeNews($newsData=array())
{
$CreateTime = time();
$FuncFlag = $this->setFlag ? 1 : 0;
$newTplHeader = "
{$this->msg['FromUserName']}
{$this->msg['ToUserName']}
{$CreateTime}
news
%s
%s";
$newTplItem = "
<![CDATA[%s]]>
%s
%s
%s
";
$newTplFoot = "
%s
";
$Content = '';
$itemsCount = count($newsData['items']);
$itemsCount = $itemsCount < 10 ? $itemsCount : 10;//公眾平台圖文回複的訊息一次最多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,$newsData['content'],$itemsCount);
$footer = sprintf($newTplFoot,$FuncFlag);
return $header . $Content . $footer;
}
public function reply($data)
{
if ($this->debug) {
$this->write_log($data);
}
echo $data;
}
public function valid()
{
if ($this->checkSignature()) {
if( $_SERVER['REQUEST_METHOD']=='GET' )
{
echo $_GET['echostr'];
exit;
}
}else{
write_log('認證失敗');
exit;
}
}
private function checkSignature()
{
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];

$tmpArr = array($this->token, $timestamp, $nonce);
sort($tmpArr);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );

if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
private function write_log($log){
//這裡是你記錄調試資訊的地方 請自行完善 以便中間調試
}
}
?>

2.調用weixin.class.php

把你的公眾平台主介面檔案(如前面定義的http://www.yourdomain.com/weixin.php)中,修改代碼為:
複製代碼 代碼如下:include_once('weixin.class.php');//引用剛定義的訊息處理類
define("TOKEN", "mmhelper");
define('DEBUG', true);
$weixin = new Weixin(TOKEN,DEBUG);//執行個體化
$weixin->getMsg();
$type = $weixin->msgtype;//訊息類型
$username = $weixin->msg['FromUserName'];//哪個使用者給你發的訊息,這個$username是加密之後的,但是每個使用者都是一一對應的
if ($type==='text') {
if ($weixin->msg['Content']=='Hello2BizUser') {//使用者第一次關注你的帳號的時候,你的公眾帳號就會受到一條內容為'Hello2BizUser'的訊息
$reply = $weixin->makeText('歡迎你關注哦,屌絲');
}else{//這裡就是使用者輸入了文本資訊
$keyword = $weixin->msg['Content']; //使用者的簡訊內容
include_once("chaxun.php");//簡訊 調用查詢程式
$chaxun= new chaxun(DEBUG,$keyword,$username);
$results['items'] =$chaxun->search();//查詢的代碼

$reply = $weixin->makeNews($results);
}
}elseif ($type==='location') {
//使用者發送的是位置資訊 稍後的文章中會處理
}elseif ($type==='image') {
//使用者發送的是圖片 稍後的文章中會處理
}elseif ($type==='voice') {
//使用者發送的是聲音 稍後的文章中會處理
}
$weixin->reply($reply);
?>

3.查詢代碼

還需要將資料庫裡面的查詢結果格式化為特定的形式
複製代碼 代碼如下:public function search(){
$record=array(); //定義返回結果的數組
$list = $this->search($this->keyword);//普通的根據關鍵詞查詢資料庫的操作 代碼就不用分享了
    if(is_array($list)&&!empty($list)){
foreach($list as $msg){
        $record[]=array(//以下代碼,將資料庫中查詢返回的數組格式化為返回訊息能接收的數組形式,即title、description、picurl、url 詳見官方的文檔描述
'title' =>$msg['title'],
'description' =>$msg['discription'],
'picurl' => $msg['pic_url'],
'url' =>$msg['url']
);
        }
    }
    return $record;
}
?>

http://www.bkjia.com/PHPjc/745823.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/745823.htmlTechArticle一、寫好介面程式 在你的伺服器上上傳好一個介面程式檔案,如http://www.yourdomain.com/weixin.php 內容如下: 複製代碼 代碼如下: ?php define("TO...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.