前言
此文接着前文,试验了一下图片回复的例子。
微信官方接受消息参数说明见:https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_standard_messages.html ;
微信官方参数被动回复消息参数说明见: https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Passive_user_reply_message.html#1
重要参数说明
回复和接收整体参数都差不多,但是也有几处不同。
1. MsgType: 消息类型不同:图片为:image
2. 图片多了下列几个参数,其中: MediaId 特别注意,因为在被动回复需要用
PicUrl | 图片链接(由系统生成) |
MediaId | 图片消息媒体 id,可以调用获取临时素材接口拉取数据。 |
MsgId | 消息 id,64 位整型 |
代码示例(基于昨天的微信文本回复改的)
代码只有基础功能,用户发送啥回复啥。支持图片和问题。复杂一点的自定义图片还在学习中,学会再更博文。
<?php
// 接收参数
define("TOKEN", "test123456");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();
class wechatCallbackapiTest{
public function valid() {
$echoStr = $_GET["echostr"];
//valid signature , option
if($this->checkSignature()){
echo $echoStr;
$this->responseMsg();
exit;
}
}
public function transmitText($object, $content) {
$xmlTpl = '<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>';
$res = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
return $res;
}
public function transmitImage($object, $content) {
$xmlTpl = '<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
<Image>
<MediaId><![CDATA[%s]]></MediaId>
</Image>
</xml>';
$res = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);
return $res;
}
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();
switch ($postObj->MsgType) {
case 'text':
$content = '<a href="https://itzhai.cn">'.$keyword.'</a>';
$res = $this->transmitText($postObj, $content);
break;
case 'image':
$content = $postObj->MediaId;
$res = $this->transmitImage($postObj, $content);
break;
default:
// code...
break;
}
echo $res;
}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;
}
}
}
最终效果
不要喷我此处无图,原因是自己实践一下更好,代码我自己测试是没问题的。还有就是 wordpress 截图粘贴插件不能用了,我很苦恼。图片在手机上,下次看用微信电脑版有法没。