很久木有來寫博文!最近研究微信接口開發,從網上查到的資料不是很多,就把自己研究成果跟大家分享一下!
首先我們需要申請一個微信公衆賬号,因為這個公衆賬号是公司的,是以不友善透露給大家! 相信簡單的申請工作都是沒有問題的!申請成功之後,菜單欄會出現“進階功能”,如下圖:

裡面有2中模式可以選擇,“編輯模式”和“開發模式”,上面都詳細的描述就不再想大家作解釋了!
這裡我們要講的是開發模式。好了,到現在為止就可以進入開發模式的講解了!
進入開發模式之後,我們需要在http://mp.weixin.qq.com/wiki/index.php?title=%E6%B6%88%E6%81%AF%E6%8E%A5%E5%8F%A3%E6%8C%87%E5%8D%97這個頁面最底部,有一個demo例子,下載下傳之後,放到伺服器的某個目錄裡面。
然後我們在配置URL和Token值,如下圖:
URL:填寫我們放demo的通路網址,例如:http://www.123.com/wx_sample.php
Token:這個值可以随便寫。
打開檔案wx_sample.php,修改下面的内容
define("TOKEN", "weixin"); //修改成自己填寫的token
<?php
/**
* wechat php test
*/
// define
// your
// token
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->responseMsg();
class wechatCallbackapiTest {
public function valid() {
$echoStr = $_GET["echostr"];
// valid
// signature
// ,
// option
if($this->checkSignature()) {
echo $echoStr;
exit();
}
}
public function responseMsg() {
// get
// post
// data,
// May
// be
// due
// to
// the
// different
// environments
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
// extract
// 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 = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>";
if(!empty($keyword)) {
$msgType = "text";
$contentStr = "Welcome to wechat world!";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
} else {
echo "Input something...";
}
} 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;
}
}
}
?>