1.通过小程序获取模板id
2.详见小程序端消息订阅接口 wx.requestSubscribeMessage
wx.requestSubscribeMessage({
tmplIds: [''], //此处填入申请得到的模板id
success (res) { }
})
**说明:**请求同意一次,永久时间内(任意时间内)只能发一次
3:(服务器端)调用接口下发订阅消息
1.先获取access_token
2.完整php代码如下:
public function actionSubmessage(){
/** @var *
* 微信小程序消息订阅
*/
//配置appid
$appid = "**************";
//配置appscret
$secret = "***************";
$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"];
$url_2="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=".$access_token;
//要推送到的用户的openid
$openid = "43*************";
//模板id
$template_id = "********3erS7djkeOehgs****";
$data = [] ;
//接收者(用户)的 openid
$data['touser'] = $openid ;
//所需下发的订阅模板id
$data['template_id'] = $template_id ;
//点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。
$data['page'] = "pages/wechatpay/wechatpay" ;
//模板内容,格式形如 { "key1": { "value": any }, "key2": { "value": any } }
$data['data'] = [
"thing4"=>[
'value' => '123'
],
"thing2"=>[
'value' => '666'
],
"thing1"=>[
'value' => '666'
],
'thing8'=>[
'value'=>'温馨提示'
],
'time5'=>[
'value'=>date('Y-m-d H:i:s', time())
]
];
//跳转小程序类型:developer为开发版;trial为体验版;formal为正式版;默认为正式版
$data['miniprogram_state'] = 'developer';
var_dump($this->posturl($url_2,$data));
}
function geturl($url){
/** @var *
* 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){
/** @var *
* 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);
}
ps:如有问题欢迎留言!