search
HomeBackend DevelopmentPHP Tutorial如何使用微信公众平台开发模式实现多客服_php实例

其实微信公众平台的多客服功能已经出来好久了,并且一出来的时候我就已经为自己的公众号实现了,原本以为大家都已经会了,但是今天还是有人问起这个多客服功能怎么使用,我找了下网上也没什么好的教程,今天我就给大家发一篇比较简单易懂的教程吧!

在这篇微信公众平台开发教程中,我们将介绍如何使用开发模式实现多客服系统。

一、回复多客服消息

在新的微信协议中,开发模式也可以接入客服系统。 开发者如果需要让用户使用客服系统,需要在接收到用户发送的消息时,返回一个MsgType为transfer_customer_service的消息,微信服务器在收到这条消息时,会把用户这次发送的和以后一段时间内发送的消息转发客服系统。

返回的消息举例如下

<xml>
  <ToUserName><![CDATA[touser]]></ToUserName>
  <FromUserName><![CDATA[fromuser]]></FromUserName>
  <CreateTime>1399197672</CreateTime>
  <MsgType><![CDATA[transfer_customer_service]]></MsgType>
</xml> 

该消息的实现如下(以方倍工作室的微信公众平台PHP SDK为基础)

   //回复多客服消息
  private function transmitService($object)
  {
    $xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[transfer_customer_service]]></MsgType>
</xml>";
    $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
    return $result;
  } 

二、触发多客服会话

一般情况下,用户想要咨询问题是,经常会问“你好”,“在吗”,这样的问题。

我们以这些词为触发关键词,当用户发送的文本消息内容中包含这些词的时候,就返回多客服消息给用户(用户在微信端感觉不到任何内容,但微信公众账号会将用户本次及以后一段时间的消息都转发到客服)。

实现代码如下:

 //接收文本消息
  private function receiveText($object)
  {
    $keyword = trim($object->Content);
    if (strstr($keyword, "投诉") || strstr($keyword, "你好") || strstr($keyword, "在吗")){
      $result = $this->transmitService($object);
    }
    return $result;
  }

三、完整代码

<&#63;php
/*
  方倍工作室
  CopyRight 2014 All Rights Reserved
*/
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
if (!isset($_GET['echostr'])) {
  $wechatObj->responseMsg();
}else{
  $wechatObj->valid();
}
class wechatCallbackapiTest
{
  //验证消息
  public function valid()
  {
    $echoStr = $_GET["echostr"];
    if($this->checkSignature()){
      echo $echoStr;
      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;
    }
  }
  //响应消息
  public function responseMsg()
  {
    $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
    if (!empty($postStr)){
      $this->logger("R ".$postStr);
      $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
      $RX_TYPE = trim($postObj->MsgType);
      switch ($RX_TYPE)
      {
        case "event":
          $result = $this->receiveEvent($postObj);
          break;
        case "text":
          $result = $this->receiveText($postObj);
          break;
      }
      $this->logger("T ".$result);
      echo $result;
    }else {
      echo "";
      exit;
    }
  }
  //接收事件消息
  private function receiveEvent($object)
  {
    switch ($object->Event)
    {
      case "subscribe":
        $content[] = array("Title" =>"欢迎关注方倍工作室", "Description" =>"使用方法:\n1.发送快递单号,例如6367532560,可查询快递详情", "PicUrl" =>"http://www.3856.cc/weixin/weixin/logo.jpg", "Url" =>"");
        break;
      default:
        $content = "receive a new event: ".$object->Event;
        break;
    }
    if(is_array($content)){
      if (isset($content[0])){
        $result = $this->transmitNews($object, $content);
      }else if (isset($content['MusicUrl'])){
        $result = $this->transmitMusic($object, $content);
      }
    }else{
      $result = $this->transmitText($object, $content);
    }
    return $result;
  }
  //接收文本消息
  private function receiveText($object)
  {
    $keyword = trim($object->Content);
    if($keyword == "时间" || $keyword == "测试"){
      $content = date("Y-m-d H:i:s",time());
      $result = $this->transmitText($object, $content);
    }
    //触发多客服模式
    else if (strstr($keyword, "您好") || strstr($keyword, "你好") || strstr($keyword, "在吗") || strstr($keyword, "有人吗")){
      $result = $this->transmitService($object);
      return $result;
    }
    return $result;
  }
  private function transmitText($object, $content)
  {
    $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
    $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
    return $result;
  }
  private function transmitNews($object, $newsArray)
  {
    if(!is_array($newsArray)){
      return;
    }
    $itemTpl = "  <item>
    <Title><![CDATA[%s]]></Title>
    <Description><![CDATA[%s]]></Description>
    <PicUrl><![CDATA[%s]]></PicUrl>
    <Url><![CDATA[%s]]></Url>
  </item>
";
    $item_str = "";
    foreach ($newsArray as $item){
      $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
    }
    $newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[]]></Content>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str</Articles>
</xml>";
    $result = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
    return $result;
  }
  private function transmitMusic($object, $musicArray)
  {
    $itemTpl = "<Music>
  <Title><![CDATA[%s]]></Title>
  <Description><![CDATA[%s]]></Description>
  <MusicUrl><![CDATA[%s]]></MusicUrl>
  <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
</Music>";
    $item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);
    $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[music]]></MsgType>
$item_str
</xml>";
    $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time());
    return $result;
  }
  //回复多客服消息
  private function transmitService($object)
  {
    $xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[transfer_customer_service]]></MsgType>
</xml>";
    $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
    return $result;
  }
  private function logger($log_content)
  {
    if(isset($_SERVER['HTTP_APPNAME'])){  //SAE
      sae_set_display_errors(false);
      sae_debug($log_content);
      sae_set_display_errors(true);
    }else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
      $max_size = 10000;
      $log_filename = "log.xml";
      if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
      file_put_contents($log_filename, date('H:i:s')." ".$log_content."\r\n", FILE_APPEND);
    }
  }
}
&#63;> 

本段代码经过测试,在自定义菜单中返回多客服消息,无法让用户进入多客服状态,使用多客服消息后,后续所有消息在一段时间内都将作为客服消息转发,原来的开发模式下的自动回复都将失效。

本文写的不好,还望海涵,有好的意见欢迎分享,大家共同学习进步。同时,感谢大家一直以来对脚本之家网站的支持。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software