微信模板消息接口-给用户发送订单成功信息/支付成功等等

微信模板消息仅用于公众号向用户发送重要的服务通知,只能用于符合其要求的服务场景中,如信用卡刷卡通知,商品购买成功通知等。不支持广告等营销类消息以及其它所有可能对用户造成骚扰的消息。

<?php
//curl模拟请求发送信息
function send_template_message($data,$access_token){
    //return $data.'----'.$access_token;
    //$access_token = get_access_token($appId,$appSecret);
    $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access_token;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8','Content-Length: ' . strlen($data)));
    ob_start();
    curl_exec($ch);
    $return_content = ob_get_contents();
    ob_end_clean();
    $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    return array($return_code, $return_content);
}
//获取微信access_token
function get_accessToken($appid='',$appsecret=''){
    $tokenFile = "./access_token.txt"; // 缓存文件名
    $data = json_decode(file_get_contents($tokenFile)); //转换为json格式
    if ($data->expire_time < time() or ! $data->expire_time) {
        //token过期的情况
        $res = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret);
        $res = json_decode($res, true); // 对 JSON 格式的字符串进行编码
        $access_token = $res['access_token'];
        if ($access_token) {

            $data['expire_time'] = time() + 3600; //保存1小时

            $data['access_token'] = $access_token;

            $fp = fopen($tokenFile, "w"); //只写文件

            fwrite($fp, json_encode($data)); //写入json格式文件

            fclose($fp); //关闭连接
        }
    } else {
        $access_token = $data->access_token;
    }
    return $access_token;
}

//具体使用如下:
//微信订单发送 start 先根据appid和appsecret获取access_token $che=get_accessToken($weixinconfig['appid'],$weixinconfig['appsecret']); $data = array( 'first' => array( 'value'=> urlencode('您好,你购买的商品已经发货了'), 'color' => '#743A3A', ), 'orderID' => array('value' => urlencode('2222222'), 'color' => '#743A3A', ), 'orderMoneySum' => array('value' => urlencode('222'), 'color' => '#743A3A', ), 'backupFieldName' => array('value' => urlencode('111'), 'color' => '#743A3A', ), 'backupFieldData' => array('value' => urlencode('544564'), 'color' => '#743A3A', ), 'remark' => array('value' => urlencode('你的订单已提交,我们尽快发货'), 'color' => '#743A3A', ), ); $array = array( 'touser' => $json['openid'], 'template_id' => 'GG5OlUTIJcPJqEIvaZz_BM-2CNPoMBFFHyPj_MwYNGw', "url"=>"http://weixin.qq.com/download", 'topcolor'=>'#FF0000', 'data' => $data, ); send_template_message(urldecode(json_encode($array)),$che); //微信订单发送 end


?>
$json['openid']  此处为接收信息微信的openid
原文地址:https://www.cnblogs.com/houdj/p/6245683.html