微信公众号“发送消息回复”与“模版消息推送”功能实现(2021)

一、服务器验证

1.微信公众号配置服务器验证信息

2.验证代码如下:

$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;
    }
}

二、获取用户OPENID后,推送模板消息

1.微信公众号中选取模板

2.推送主PHP代码如下:

//引用推送模板类
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.推送的调用方法代码如下:

//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;
}

至此完成模板消息推送。

二、用户在公众号发送消息后,程序识别后自定义回复

1.回复的主PHP代码如下:

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

2.回复的调用方法代码如下:

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;
}

至此完成发送消息回复。

猜你喜欢

转载自blog.csdn.net/HoD_DoH/article/details/118080878