>  기사  >  위챗 애플릿  >  php WeChat 공개 계정 개발 (3) php는 간단한 WeChat 문자 커뮤니케이션을 구현합니다.

php WeChat 공개 계정 개발 (3) php는 간단한 WeChat 문자 커뮤니케이션을 구현합니다.

黄舟
黄舟원래의
2018-05-15 16:28:561979검색

WeChat 개발 전 토큰을 설정해야 합니다. 이는 WeChat에서 설정하며 WeChat 통신을 구현하기 위해 임의로 설정할 수 있습니다. 다음은 다른 사람이 작성한 WeChat 클래스입니다. 꽤 좋은 기능을 가지고 있습니다. weixin.class.php 코드는 다음과 같습니다

<?php
class Weixin
{
 public $token = &#39;&#39;;//token
 public $debug = false;//是否debug的状态标示,方便我们在调试的时候记录一些中间数据
 public $setFlag = false;
 public $msgtype = &#39;text&#39;; //(&#39;text&#39;,&#39;image&#39;,&#39;location&#39;)
 public $msg = array();
 
 public function __construct($token,$debug)
 {
 $this->token = $token;
 $this->debug = $debug;
 }
//获得用户发过来的消息(消息内容和消息类型 )
 public function getMsg()
 {
 $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
 
 if (!empty($postStr)) {
  $this->msg = (array)simplexml_load_string($postStr, &#39;SimpleXMLElement&#39;, LIBXML_NOCDATA);
  $this->msgtype = strtolower($this->msg[&#39;MsgType&#39;]);
 }
 }
//回复文本消息
 public function makeText($text=&#39;&#39;)
 {
 $CreateTime = time();
 $FuncFlag = $this->setFlag ? 1 : 0;
 $textTpl = "<xml>
  <ToUserName><![CDATA[{$this->msg[&#39;FromUserName&#39;]}]]></ToUserName>
  <FromUserName><![CDATA[{$this->msg[&#39;ToUserName&#39;]}]]></FromUserName>
  <CreateTime>{$CreateTime}</CreateTime>
  <MsgType><![CDATA[text]]></MsgType>
  <Content><![CDATA[%s]]></Content>
  <FuncFlag>%s</FuncFlag>
  </xml>";
 return sprintf($textTpl,$text,$FuncFlag);
 }
 
//根据数组参数回复图文消息
 public function makeNews($newsData=array())
 {
 $CreateTime = time();
 $FuncFlag = $this->setFlag ? 1 : 0;
 $newTplHeader = "<xml>
  <ToUserName><![CDATA[{$this->msg[&#39;FromUserName&#39;]}]]></ToUserName>
  <FromUserName><![CDATA[{$this->msg[&#39;ToUserName&#39;]}]]></FromUserName>
  <CreateTime>{$CreateTime}</CreateTime>
  <MsgType><![CDATA[news]]></MsgType>
  <Content><![CDATA[%s]]></Content>
  <ArticleCount>%s</ArticleCount><Articles>";
 $newTplItem = "<item>
  <Title><![CDATA[%s]]></Title>
  <Description><![CDATA[%s]]></Description>
  <PicUrl><![CDATA[%s]]></PicUrl>
  <Url><![CDATA[%s]]></Url>
  </item>";
 $newTplFoot = "</Articles>
  <FuncFlag>%s</FuncFlag>
  </xml>";
 $Content = &#39;&#39;;
 $itemsCount = count($newsData[&#39;items&#39;]);
 $itemsCount = $itemsCount < 10 ? $itemsCount : 10;//微信公众平台图文回复的消息一次最多10条
 if ($itemsCount) {
  foreach ($newsData[&#39;items&#39;] as $key => $item) {
  if ($key<=9) {
   $Content .= sprintf($newTplItem,$item[&#39;title&#39;],$item[&#39;description&#39;],$item[&#39;picurl&#39;],$item[&#39;url&#39;]);
  }
  }
 }
 $header = sprintf($newTplHeader,$newsData[&#39;content&#39;],$itemsCount);
 $footer = sprintf($newTplFoot,$FuncFlag);
 return $header . $Content . $footer;
 }
 public function reply($data)
 {
 
 echo $data;
 }
 public function valid()
 {
 if ($this->checkSignature()) {
  if( $_SERVER[&#39;REQUEST_METHOD&#39;]==&#39;GET&#39; )
  {
  echo $_GET[&#39;echostr&#39;];
  exit;
  }
 }else{
  
  exit;
 }
 }
 private function checkSignature()
 {
 $signature = $_GET["signature"];
 $timestamp = $_GET["timestamp"];
 $nonce = $_GET["nonce"];
 
 $tmpArr = array($this->token, $timestamp, $nonce);
 sort($tmpArr);
 $tmpStr = implode( $tmpArr );
 $tmpStr = sha1( $tmpStr );
 
 if( $tmpStr == $signature ){
  return true;
 }else{
  return false;
 }
 }
 
}
?>

그러면 정식으로 개발됩니다. Baidu SVN 주소를 사용하여 weixinapi.php 파일을 생성합니다. 배경 설정에 따라 이름이 지정됩니다.

<?php
define("TOKEN", "");
define(&#39;DEBUG&#39;, false);
include_once(&#39;weixin.class.php&#39;);
require_once("db.php");
  
$weixin = new Weixin(TOKEN,DEBUG);//实例化
$weixin->getMsg();
$type = $weixin->msgtype;//消息类型
$keyword = $weixin->msg[&#39;Content&#39;];//获取的文本
if ($type===&#39;text&#39;) {
$reply = $weixin->makeText($key);
}elseif($type===&#39;event&#39;){//第一次关注推送事件
 $reply = $weixin->makeText("欢迎关注");
}else{//其他类型
$reply = $weixin->makeText("暂时没有图片,声音,地理位置等功能,后续开发会增加,感谢你关注");
}

$weixin->reply($reply);

이렇게 해서 처음으로 이벤트 답글, 텍스트 답글이 아닌 텍스트 답글에 중점을 두고 여기에 입력한 내용이 반환됩니다.
구체적인 구현 기능은 문자 답장에 기재되어 있습니다.
다른 기능은 당분간 구현되지 않을 예정이며, 구체적인 개발 내용은 다음 섹션에서 논의하겠습니다.

위 내용은 위챗 공개계정 개발(3)간단한 위챗 문자소통을 구현하기 위한 php의 내용이며, 더 많은 관련 내용은 PHP 중국어 홈페이지(www.php.cn)를 참고해주세요. )!

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