微信模板消息发送

来源:互联网 发布:怎么加入淘宝全球购 编辑:程序博客网 时间:2024/05/16 06:41

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


代码:

   /**     * 发送自定义的模板消息     * @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;    }


原创粉丝点击