Skip to content

Instantly share code, notes, and snippets.

@no13bus
Created April 9, 2014 03:34
Show Gist options
  • Select an option

  • Save no13bus/10223787 to your computer and use it in GitHub Desktop.

Select an option

Save no13bus/10223787 to your computer and use it in GitHub Desktop.
<?php
/**
* wechat php test
*/
//define your token
define("TOKEN", "iambus");
$wechatObj = new wechatCallbackapiTest();
if (isset($_GET['echostr'])) {
$wechatObj->valid();
}else{
$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);
$createtime = $postObj->CreateTime;
$msgtype = $postObj->MsgType;
$location_x = $postObj->Location_X;
$location_y = $postObj->Location_Y;
$scale = $postObj->Scale;
$label = $postObj->Label;
$msgid = $postObj->MsgId;
$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";
if (!empty($location_x)) {
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, gettype($location_x));
}else{
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $keyword);
}
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, SORT_STRING);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment