微信模板消息接口-給用戶發送訂單成功信息/支付成功等等


微信模板消息僅用於公眾號向用戶發送重要的服務通知,只能用於符合其要求的服務場景中,如信用卡刷卡通知,商品購買成功通知等。不支持廣告等營銷類消息以及其它所有可能對用戶造成騷擾的消息。

<?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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM