一个分享WordPress、Zblog、Emlog、Typecho等主流博客的教程网站!
当前位置:网站首页 > 其他相关教程 > 正文

微信公众号开发消息自动回复服务器端php代码

作者:xlnxin发布时间:2022-10-02分类:其他相关教程浏览:542


导读:关注事件与一般的文本消息有两处不同,一是msgtype值是event,二是增加了event值是subscribe。由于官方文档(最初的wx_sample.php)没有提取这个参数,...

关注事件与一般的文本消息有两处不同,一是msgtype值是event,二是增加了event值是subscribe。由于官方文档(最初的wx_sample.php)没有提取这个参数,需要我们自己提取。在程序中增加两个变量$msgtype和$event。

<?php
/**
 * wechat php test
 */
 
//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)){
 /* libxml_disable_entity_loader is to prevent xml external entity injection,
  the best way is to check the validity of xml by yourself */
 libxml_disable_entity_loader(true);
  $postobj = simplexml_load_string($poststr'simplexmlelement', libxml_nocdata);
 $fromusername $postobj->fromusername;
 $tousername $postobj->tousername;
 $keyword = trim($postobj->content);
 $time = time();
 $msgtype $postobj->msgtype;//消息类型
 $event $postobj->event;//时间类型,subscribe(订阅)、unsubscribe(取消订阅)
 $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>";
  
 switch($msgtype){
  case "event":
  if($event=="subscribe"){
  $contentstr "hi,欢迎关注海仙日用百货!"."\n"."回复数字'1',了解店铺地址."."\n"."回复数字'2',了解商品种类.";
  }
  break;
  case "text":
  switch($keyword){
  case "1":
  $contentstr "店铺地址:"."\n"."杭州市江干艮山西路233号新东升市场地下室第一排.";
  break;
  case "2":
  $contentstr "商品种类:"."\n"."杯子、碗、棉签、水桶、垃圾桶、洗碗巾(刷)、拖把、扫把、"
   ."衣架、粘钩、牙签、垃圾袋、保鲜袋(膜)、剪刀、水果刀、饭盒等.";
  break;
  default:
  $contentstr "对不起,你的内容我会稍后回复";
  }
  break;
 }
 $msgtype "text";
 $resultstr = sprintf($texttpl$fromusername$tousername$time$msgtype$contentstr);
 echo $resultstr;
 }else {
 echo "";
 exit;
 }
 }
 
 private function checksignature()
 {
 // you must define token by yourself
 if (!defined("token")) {
 throw new exception('token is not defined!');
 }
 
 $signature $_get["signature"];
 $timestamp $_get["timestamp"];
 $nonce $_get["nonce"];
 
 $token = token;
 $tmparr array($token$timestamp$nonce);
 // use sort_string rule
 sort($tmparr, sort_string);
 $tmpstr = implode( $tmparr );
 $tmpstr = sha1( $tmpstr );
 
 if$tmpstr == $signature ){
 return true;
 }else{
 return false;
 }
 }
}
 
?>

标签:服务器程序