调用该系列接口之前,需要先在配置文件中修改好对应的配置参数,否则将调用失败,同时该系列接口调用失败将不会通知到Error::handle()
错误回调通知中。
namespace app\http;
use x\controller\Http;
class Index extends Http
{
/**
* @RequestMapping(route="/", title="主页")
*/
public function index() {
// Token校验
$obj = new \wechat\Wechat();
// 直接点击微信公众号的验证按钮查看结果就行,反正是一次性的
$obj->official()->token()->check();
}
}
namespace app\http;
use x\controller\Http;
class Index extends Http
{
/**
* @RequestMapping(route="/", title="主页")
*/
public function index() {
$obj = new \wechat\Wechat();
// 抓取消息,并自动解密
$xml = $obj->official()->message_reply()->xml();
# FromUserName : 发送方帐号(一个OpenID)
$fromUsername = $xml->FromUserName;
# toUsername : 开发者微信号
$toUsername = $xml->ToUserName;
# keyword : 发送过来的内容
$keyword = trim($xml->Content);
# 服务器时间戳
$time = time();
# 这里的XML格式不能改变,是微信规定的格式,里面的参数使用[%s]占位符占用,到时候填充完成,再发送回给微信
$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 = "SW-X Hello word!";
if ($keyword == '小黄牛') {
$contentStr = "真帅~~";
}
// 替换占位符
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
// 回复消息,并自动加密
$obj->official()->message_reply()->send($resultStr);
}
}
}