小程式訂閱訊息【PHP版】
public function actionSubmessage($User,$Tel,$Type) {//微信小程式訊息訂
//配置appid
$appid = "wx81****************b9";
//配置appscret
$secret = "c2a7***********************bde";
//校驗api:請勿改動
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
//獲取access_token $access_token = $this -> geturl($url)["access_token"];
//固定api:請勿改動
$url_2 = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=".$access_token;
//要推送到的使用者的openid
$openid = "o0Lcm0dq6wBY6QQCQt6R-uAFciCc";
//模板id
$template_id = "f59Sdp0sK2Ww1pbTd7LcvTsjJWA197dnx21TfYXSGog";
$data = [];
//接收者(使用者)的 openid
$data['touser'] = $openid;
//所需下發的訂閱模板id
$data['template_id'] = $template_id;
//點選模板卡片後的跳轉頁面,僅限本小程式內的頁面。支援帶引數,(示例index?foo=bar)。該欄位不填則模板無跳轉。
$data['page'] = "pages/index/index";
//模板內容,格式形如 { "key1": { "value": any }, "key2": { "value": any } }
$data['data'] = [
"name1" => [ 'value' => $User ],
"thing2" => [ 'value' => $Tel ],
"date3" => [ 'value' => date('Y-m-d H:i', time()) ],
"phrase4" => [ 'value' => $Type ],
"thing5" => [ 'value' => '有新的使用者已報名,請儘快聯絡' ]
];
//跳轉小程式型別:developer為開發版;trial為體驗版;formal為正式版;預設為正式版
//$data['miniprogram_state'] = 'developer';
$this->success("呼叫訊息",$this -> posturl($url_2, $data));
//var_dump($this -> posturl($url_2, $data));
}
function geturl($url){ /** curl get請求封裝,返回json資料格式資料 **/
$headerArray =array("Content-type:application/json;","Accept:application/json");
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
$output = curl_exec($ch); curl_close($ch);
$output = json_decode($output,true); return $output;
}
function posturl($url,$data){ /** curl post請求封裝,返回json資料格式資料 **/
$data = json_encode($data);
$headerArray =array("Content-type:application/json;charset='utf-8'","Accept:application/json");
$curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return json_decode($output,true);
}