如今互联网时代微信成为手机中热门的聊天软件,对于网站来说,微信的公共平台的诞生给了营销又增加了一道门。微信的APP一直想弄来着,最近研究了一下。
官方有两种方式 一种是在微信官方里面操作信息和回复。这种叫做-编辑模式,另一种是在自己的网站集成微信。这种叫做-开发模式。两种模式只能开一种。
编辑模式很简单。在里面可以设定关键词,然后用户发信息与这个关键词匹配。就会回复相应内容、
开发模式就相对能复杂些,流程如下:
验证网站-微信会发送验证及内容-通过验证接受内容-在5秒之内回复-用户接受-完成。
以下是代码:官方案例有些问题。这个是可以回复天气预报的。比如说回复 北京 就会收到关于北京的天气预报。掉的天气预报借口。
//define your token
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
//$wechatObj->valid();//验证完成后可将此行代码注释掉
$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);
file_put_contents('tst.txt',$keyword);
$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";
$url = "http://api2.sinaapp.com/search/weather/?appkey=20130430&appsecert=fa6095e113cd28fd&reqtype=text&keyword=".urlencode($keyword);
$weatherJson = file_get_contents($url);
$weather = json_decode($weatherJson, true);
$con= $weather['text']['content'];
if($con){
$contentStr=$con;
}else{
$contentStr="beijing"
}
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}else{
echo "Input something...";
}
}else {
echo "";
exit;
}
}
function substring($str, $start, $len) {
$tmpstr = "";
$strlen = $start + $len;
for($i = 0; $i < $strlen; $i++) {
if(ord(substr($str, $i, 1)) > 0xa0) {
$tmpstr .= substr($str, $i, 2);
$i++;
} else
$tmpstr .= substr($str, $i, 1);
}
return $tmpstr;
}
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;
}
}
}