<?php |
/** |
* @author heqing |
* @version v1.0 |
*/ |
|
|
//define your token |
define( "TOKEN" , "weixin" ); //这里填写的是你在微信上设置的TOKEN,但是必须保证与微信公众平台 接口配置信息一致 |
$wechatObj = new wechatCallbackapiTest(); |
$wechatObj ->valid(); //这里是测试网站配置信息和开发的是否一致。 |
|
$wechatObj ->responseMsg(); //新增加这一项,目的是调用responseMsg()这个功能。 |
|
|
|
class wechatCallbackapiTest |
{ |
|
//若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,否则接入失败。 |
|
public function valid() |
{ |
$echoStr = $_GET [ "echostr" ]; |
|
|
//valid signature , option |
if ( $this ->checkSignature()){ |
header( 'content-type:text' ); |
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 )) // $keyword是关键词,即为用户发送的信息 |
{ |
$msgType = "text" ; //文本格式的消息 |
$contentStr = "Welcome to wechat world!" ; //预制消息回复 |
|
if ( $keyword == "index" ) { |
$contentStr = "welcome to nongdaxy.com" ; |
} |
|
if ( $keyword == "首页" ) { |
$contentStr = "欢迎来到校园之窗" ; |
} |
$resultStr = sprintf( $textTpl , $fromUsername , $toUsername , $time , $msgType , $contentStr ); |
echo $resultStr ; |
} else { |
echo "Input something..." ; |
} |
|
|
} else { |
echo "" ; |
exit ; |
} |
} |
// 开发者通过检验signature对请求进行校验 |
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; |
} |
} |
} |
|
|
?> |
by: 发表于:2017-10-27 09:35:26 顶(0) | 踩(0) 回复
??
回复评论