How to enable the mini program customer service function

angryTom
Release: 2020-03-13 13:26:39
Original
3453 people have browsed it

How to enable the mini program customer service function

How to enable the customer service function of the mini program

To enable the customer service function of a customized mini program, two steps are required,

Step one: Activate the message push function on your own WeChat platform

The details are in the official wiki https://developers.weixin.qq.com/miniprogram/ introduction/custom.html#Fill in the message push configuration

Step 2: Complete your own backend

Prerequisite: Your server can be accessed by WeChat.

Process: After the user initiates an event, he sends a data packet to the WeChat server. If you enable the message push service (the first step), the WeChat server will process and forward the data. The specific format is xml or json depends on your choice in the WeChat backend. The json I chose here, WeChat will return the data packet to you by actively calling your interface. If you want to respond to a certain message from the user, you need an interface to send your data to the WeChat server. The response packet contains the customer service's openid. See the code for specific details.

<?php
header(&#39;Content-type:text&#39;);
define("TOKEN", "mytoken");

class Mini extends Controller{
    private $appid = &#39;&#39;;
    private $secret = &#39;&#39;;
    public function check(){     //校验服务器地址URL
        if (isset($_GET[&#39;echostr&#39;])) {
            $this->valid();
        }else{
            $this->responseMsg();
        }
    }
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            header(&#39;content-type:text&#39;);
            echo $echoStr;
            exit;
        }else{
            echo $echoStr.&#39;+++&#39;.TOKEN;
            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 = file_get_contents(&#39;php://input&#39;);//因为我的环境是php7
        if (!empty($postStr) && is_string($postStr)){
            $postArr = json_decode($postStr,true);
            if(!empty($postArr[&#39;MsgType&#39;]) && $postArr[&#39;MsgType&#39;] == &#39;text&#39;){   //文本消息
                $fromUsername = $postArr[&#39;FromUserName&#39;];   //发送者openid
                $toUserName = $postArr[&#39;ToUserName&#39;];       //小程序id
                $textTpl = array(
                    "ToUserName"=>$fromUsername,
                    "FromUserName"=>$toUserName,
                    "CreateTime"=>time(),
                    "MsgType"=>"transfer_customer_service",
                );
                exit(json_encode($textTpl));
            }elseif(!empty($postArr[&#39;MsgType&#39;]) && $postArr[&#39;MsgType&#39;] == &#39;image&#39;){ //图文消息
                $fromUsername = $postArr[&#39;FromUserName&#39;];   //发送者openid
                $toUserName = $postArr[&#39;ToUserName&#39;];       //小程序id
                $textTpl = array(
                    "ToUserName"=>$fromUsername,
                    "FromUserName"=>$toUserName,
                    "CreateTime"=>time(),
                    "MsgType"=>"transfer_customer_service",
                );
                exit(json_encode($textTpl));
            }elseif($postArr[&#39;MsgType&#39;] == &#39;event&#39; && $postArr[&#39;Event&#39;]==&#39;user_enter_tempsession&#39;){ 
                $fromUsername = $postArr[&#39;FromUserName&#39;];  

           $data = array(
                               "touser"=>$fromUsername,
                               "msgtype"=>"link",
                                "link"=>[
                                    "title"=>&#39;this is title&#39;,
                                    "description"=> "Is Really A Happy Day",
                                    "url":=>"URL",
                                    "thumb_url"=>"THUMB_URL"
                                ]
                           );
          $json = json_encode($data,JSON_UNESCAPED_UNICODE); 
                $access_token = $this->get_accessToken();
                $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
                //将数据返给微信服务器进行转发。
                $this->curl_post($url,$json);
                
            }else{
                exit(&#39;aaa&#39;);
            }
        }else{
            echo "";
            exit;
        }
    }
  
    public function get_accessToken(){
        if(cache(&#39;access_token&#39;)){
            return cache(&#39;access_token&#39;);
        }
        /* 不在有效期,重新发送请求,获取access_token */
        else{
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->secret}";
            $result = curl_get_https($url);
            $res = json_decode($result,true);   //json字符串转数组
            if($res){
                cache(&#39;access_token&#39;,$res[&#39;access_token&#39;],7100);
                return cache(&#39;access_token&#39;);
            }else{
                return &#39;api return error&#39;;
            }
        }
    }
    /**
     * @Author   callmelx
     * @DateTime 2018-10-06
     * @return   [type]     [description]
     */
    public function curl_post($url,$data=&#39;&#39;){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($curl, CURLOPT_HTTPHEADER, $headers );
        $output = curl_exec($curl);
        if (curl_errno($curl)) {
            echo &#39;Errno&#39;.curl_error($curl);//捕抓异常
        }
        curl_close($curl);
        if($output == 0){
            echo &#39;success&#39;;exit;
        }
    }
}
Copy after login

There are several pitfalls that you need to pay attention to. If your token verification always fails:

1. It is recommended that you take a look at the token of your server. Whether it is the same as the current token.

2. If you find that there is absolutely no problem with your code, and there is absolutely no problem with the token, and you still get an error, then I suggest you check the permissions of your server's file . If You are using the TP framework. Check whether your runtime is set to 777. If you set it to 755, it may not work.

Recommended learning: Small program development

The above is the detailed content of How to enable the mini program customer service function. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!