微信模板消息发送

本文介绍了一种在微信公众平台上实现用户购买成功后自动推送模板消息的方法。通过PHP代码实现消息构造与发送,包括获取access_token、设置消息内容及调用微信API进行推送。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于现在公众号需要,增加了一个用户购买成功后推送消息。


代码:

   /**
     * 发送自定义的模板消息
     * @param $touser
     * @param $template_id
     * @param $url
     * @param $data
     * @param string $topcolor
     * @return bool
     */
    public function template($touser = '', $template_id = '', $url = '', $data = '', $topcolor = '#7B68EE') {
        $template = array(
            'touser' => $open_id,//用户openid
            'template_id' => 'AC6gmr61YOpCFVQ27rLsUSGsgnZhBlw3JpxKjQZjsSw',//模板id
            'url' => $url,//跳转的链接
            'topcolor' => $topcolor,//颜色
            'data' => array(//发送的数据
                'first' => array('value' => '您好,您购买商品成功了'),
                'keyword1' => array('value' => '商品1'),
                'keyword2' => array('value' => date('Y年m月d日 H:i', time())),
                'keyword3' => array('value' => '10元'),
                'keyword4' => array('value' => time()),
                'remark' => array('value' => '查看详情'),
            )
        );
        $json_template = json_encode($template);
        if (!isset($_SESSION['wechat_access_token']) || !isset($_SESSION['expires_in']) || $_SESSION['expires_in'] <= time()) {
            $result = $this->getWechatAccessToken();
            $_SESSION['expires_in'] = $result['expires_in'] + time();
            $_SESSION['wechat_access_token'] = $result['access_token'];
        }
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $wechat_access_token;
        $dataRes = $this->http_request($url, $json_template);
        $return_array = json_decode($dataRes, TRUE);
        if ($return_array['errcode'] == 0) {
            return true;
        } else {
            return false;
        }
    }

//获取 access_token
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET


//curl
    function http_request($url, $data = array()) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        // 我们在POST数据哦!
        curl_setopt($ch, CURLOPT_POST, 1);
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值