>  기사  >  백엔드 개발  >  WeChat 공개 계정 개발을 위한 문자 메시지 자동 회신 PHP 코드 개발_php 예

WeChat 공개 계정 개발을 위한 문자 메시지 자동 회신 PHP 코드 개발_php 예

PHP中文网
PHP中文网원래의
2016-08-17 13:02:352954검색

본 글의 예시는 참고용으로 PHP WeChat 문자 메시지 자동 응답 코드를 공유합니다.

1. PHP 샘플 코드 다운로드
다운로드 주소 1: http://xiazai.php.net/201608/yuanma/phpwx(php.net).rar
다운로드 주소 2: https://mp.weixin.qq.com/wiki/home/ index.html(개발시작-"접근안내-"PHP 샘플코드 다운로드)

2.wx_sample.php 초기코드

valid();

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();
 $textTpl = "%s0"; 
 if(!empty( $keyword ))
 {
  $msgType = "text";
  $contentStr = "Welcome to wechat world!";
  $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
  echo $resultStr;
 }else{
  echo "Input something...";
 }

 }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;
 }
 }
}

?>

3. 응답 메시지 메서드를 호출합니다.
wx_sample에서 $wechatObj->valid를 주석 처리합니다. php 파일(); 아래에 "$wechatObj->responseMsg();"를 추가하세요.

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();
 $textTpl = "%s0"; 
 if(!empty( $keyword ))
 {
  $msgType = "text";
  $contentStr = "Welcome to wechat world!";
  $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
  echo $resultStr;
 }else{
  echo "Input something...";
 }

 }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;
 }
 }
}

?>

4. 키워드 자동 답글 및 팔로우 답글
$keyword 은 사용자가 WeChat에서 보낸 문자 메시지를 저장합니다.
공식 개발자 문서: https://mp.weixin.qq.com/wiki/home/index.html(메시지 관리-"메시지 수신-이벤트 푸시 수신-"1. 팔로우/언팔로우 이벤트)

팔로우 이벤트와 일반 문자 메시지의 차이점은 두 가지입니다. 하나는 MsgType 값이 event이고, 다른 하나는 추가된 Event 값이 subscribe라는 점입니다. 공식 문서(원본 wx_sample.php)에서는 이 매개변수를 추출하지 않으므로 직접 추출해야 합니다. 두 개의 변수 $msgType 및 $event를 프로그램에 추가합니다.

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 = "%s0"; 
  
 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;
 }
 }
}


?>

위 내용은 위챗 공개계정 개발을 위한 문자메시지 자동응답 php코드_php 예시 전체 내용이길 바랍니다. 도움이 필요하시면 PHP 중국어 웹사이트(www.php.cn)에서 더 많은 관련 콘텐츠를 확인하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.