Home  >  Article  >  Backend Development  >  How to implement WeChat public account event push in PHP

How to implement WeChat public account event push in PHP

王林
王林Original
2023-05-13 12:10:353577browse

WeChat official accounts have become an important channel for many companies in marketing and services, and the event push function is also an extremely important part. This article will introduce how to implement WeChat official account event push in PHP, so that enterprises can better interact with users.

1. Overview of WeChat public account event push

WeChat public account event push refers to the WeChat server actively pushing specific types of events to the public account during the interaction between the user and the public account. Such as following, unfollowing, clicking on the menu, etc. Official accounts can provide better user experience and services by handling these events.

2. PHP environment construction

Before implementing WeChat public account event push, you first need to set up a PHP development environment. This article uses XAMPP as an example to introduce the specific steps:

  1. Download and install XAMPP (it is recommended to choose the PHP7 version);
  2. Start the Apache server and MySQL database;
  3. Enter "localhost" in the browser to confirm that you can access the XAMPP welcome page normally;
  4. Create a new directory under the XAMPP root directory and name it "wechat", which will be used to store WeChat development code.

3. WeChat public account development configuration

After the PHP development environment is set up, the WeChat public account needs to be configured to facilitate interaction with PHP. The specific steps are as follows:

  1. Log in to the WeChat public platform, enter the "Development" - "Basic Configuration" page, and obtain the AppID and AppSecret.
  2. Find the "Server Configuration" option at the bottom of the page, fill in the server address, Token and other information, and enable the "Receive Messages" and "Receive Events" functions, save and take effect.
  3. Verify the validity of the server address. In the "Server Configuration" page, click "Submit", and the system will send a GET request to the filled in server address and return echostr according to the configuration requirements. If the return is successful, it means that the verification is passed. If the verification fails, reconfiguration is required.

4. Write PHP code

After the development and configuration of the WeChat public account is completed, you can write the relevant code in PHP. The code implementation will be divided into three parts.

  1. Get the received message or event and parse it

The WeChat official account will send the received message or event to the server address configured by the official account, so it needs to be passed PHP receives and parses this data. The specific implementation code is as follows:

$postdata = $GLOBALS['HTTP_RAW_POST_DATA'];  //获取POST数据
if (!empty($postdata)) {  //判断数据是否为空
    $postObj = simplexml_load_string($postdata, 'SimpleXMLElement', LIBXML_NOCDATA);  //将XML数据解析为对象
    $msgType = $postObj->MsgType;   //获取消息类型
    if ($msgType == 'event') {   //判断消息是否为事件
        $event = $postObj->Event;  //获取事件类型
        //处理事件
    } else {
        //处理消息
    }
}
  1. Processing events and messages

After receiving a message or event, it needs to be processed accordingly according to different types. The specific implementation code is as follows:

(1) Processing events of interest:

if ($event == 'subscribe') {
    $toUser = $postObj->FromUserName;  //获取用户OpenID
    $fromUser = $postObj->ToUserName;  //获取公众号原始ID
    $time = time();  //获取当前时间戳
    $msgType = 'text';  //回复消息类型为文本
    $content = '欢迎关注我们的公众号!';  //回复消息内容
    $template = '<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[%s]]></MsgType>
        <Content><![CDATA[%s]]></Content>
        </xml>';
    $info = sprintf($template, $toUser, $fromUser, $time, $msgType, $content);  //构造回复消息XML
    echo $info;  //返回回复消息给微信服务器
}

(2) Processing text messages:

if ($msgType == 'text') {
    $toUser = $postObj->FromUserName;  //获取用户OpenID
    $fromUser = $postObj->ToUserName;  //获取公众号原始ID
    $time = time();  //获取当前时间戳
    $msgType = 'text';  //回复消息类型为文本
    $content = '您发送的是文本消息,我们会尽快回复您的问题。';  //回复消息内容
    $template = '<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[%s]]></MsgType>
        <Content><![CDATA[%s]]></Content>
        </xml>';
    $info = sprintf($template, $toUser, $fromUser, $time, $msgType, $content);  //构造回复消息XML
    echo $info;  //返回回复消息给微信服务器
}
  1. Generate signature

In the development of WeChat public accounts, signatures need to be used to ensure the security of the interaction process. The specific implementation method is as follows:

$signature = $_GET["signature"];  //获取加密签名
$timestamp = $_GET["timestamp"];  //获取时间戳
$nonce = $_GET["nonce"];  //获取随机数
$token = "你在微信公众平台设置的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;
}

5. Deployment test

After the PHP code is written, the code needs to be deployed to the server for testing. The specific steps are as follows:

  1. Upload the written code to the "htdocs/wechat" directory under the XAMPP directory.
  2. Enter "localhost/wechat" in the browser to confirm that the server environment deployment is completed correctly.
  3. Conduct an event push test on the WeChat public platform to check whether the acceptance and processing are normal.

6. Summary

Through the implementation of the above steps, WeChat official account event push can be successfully implemented in PHP. Enterprises can use this function to better interact with users and enhance brand influence and user satisfaction.

The above is the detailed content of How to implement WeChat public account event push in PHP. For more information, please follow other related articles on the PHP Chinese website!

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