|
小程序模板消息即將被廢棄掉,于是有了新接口wx.requestSubscribeMessage ----訂閱消息推送 本篇將帶你感受一下訂閱推送的坑坑洼洼 前期準備工作申請訂閱消息模板 id appid 等自行準備 這準備不好的話 別干了兄弟轉行吧 我不讓白嫖!!!!! 話不多說直接上代碼!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 小程序端 app.js ![]()
//app.js
App({
onLaunch: function () {
// 展示本地存儲能力
var logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
var that = this
var user = wx.getStorageSync('user') || {};
var userInfo = wx.getStorageSync('userInfo') || {};
// 登錄
wx.login({
success: res => {
// 發(fā)送 res.code 到后臺換取 openId, sessionKey, unionId
//獲取openid___________________________________________開始
that.globalData.code = res.code
if (res.code) {
wx.getUserInfo({
success: function (res) {
var objz = {};
objz.avatarUrl = res.userInfo.avatarUrl;
objz.nickName = res.userInfo.nickName;
wx.setStorageSync('userInfo', objz);//存儲userInfo
},
fail: function (e) {
}
});
var d = that.globalData;//這里存儲了appid、secret、token串
var l = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + d.appid + '&secret=' + d.secret + '&js_code=' + res.code + '&grant_type=authorization_code';
wx.request({
url: l,
data: {},
method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
// header: {}, // 設置請求的 header
success: function (res) {
var obj = {};
obj.openid = res.data.openid;
obj.expires_in = Date.now() + res.data.expires_in;
console.log(obj.openid);
wx.setStorageSync('userop', obj);//存儲openid
}
});
} else {
console.log('獲取用戶登錄態(tài)失敗!' + res.errMsg)
}
//獲取openid___________________________________________結束
}
})
// 獲取用戶信息
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
// 已經(jīng)授權,可以直接調用 getUserInfo 獲取頭像昵稱,不會彈框
wx.getUserInfo({
success: res => {
// 可以將 res 發(fā)送給后臺解碼出 unionId
this.globalData.userInfo = res.userInfo
// 由于 getUserInfo 是網(wǎng)絡請求,可能會在 Page.onLoad 之后才返回
// 所以此處加入 callback 以防止這種情況
if (this.userInfoReadyCallback) {
this.userInfoReadyCallback(res)
}
}
})
}
}
})
},
globalData: {
url:"http://192.168.0.199:8888/app",
appid: '微信appid',//微信appid
secret: '秘鑰',//秘鑰
userInfo: null
}
})
![]() index.js ![]()
//登錄
login:function(){
if(!this.data.userName){
wx.showToast({
title: '用戶名不能為空',
icon:'none'
})
return;
}
if (!this.data.pwd) {
wx.showToast({
title: '密碼不能為空',
icon: 'none'
})
return;
}
wx.showLoading({});
wx.setStorageSync("cid",this.guid());
wx.request({
url: app.globalData.url + '/Login/appLogin',
data:{
username: this.data.userName,
password: this.data.pwd,
clientId: wx.getStorageSync("cid"),
openid: wx.getStorageSync('userop').openid
},
header: {
'content-type': 'application/x-www-form-urlencoded',
'X-Requested-With':'XMLHttpRequest'
},
method:"POST",
success:function(res){
if(res.data.status == 200){
wx.setStorageSync("user", res.data.user);
wx.removeStorageSync('sessionid');
wx.setStorageSync("sessionid", res.cookies[1]);
wx.switchTab({
url: '/pages/main/main'
});
return;
}else{
wx.showToast({
title: '用戶名或密碼錯誤',
icon: 'none'
})
}
}
});
![]() 獲取到openid之后直接就從你的登錄方法往后端傳就行 后端接收后存到相應的表里 下次登錄給掛個標識 表里對應的useid有就不存了 沒有就存 如果有redis可以做緩存 避免給數(shù)據(jù)庫造成太大的壓力 當然這只是小程序獲取openi的第一步 后端代碼給您您 微信個推的工具類 自己寫的用的話可以根據(jù)自己的需求改改 ![]()
1 package com.jeesite.modules.sys.utils;
2
3 import com.alibaba.fastjson.JSONObject;
4 import com.jeesite.common.wx.TemplateDataVo;
5 import com.jeesite.common.wx.WxMssVo;
6 import lombok.extern.slf4j.Slf4j;
7 import org.springframework.http.ResponseEntity;
8 import org.springframework.stereotype.Component;
9 import org.springframework.web.client.RestTemplate;
10 import java.util.HashMap;
11 import java.util.Map;
12
13 /**
14 * @Author wm
15 * @Description wx小程序發(fā)送工具
16 * @Date 2020/4/278:22
17 **/
18
19 @Slf4j
20 @Component
21 public class WeChatPushUtils {
22
23
24
25 /**
26 *
27 * @param openid 用戶openid
28 * @param templateDataVo 模板消息
29 * @return
30 */
31 public static String pushOneUser( String openid,TemplateDataVo templateDataVo) {
32 RestTemplate restTemplate = new RestTemplate();
33 //自動獲取token
34 String access_token = getAccess_token();
35 String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + access_token; //微信請求接口
36 //封裝模板數(shù)據(jù)
37 WxMssVo wxMssVo = new WxMssVo();
38 //用戶openid
39 wxMssVo.setTouser(openid);
40 Map<String,Object> data = new HashMap<>();
41 data.put("number2",templateDataVo.getNumber2());
42 data.put("name1",templateDataVo.getName1());
43 wxMssVo.setData(data);
44 ResponseEntity<String> responseEntity = restTemplate.postForEntity(url,JSONObject.toJSON(wxMssVo).toString(),String.class);
45 log.info("小程序推送結果={}", responseEntity.getBody());
46 return responseEntity.getBody();
47 }
48
49 /**
50 * 獲取access_token
51 * appid和appsecret到小程序后臺獲取,當然也可以讓小程序開發(fā)人員給你傳過來
52 * */
53 public static String getAccess_token() {
54 RestTemplate restTemplate = new RestTemplate();
55 //獲取access_token
56 String appid = "微信appid";
57 String appsecret = "密鑰";
58 String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
59 "&appid=" + appid + "&secret=" + appsecret; //獲取token
60 if(restTemplate==null){
61 restTemplate = new RestTemplate();
62 }
63 String json = restTemplate.getForObject(url, String.class);
64 JSONObject myJson = JSONObject.parseObject(json);
65 return myJson.get("access_token").toString();
66 }
67 }
![]() 這里面不得不說的幾個坑 我的天那選的模板 一定一定要根據(jù)微信公眾平臺提供的例子去封裝 一定一定一定 別自己隨便去封裝什么實體 最底層的key就是value 不解釋了我截個圖去
也別說了 看圖寶貝 接口很隱秘網(wǎng)址先po出來https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html 看右邊大紅框里面的data值 就是你申請的模板對應的相關字段 data 比如你申請的字段是 thing1 name你寫的方式就是
對沒錯 value 就是每個字段值的key 這就是那個坑封裝的坑 如果想實體封裝太麻煩 建議JSONOBJECT簡單粗暴 但是!!!!但是 到了這一步即使你傳進去了模板id openid 想發(fā)請求 不好意思 不行行!!!!!!!! 下面我們來看看原因
還是看圖 步驟一的數(shù)據(jù)都有了 詳情網(wǎng)址:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/subscribe-message.html 那**步驟二呢 用戶沒訂閱發(fā)個蛋蛋............ 下面就得讓openid這個用戶訂閱一下 上!!!代!!!!碼!!!!! 我是這樣做的
加了一個按鈕 ,用戶點了就是這樣的
雖然有點丑 功能是有了 代碼標簽
1 <button bindtap="subTap" type="defaults" style=" background-color:#98F898;width:95%;margin:20px 10px;">訂閱消息<text>{{textcontent}}</text></button>
函數(shù) ![]()
1 //訂閱消息開啟
2 data: {
3 textcontent: '提示:未開啟'
4 },
5
6 // 檢測是否開啟 更新提示
7 testingTap: function() {
8 let that = this;
9 wx.getSetting({
10 withSubscriptions: true,
11 success(res) {
12 console.log(res)
13 if (res.subscriptionsSetting.mainSwitch) {
14 if (res.subscriptionsSetting.itemSettings != null) {
15 let item = res.subscriptionsSetting.itemSettings.模板id
16 console.log(item)
17 if (item == "reject") {
18 that.setData({
19 textcontent: '提示:您已經(jīng)拒絕訂閱消息'
20 })
21 } else if (item == "accept") {
22 that.setData({
23 textcontent: '提示:您已經(jīng)開啟訂閱消息'
24 })
25 } else if (item == "ban") {
26 that.setData({
27 textcontent: '提示:您已經(jīng)被后臺封禁'
28 })
29 }
30 }
31 } else {
32 that.setData({
33 textcontent: '提示:訂閱消息未開啟'
34 })
35 }
36 }
37 })
38 },
39
40 //授權
41 subTap: function() {
42 let that = this;
43 wx.requestSubscribeMessage({
44 tmplIds: ['模板id'],
45 success(res) {
46 if(res.模板id=="accept"){
47 that.setData({
48 textcontent: '提示:授權成功'
49 })
50 }else{
51 that.setData({
52 textcontent: '提示:未授權'
53 })
54 }
55 },
56 fail(res) {
57
58 that.setData({
59 textcontent: '提示:授權失敗'
60 })
61 }
62 })
63 }
![]() 這樣用戶訂閱了之后才能發(fā)送 .........快去試試吧 本文為原創(chuàng)當然寫的時候太草率 有諸多問題沒有說明 但是代碼你只要有點基礎 放對地方了絕對 下面附成功圖
|