准備工作:
- 開通服務號訂閱通知: 功能-添加功能插件 找到並添加 訂閱通知。
- 在 訂閱通知 中設置相應 類別(需管理員權限)、添加 模板。
用戶訂閱:
官網:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_Open_Tag.html#23
- 綁定域名,登錄微信公眾平台進入 公眾號設置 的 功能設置 里填寫 JS接口安全域名
- 安裝微信官方 js-sdk:npm install weixin-js-sdk (官方使用說明 https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html)或者引入JS文件:http://res.wx.qq.com/open/js/jweixin-1.6.0.js
- 通過config接口注入權限驗證配置並申請所需開放標簽
import wx from 'weixin-js-sdk' function wxconfig (){ let url = "/getJsSignature"; //后台動態獲取config信息接口 let param = { url : location.href //使用開放標簽頁面的完整url }; $post(url, param, (res)=> { //post請求接口 let data = res.val wx.config({ debug: true, // 開啟調試模式,調用的所有api的返回值會在客戶端alert出來,若要查看傳入的參數,可以在pc端打開,參數信息會通過log打出,僅在pc端時才會打印。 appId: data.appid, // 必填,開發者id timestamp: data.timestamp, // 必填,生成簽名的時間戳(自定義) nonceStr: data.noncestr, // 必填,生成簽名的隨機字符串(自定義) signature: data.signature,// 必填,簽名(sha1簽名算法) jsApiList: [], // 必填,需要使用的JS接口列表 openTagList: [ 'wx-open-subscribe'] // 必填,需要使用的JS接口列表,這里填的就是消息訂閱用到的開放標簽 }); }); }
- 頁面中添加開放標簽 wx-open-subscribe
<!--頁面 template:['w_A5DmhNEAPce3PDoaV1fVX0ptwNR0E9HspN95yb95Y','xxxxx'](多模板)--> <wx-open-subscribe :template="template" id="'subscribe-btn" @success="successSubscribe" @error="subErrorSubscribe"> <script type="text/wxtag-template"> <style> <!--按鈕樣式--> .subscribe-btn{} </style> <button class="subscribe-btn">訂閱+1</button> </script> </wx-open-subscribe>
<!--成功事件:包括確定、取消--> successSubscribe(e){ let subscribeDetails = JSON.parse(e.detail.subscribeDetails) let status = JSON.parse(subscribeDetails[模板id]).status if (status=='accept'){ // 同意訂閱該模板 }else if (status=='reject'){ // 拒絕訂閱該模板 } }, <!--錯誤事件--> subErrorSubscribe(e){ let errMsg = e.detail.errMsg // 錯誤提示 let errCode = e.detail.errCode // 錯誤碼 console.log(errMsg,errCode ) }
對於vue項目
開放標簽屬於自定義標簽,Vue會給予未知標簽的警告,可通過配置Vue.config.ignoredElements來忽略Vue對開放標簽的檢查。
在mail.js 里面配置
Vue.config.ignoredElements = ["wx-open-subscribe"];
關於vue的事件監聽
<template> <div class="button"> <wx-open-subscribe :template="['2KkIMjZMtFmL0qWBALfltU8EPDwA3F8sqpStAxkXN_s']" @error="onError" @success="onSuccess" id="subscribe"> <script type="text/wxtag-template"> <style> button{ padding: 10px 30px; display: flex; width: 100% align-items: center; justify-content: center; background: #4BCB7C; color: #fff; font-size: 16px; border: none; outline: none; border-radius: 50px; } </style> <button class="button">接受審核結果通知</button> </script> </wx-open-subscribe> </div> </template> <script> export default { methods: { onError(e) { console.log(e); }, onSuccess(e) { if (e.detail.errMsg == 'subscribe:ok') { let status = JSON.parse(e.detail.subscribeDetails); if (JSON.parse(status['模板消息ID']).status == 'accept') { Toast.success('訂閱成功'); } else { Toast.fail('訂閱失敗'); } } else { Toast.fail('訂閱失敗'); } } } } </script>