# 發送模板API例子
在給用戶發送模板之前,先得獲得用戶Openid(用戶唯一標識)
要獲得用戶Openid,要用戶授權。
所以編寫了一個類GetOpenid.class.php來獲取Openid,具體見上一章。
* * * * *
~~~
<?php
/**
* 微信模板消息設置模板.
* User: wss
* Date: 2016/8/10
* Time: 14:46
* @author 大魔仙
*/
$appid = "";//微信公眾平臺的標識,可在微信平臺賬號中獲取
$appsecret = "";可在微信平臺賬號中獲取
//調用類
require_once "GetOpenid.class.php";
//類實例化。
$GetOpenid = new GetOpenid();
/*/**
* 判斷是否授權過
*
* @Author: 大魔仙
* @Date: 2016/6/15
*/
獲取用戶權限鏈接:
//https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=(*你的回調URL)*&response_type=code&scope=snsapi_userinfo&state=111#wechat_redirect
//第一步:用戶同意授權,獲取code
$code = $GetOpenid->getCode();
//第二步:通過code換取網頁授權access_token
$data = $GetOpenid->getAccessToken($code);
//$accessToken = $data->access_token;
$openid = $data->openid;
//三、用appid和appsecert獲得access token 接口
/*$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
$output = https_request($url); //用于微信接口數據傳輸的萬能函數
$jsoninfo = json_decode($output, true); //生成PHP關聯數組
$access_token = $jsoninfo["access_token"];
var_dump($jsoninfo);*/
//因為獲得access_token是有次數限制的,(具體限制可靠查看官方接口權限),所以最好是在獲取后保存下,一般2小時后失效。
//$access_token="DPkXmi-iVpp4z6e0YeN-QaeSn8prwWXdTfnoDIJ2E218j4-d_h-HepBuSnW3E1SpqI4uKACbTr9tRNUwsgDVe4WQ5Wlw0NI57eQGcgmyeLkUWPeACAKMF";
//四、定義發送信息模板
$date = array(
"touser" =>$openid,//接收者openid
"template_id"=>"RQNOdQ7MMMzbyS-m3E5a9w8qNWZl857-d2i76EAwEGI",//模板ID
"url"=>"http://admin.nextdog.cc/AAAA/wushanshan/HelloWord.php",//模板跳轉鏈接
"data"=>array(
"first"=> array(
"value"=>urlencode("歡迎來到大魔仙模板測試!"),
"color"=>"#173177"
),
"remark"=>array(
"value"=>urlencode("\\n歡迎再次購買!(hello world!)"),
"color"=>"#173177"
)
//因為我定義了行業類型就局限性,只有這些內容
);
$post_send=json_encode($date);
$url2="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$access_token";
$output = https_request($url2,$post_send); //調用微信接口數據傳輸的萬能函數
$jsoninfo = json_decode($output, true); //生成PHP關聯數組
var_dump($jsoninfo);
function https_request($url,$data = null)
{ //函數定義,數據傳輸萬能方法
$curl = curl_init(); //
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
~~~