PHP实现接收微信公众平台推送

前言

用PHP实现接受公众号的推送消息(ticket、私信等)。

首先申请一个公众号,一定要是服务号,然后进行微信认证,这些是前提条件。

 

 

 

一.微信公众平台配置

1.进入基本配置,第一次进入会提示开启开发者,点击开启即可。

 

2.启用secret,配置服务器白名单

 

3.修改服务器配置

URL填写你需要接受消息的地址;

Token和解密Key都可以自己填写;

加解密方式按照项目需求选择即可;

 注意提交时会报这个token验证失败,我解决的方法是在代码里直接输出传参里的值。

public function notify(){
       //用于第一次服务器配置
        echo $_GET['echostr'];
        exit;
}

 

 二.代码实现

1.代码中接受到推送后可以进行校验,保证是微信推送消息。

encryptMsg即是接收到的消息,可以根据开发文档对数据进行处理。

微信文档:https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_standard_messages.html

    /*
     * 接收推送
     */
    public function notify(){
//        //用于第一次服务器配置
//        echo $_GET['echostr'];
//        exit;

        $encryptMsg = file_get_contents('php://input');

        $filename = date('Y-m-d')."_ceshi.txt";
        $files = fopen($filename,'a+');
        fwrite($files,date('Y-m-d H:i:s')."----->".$encryptMsg."---->".json_encode($_GET)."\r\n\r\n");
        fclose($files);

        $res = $this->checkSignature();
        if ($res){
            //验证成功
            $content = explode("<Content><![CDATA[",$encryptMsg)[1];
            $content = explode("]]></Content>",$content)[0];
        }else{
            //验证失败
        }

        echo $_GET['echostr'];
        exit;
    }

    private function checkSignature(){
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = WX_NOTICE_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;
        }
    }

 

 

posted @ 2023-07-28 15:40  知冷知热  阅读(1192)  评论(0)    收藏  举报