Home  >  Article  >  Backend Development  >  Example to explain how to implement WeChat push information function in PHP

Example to explain how to implement WeChat push information function in PHP

PHPz
PHPzOriginal
2023-04-12 14:44:402156browse

With the continuous development of the Internet, WeChat has become one of the indispensable tools in people's lives. Many websites and applications need to push information to users' WeChat in real time, and PHP, as a popular server-side programming language, can realize the function of pushing information to users through WeChat public accounts. So, today we will introduce how to use PHP to push information to WeChat.

First of all, we need to obtain the developer account, password, AppID, AppSecret and other information of the WeChat official account. Then, set up the developer mode on the WeChat public platform and obtain the server configuration, token and other parameters.

Next, we can start writing PHP code. First, we need to create a WeChat public account web service that can receive messages and reply. You can use PHP frameworks such as Laravel or Yii to build it. If you have no experience using frameworks, you can also directly use PHP's curl library for development.

In the PHP code, we need to set the interface address and token of the WeChat official account so that we can receive verification and information push from the WeChat server. You can set up a unified callback function to receive and process information from users. For example, the following code snippet:

$wechatObj = new wechatCallbackapi();
if (!isset($_GET['echostr'])) {
    $wechatObj->responseMsg();
} else {
    $wechatObj->valid();
}
class wechatCallbackapi
{
    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 = 'your_token';
        $tmpArr = [$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"];
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        switch ($postObj->MsgType) {
            case 'text':
                $content = "收到您的信息,谢谢!";
                $resultStr = $this->textMsg($postObj, $content);
                echo $resultStr;       
                break;
            default:
                echo "";
                break;
        }
    }
    public function textMsg($object, $content)
    {
        $time = time();
        $textTpl = '<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[text]]></MsgType>
            <Content><![CDATA[%s]]></Content>
            <FuncFlag>0</FuncFlag>
            </xml>';
        $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, $time, $content);
        return $resultStr;
    }
}

In the above code, checkSignature() is used to verify the interface, responseMsg() is used to respond to the information sent by the user, and textMsg() is used to reply to the user's information. In this example we are just replying to a simple message, in reality we can extend this as needed to use a database to store the message and return it to the user.

Finally, we need to use the API interface provided by the WeChat public account open platform to push information. Take pushing text information as an example. In the PHP code, we only need to construct a data array as follows, and then use curl to send a POST request to the WeChat server:

$data = [
    'touser' => $openid,
    'msgtype' => 'text',
    'text' => ['content' => '你好,欢迎使用我们的微信公众号服务!']
];
$url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $access_token;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$ret = curl_exec($ch);
curl_close($ch);

Of course, this is just one of them As a simple example, the WeChat public platform provides a rich API interface, which can be developed using PHP to implement more complex functions.

To summarize, PHP can implement the function of pushing information to WeChat public accounts. We need to set up the developer account and corresponding interface parameters on the WeChat public platform, and use PHP to write code to implement replies and push information. And use the API interface provided by WeChat public platform to push information. If you want to learn more about the development of WeChat official accounts, you can read more about the relevant parts of WeChat official documents to master more knowledge and improve your development level.

The above is the detailed content of Example to explain how to implement WeChat push information function 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