WeChat public account "send message reply" and "template message push" functions realized (2021)

1. Server verification

1. WeChat official account configuration server verification information

2. The verification code is as follows:

$token = 'test'; //自行配置一个特殊字符
echo $this->checkSignature();
//验证逻辑
function checkSignature()
{
    $signature = $_GET['signature'];
    $nonce = $_GET['nonce'];
    $timestamp = $_GET['timestamp'];
    $echostr = $_GET['echostr'];
    $token = $this->token;

    $arr = array($nonce, $timestamp, $token);
    sort($arr);
    $tmpstr = implode($arr);
    if (sha1($tmpstr) == $signature) {
        return $echostr;
    } else {
        return false;
    }
}

2. After obtaining the user OPENID, push the template message

1. Select a template from the WeChat official account

2. Push the main PHP code as follows:

//引用推送模板类
require('class.php');
$token = 'test'; //自行配置一个特殊字符,与服务器验证中一致
$server = new Server($token);
//配置推送参数
$openid = $_GET['openid'];
$content = array(
    'first' => array(
        'value' => $_GET['content1'],
        'color' => '#173177',
    ),
    'keyword1' => array(
        'value' => $_GET['content2'],
        'color' => '#173177',
    ),
    'keyword2' => array(
        'value' => $_GET['content3'],
        'color' => '#173177',
    ),
    'remark' => array(
        'value' => $_GET['content4'],
        'color' => '#173177'
    ),
);
//实现推送
$res = $server->responseTemplateMsg($openid, $content);

3. The code for calling the push method is as follows:

//curl统一调用方法
public function phpCurl($type, $url, $data, $contentType = 'json')
{
    $ch = curl_init();
    // 请求地址
    curl_setopt($ch, CURLOPT_URL, $url);
    // 请求参数类型
    $data = $contentType == 'json' ? urldecode(json_encode($data)) : http_build_query($data);
    // 关闭https验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    // post提交
    if ($type == 'post') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    // 返回的数据是否自动显示
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $output = curl_exec($ch);
    curl_close($ch);
    return json_decode($output, true);
}

//获取模板推送token
public function getAccessToken($appid = '123123213213', $appsecret = '123123123') //手工配制参数
{
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret;

    $result = file_get_contents('路径/文件.txt');
    $arr = explode(',', $result);
    if (time() - $arr[1] > 7000 || $arr[1] == 0) {
        $info = $this->phpCurl('get', $url, NULL);
        if ($info['expires_in'] > 0) {
            $str = $info['access_token'] . ',' . time();
            file_put_contents('路径/文件.txt', $str);
            return  $info['access_token'];
        } else {
            $this->getAccessToken($appid, $appsecret);
        }
    } else {
        return $arr[0];
    }
}

//模板信息组装,实现推送
public function responseTemplateMsg($openid, $content)
{
    $accessToken = $this->getAccessToken();
    $data = array(
        'touser' => $openid,
        'template_id' => 'AX7GVGR9r0Iv49_Am4Fs56Uz0NK_UJb-gzutvshpEZY', //自行修改
        'url' => 'http://www.baidu.com', //自行修改
        'data' => $content
    );
    $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $accessToken;

    $result = $this->phpCurl('post',$url, $data);
    if($result['errcode'] != 0){
        return false;
    }
    return true;
}

So far, the template message push is completed.

2. After the user sends a message on the official account, the program recognizes and customizes the reply

1. The main PHP code of the reply is as follows:

//引用推送模板类
require('class.php');
$token = 'test';  //自行配置一个特殊字符,与服务器验证中一致
$server = new Server($token);
echo $server->responseMsg();

2. The calling method code of the reply is as follows:

public function responseMsg()
{
    $file_in = file_get_contents("php://input");
    $postObj = simplexml_load_string($file_in);

    $toUser = $postObj->FromUserName;
    $fromUser = $postObj->ToUserName;
    $msgType = $postObj->MsgType;
    $createTime = time();
    //用户行为是“事件”
    if (strtolower($msgType) == 'event') {
        //用户行为为订阅
        if (strtolower($postObj->Event) == 'subscribe') {
            $content = '欢迎关注!订阅success';
        }
    } else {
        //这里自定义回复内容
        $content = '你发送的新消息为:';
        $content .= $postObj->Content;
    }
    $template = "
    <xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[text]]></MsgType>
        <Content><![CDATA[%s]]></Content>
    </xml>";

    $info = sprintf($template, $toUser, $fromUser, $createTime, $content);
    return $info;
}

This completes sending message replies.

Guess you like

Origin blog.csdn.net/HoD_DoH/article/details/118080878