小程序订阅消息使用(一次性)
小程序代码
<view class='func-item' data-funcname='subscript_notice' bindtap='toFunc'> <view class="func-item-icon"> <text class="iconfont icon-qingchu iconfont-size" style="color:#FE7873;"></text> </view> <view class='func-item-title'> 订阅消息 </view> <view class='func-item-nav'> <view class="iconfont icon-nav-right"></view> </view> </view>
subscriptNotice: function () { wx.requestSubscribeMessage({ tmplIds: ['Ue2WWXj6Bm58Ayzau3B1RCTIFFal1aDCXJ0WfyHo5_w'], success: (res) => { console.log('订阅结果'); console.log(res); if (res.errMsg == 'requestSubscribeMessage:ok') { let status = res['Ue2WWXj6Bm58Ayzau3B1RCTIFFal1aDCXJ0WfyHo5_w']; console.log(status); } else { wx.showModal({ showCancel: false, title: '提示', message: res.errMsg + ',请重新订阅!' }) } }, fail: ex => { wx.showModal({ title: '提示', message: JSON.stringify(ex), showCancel: false }) } }) },
后台逻辑
定义消息模板类型
/// <summary> /// 订阅模板消息 基本项 /// </summary> public class MpTempleteMessageBaseItem { public string value { get; set; } }
/// <summary> /// 经营数据通知 /// </summary> public class MpBusinessDataTempleteMessage { /// <summary> /// 商品总额 /// </summary> public MpTempleteMessageBaseItem amount1 { get; set; } /// <summary> /// 储值总额 /// </summary> public MpTempleteMessageBaseItem amount2 { get; set; } /// <summary> /// 销售单数 /// </summary> public MpTempleteMessageBaseItem number3 { get; set; } /// <summary> /// 其他收入 /// </summary> public MpTempleteMessageBaseItem amount4 { get; set; } /// <summary> /// 统计时间 /// </summary> public MpTempleteMessageBaseItem time5 { get; set; } }
订阅消息模型
/// <summary> /// 订阅消息模型 /// </summary> public class MpTempleteMessageModel { /// <summary> /// string 是 接收者(用户)的 openid /// </summary> public string touser { get; set; } /// <summary> /// string 是 所需下发的订阅模板id /// </summary> public string template_id { get; set; } /// <summary> /// string 否 点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。 /// </summary> public string page { get; set; } /// <summary> /// Object 是 模板内容,格式形如 { "key1": { "value": any }, "key2": { "value": any } } /// </summary> public object data { get; set; } /// <summary> /// string 否 跳转小程序类型:developer为开发版;trial为体验版;formal为正式版;默认为正式版 /// </summary> public string miniprogram_state { get; set; } /// <summary> /// string 否 进入小程序查看”的语言类型,支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文),默认为zh_CN /// </summary> public string lang { get; set; }
获取 token
public Result GetAccessToken() { var _result = new Result(); try { var tokenModel = Senparc.Weixin.MP.CommonAPIs.CommonApi.GetToken(AppId, AppSecret); if (tokenModel == null) { _result.success = false; _result.message = "请求token失败"; return _result; } if (tokenModel.errcode != 0) { _result.success = false; _result.message = _result.message = "获取授权token失败,错误代码:" + tokenModel.errcode + ",错误原因:" + tokenModel.errmsg; return _result; } var cacheModel = new AccessTokenCache() { access_token = tokenModel.access_token, expires = DateTime.Now.AddSeconds(tokenModel.expires_in) }; _cacheManage.GetCache(Common.CacherKeyHelper.AccessTokenCacheKey()).Set("wxapp", cacheModel, TimeSpan.FromSeconds(tokenModel.expires_in)); _result.success = true; _result.data = cacheModel; } catch (Exception ex) { _result.success = false; _result.message = ex.Message; } return _result; }
封装订阅消息模型
private MpBusinessDataTempleteMessage GetMpBusinessDataTempleteMessage(SendMessageRequestDto input) { return new MpBusinessDataTempleteMessage() { amount1 = new MpTempleteMessageBaseItem() { value = input.key_word1 }, amount2 = new MpTempleteMessageBaseItem() { value = input.key_word2 }, amount4 = new MpTempleteMessageBaseItem() { value = input.key_word4 }, number3 = new MpTempleteMessageBaseItem() { value = input.key_word3 }, time5 = new MpTempleteMessageBaseItem() { value = input.key_word5 } }; }
接口参数模型
/// <summary> /// 发送订阅消息的参数 /// </summary> public class SendMessageRequestDto { public SendMessageRequestDto() { miniprogram_state = "formal"; lang = "zh_CN"; } /// <summary> /// 发送者的openid /// </summary> public string openid { get; set; } /// <summary> /// 订阅号类型 /// 1-经营数据通知 /// </summary> public string template_type { get; set; } /// <summary> /// 点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。 /// </summary> public string page { get; set; } /// <summary> /// 跳转小程序类型:developer为开发版;trial为体验版;formal为正式版;默认为正式版 /// </summary> public string miniprogram_state { get; set; } /// <summary> /// 进入小程序查看”的语言类型,支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文),默认为zh_CN /// </summary> public string lang { get; set; } /// <summary> /// 内容关键字 1 /// </summary> public string key_word1 { get; set; } /// <summary> /// 内容关键字 2 /// </summary> public string key_word2 { get; set; } /// <summary> /// 内容关键字 3 /// </summary> public string key_word3 { get; set; } /// <summary> /// 内容关键字 4 /// </summary> public string key_word4 { get; set; } /// <summary> /// 内容关键字 5 /// </summary> public string key_word5 { get; set; } /// <summary> /// 内容关键字 6 /// </summary> public string key_word6 { get; set; } /// <summary> /// 备注 /// </summary> public string remark { get; set; } }
发送方法
public Result SendMessage(SendMessageRequestDto input) { var _result = new Result(); try { var _error = ""; var _token = _cacheManage.GetCache(Common.CacherKeyHelper.AccessTokenCacheKey()).Get("wxapp", () => { var _tokenResult = GetAccessToken(); if (_tokenResult.success) { var cacheToken = _tokenResult.data as AccessTokenCache; if (cacheToken == null) { return null; } else { return cacheToken; } } else { _error = _tokenResult.message; return null; } }); if (!string.IsNullOrWhiteSpace(_error)) { _result.success = false; _result.message = _error; return _result; } if (_token == null || _token.expires < DateTime.Now) { _cacheManage.GetCache(Common.CacherKeyHelper.AccessTokenCacheKey()).Remove("wxapp"); var _tokenResult = GetAccessToken(); if (_tokenResult.success) { _token = _tokenResult.data as AccessTokenCache; } else { _error = _tokenResult.message; _result.success = false; _result.message = _error; return _result; } } var template_id = ""; object message = new object(); switch (input.template_type) { case "1": template_id = "Ue2WWXj6Bm58AyzauXJ0WfyHo5_w"; message = GetMpBusinessDataTempleteMessage(input); break; } var messageData = new MpTempleteMessageModel { touser = input.openid, template_id = template_id, page = input.page, data = message, lang = input.page, miniprogram_state = input.miniprogram_state }; var url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + _token.access_token; var _mpResult = CommonJsonSend.Send<MpResult>(null, url, messageData); } catch (Exception ex) { _result.message = ex.Message; _result.success = false; } return _result; }