有需求联系

Information

- 信息浏览 -

PHP 微信公众号给用户发送模板消息

2023-07-28 790

<?php
$datetime = date('Y-m-d H:i:s');

//获取access_token
function get_access_token()
{
    $appid = "你的$appid";
    $secret = "你的appsecret";
    
    $result = https_request('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret);
    $json = json_decode($result, true);
    $access_token = $json['access_token'];
    return $access_token;
}


//发送消息给相关用户(用户openid)
$template = array(
    "touser" => "{$openid}",
    "template_id" => "93t-61HpBZWxq_sXtTZkPf5GVzxkCxCG4gxe4cCGmTI",
    "url" => "http://www.xmyfw.com.cn",
    "topcolor" => "#FF0000",
    "data" => array(
        "first" => array(
            "value" => "新信息",
            "color" => "#0A0A0A",
        ),
        "keyword1" => array(
            "value" => "名字",
            "color" => "#0A0A0A",
        ),
        "keyword2" => array(
            "value" => "13861399613",
            "color" => "#0A0A0A",
        ),
        "keyword3" => array(
            "value" => "{$datetime}",
            "color" => "#0A0A0A",
        ),
        "remark" => array(
            "value" => "测试模板请知悉",
            "color" => "#0A0A0A",
        ),
    ),
);
// 发送模板消息
send_template_message(urldecode(json_encode($template)));
echo '发送模板消息成功';

function send_template_message($data)
{
    $access_token = get_access_token();
    $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
    $res = https_request($url, $data);
    return json_decode($res, true);
}

function https_request($url, $data = null)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}


Copyright © 2024 镇江小蚂蚁信息科技有限公司 All Rights Reserved.