php实现微信小程序无需formid订阅发送消息,小程序迎来升级,开发者无需收集form表单提交后的formid,通过微信订阅引导用户点击点阅后就可以直接发送消息给微信用户,具体步骤如下:
一、微信小程序后台添加消息模板
选择自己的消息模板
添加模板后就可以看到自己的模板
二、小程序订阅代码
wx.requestSubscribeMessage({ tmplIds: ['模板id'],//可以是多个 success (res) { }, fail (res){ } })
注意:此段代码必须在bindtap事件中触发,如果在form提交事件中提交会fail并显示错误"requestSubscribeMessage:fail can only be invoked by user TAP gesture."
三、php后台代码
<?php class Message { private $appId = ""; private $appSecret = ""; function sendmMsg($openid, $template_id, $content, $url) { $tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret"; $tokenValue = $this->httpGet($tokenUrl); $TmUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=$tokenValue->access_token"; $data = [ 'touser' => $openid, 'template_id' => $template_id, 'page' => $url, //小程序消息提醒点击跳转小程序页面路径 'miniprogram_state' => 'formal', "data" => $content // "data" => array( // 'keyword1' => array('value' => $content), // 'keyword2' => array('value' => $username), // 'keyword3' => array('value' => date('Y-m-d H:i:s', time())) // ), ]; return $this->httpPost($TmUrl, $data); } private function httpGet($url) { $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, 500); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_URL, $url); $res = curl_exec($curl); curl_close($curl); return json_decode($res); } private function httpPost($url, $post_data) { $postdata = json_encode($post_data, JSON_UNESCAPED_UNICODE); $options = array( 'http' => array( 'method' => 'POST', 'header' => 'Content-type:application/json', 'content' => $postdata, 'timeout' => 15 * 60 // 超时时间(单位:s) ) ); $context = stream_context_create($options); $result = file_get_contents($url, false, $context); return $result; } } ?>直接调用sendmMsg函数其中
openid是用户的openid
template_id 是我们微信小程序的后台模板id
url是消息跳转小程序的url,如果不填消息就无法跳转
content参数必须是数组的形式传入,类似于
array(
'keyword1' => array('value' => $content),
'keyword2' => array('value' => $username),
'keyword3' => array('value' => date('Y-m-d H:i:s', time()))
网友评论0