首先需要在微信小程序中添加新的消息模板 得到 消息模板id 以及消息 參數 結構
然后是微信小程序方面 需要首先 激活消息模板 然后在激活成功的回調函數中進行消息的發送
/** * 激活消息模板 */ wx.requestSubscribeMessage({ tmplIds: ['MDXKR0gxp_F392DOtrqDMN9KztZNdW5hE5AtVT4ja70'], success: function (res) { /** * 微信小程序發送消息 */ wx.request({ url: send, data:{ 'touser':wx.getStorageSync('open_id'), 'order_create':_this.data.ordersuccess.create_time, 'order_no':_this.data.ordersuccess.order_num, 'price_sum':_this.data.ordersuccess.final_sum, 'delivery':_this.data.ordersuccess.delivery}, success:function(res){ console.log(res); } }) }, complete: function(res){ }, fail: function(res){ } })
接下來是后台處理發送請求:
/** * 發送微信小程序消息 */ public function send(){ $touser=IFilter::act(IReq::get('touser')); $order_create=IFilter::act(IReq::get('order_create')); //訂單創建時間 $order_no=IFilter::act(IReq::get('order_no')); //訂單編號 $price_sum=IFilter::act(IReq::get('price_sum')); //訂單金額 $delivery=IFilter::act(IReq::get('delivery')); //配送方式 //siteconfig讀取類 $siteConfigObj = new Config("site_config"); $site_config = $siteConfigObj->getInfo(); $appid=$site_config['wechat_AppID']; $secret=$site_config['wechat_AppSecret']; /** * 首先獲取微信小程序的 AccessToken */ $ccc="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret"; $content=$this->curl($ccc); $content=json_decode($content); $accesstoken=$content->access_token; $datas=array( 'touser'=>$touser, 'lang'=>'zh_CN', 'data'=>array( 'character_string1'=>array('value'=>$order_no), 'time2'=>array('value'=>$order_create), 'amount3'=>array('value'=>$price_sum), 'phrase4'=>array('value'=>$delivery), 'date7'=>array('value'=>ITime::getDateTime()), ), 'template_id'=>'MDXKR0gxp_F392DOtrqDMN9KztZNdW5hE5AtVT4ja70', 'miniprogramState'=> 'trial' //跳轉 小程序類型 ); $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=$accesstoken"; $result = $this->curl($url, $datas); Block::sendRseult(200,'goods detail success',[ 'flag'=>0, 'result'=>$result, ]); }
然后這就發送成功了
注: 可能遇到的問題就是 wx.requestSubscribeMessage 這個調用必須要在點擊事件中 再有其他的問題就是微信所報的錯了 文檔中都有的 按照報錯的代碼 以及提示 改就ok