PHP微信模板消息推送【原创

来源:https://www.sucaihuo.com/php/1236.html 2017-01-12 07:22浏览(3696) 收藏

用户下完订单以后,自动推送订单消息到用户微信账号里。PHP根据openid向微信用户推送模板消息
PHP微信模板消息推送
分类:PHP > 微信 难易:中级
查看演示 下载资源 下载积分: 600 积分

首先到mp.weixin.qq.com,配置微信模板消息,获取appid和secret

然后获取微信用户的openid,之前我们在这篇文章中演示过http://www.sucaihuo.com/php/1008.html

include_once 'config.php';
$redirect_uri = "http://www.sucaihuo.com/project/openid/openid.php";
$redirect_uri = urlencode($redirect_uri);

$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $appid . "&redirect_uri=" . $redirect_uri . "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
header('Location: ' . $url . '');

然后获取access_token

$json_token = http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret);
$access_tokens = json_decode($json_token, true);

$access_token = $access_tokens['access_token'];

最后推送模板消息,模板id 必须是你自己的

//模板消息
$template = array(
    'touser' => $openid, //用户openid
    'template_id' => "Wi-ijSlQPzlnNjEkumVmfPKk9OUIfGcKyOn4Tky4iYM", //模板消息id
    'url' => "http://www.sucaihuo.com/", 
    'topcolor' => "#173177",
    'data' => array(
        'first' => array('value' => urlencode("您好,您已购买成功"), 'color' => "#743A3A"),
        'delivername' => array('value' => urlencode("顺丰快递"), 'color' => '#173177'),
        'ordername' => array('value' => urlencode(date('YmdHis')), 'color' => '#173177'),
        'remark' => array('value' => urlencode('请尽快发货'), 'color' => '#173177'),
    )
);
$json_template = json_encode($template);

$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
$json = http_request($url, urldecode($json_template));
$rs = json_decode($json, true);
if ($rs['errcode'] == 0) {
    echo "<span style='color:red;font-size:32px'>模板消息发送成功,请打开微信查看是否有新消息。</span>";
} else {
    echo "发送失败,错误信息如下:";
    print_r($rs);
}
声明:本文为原创文章,如需转载,请注明来源sucaihuo.com并保留原文链接:https://www.sucaihuo.com/php/1236.html
评论1
头像

系统已开启自动识别垃圾评论机制,识别到的自动封号,下载出错或者资源有问题请联系全栈客服QQ 1915635791

  • 头像 沙发
    07-22 10:23
    s***g
    先看看再说,不知道性行不行
1 2