您现在的位置是:网站首页> 编程资料编程资料
.NET CORE3.1实现微信小程序发送订阅消息_实用技巧_
2023-05-24
347人已围观
简介 .NET CORE3.1实现微信小程序发送订阅消息_实用技巧_
一、appsettings.json定义小程序配置信息
"WX": { "AppId": "wx88822730803edd44", "AppSecret": "75b269042e8b5026e6ed14aa24ba9353", "Templates": { "Audit": { "TemplateId": "aBaIjTsPBluYtj2tzotzpowsDDBGLhXQkwrScupnQsM", "PageUrl": "/pages/index/formAudit?formId={0}&tableId={1}", "MiniprogramState": "developer", "Lang": "zh_TW", "Data": { "Title": "thing6", "Content": "thing19", "Date": "date9" } } }, "SignatureToken": "aaaaaa", "MessageSendUrl": "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={0}", "AccessTokenUrl": "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}" } 二、编写通用类加载配置
using System; using System.Text; using System.Security.Cryptography; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Json; namespace WXERP.Services { /// /// 项目公有静态类 /// public class Common { /// /// 獲取根目錄 /// public static string AppRoot => Environment.CurrentDirectory;// AppContext.BaseDirectory; /// /// 獲取項目配置 /// public static IConfiguration Configuration { get; set; } /// /// 加載項目配置 /// static Common() { Configuration = new ConfigurationBuilder() .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true //当appsettings.json被修改时重新加载 }) .Build(); } /// /// SHA1加密 /// /// 需要加密的字符串 /// 返回40位大寫字符串 public static string SHA1(string content) { try { SHA1 sha1 = new SHA1CryptoServiceProvider(); byte[] bytes_in = Encoding.UTF8.GetBytes(content); byte[] bytes_out = sha1.ComputeHash(bytes_in); sha1.Dispose(); string result = BitConverter.ToString(bytes_out); result = result.Replace("-", ""); return result; } catch (Exception ex) { throw new Exception("Error in SHA1: " + ex.Message); } } } } 三、编写HttpHelper请求类
using System; using System.Text; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using System.Collections.Generic; namespace WXERP.Services { /// /// HTTP請求輔助類 /// public class HttpHelper { /// /// post同步請求 /// /// 地址 /// 數據 /// application/xml、application/json、application/text、application/x-www-form-urlencoded /// 請求頭 /// public static string HttpPost(string url, string postData = null, string contentType = null, Dictionary headers = null) { using HttpClient client = new HttpClient(); if (headers != null) { foreach (var header in headers) client.DefaultRequestHeaders.Add(header.Key, header.Value); } postData ??= ""; using HttpContent httpContent = new StringContent(postData, Encoding.UTF8); if (contentType != null) httpContent.Headers.ContentType = new MediaTypeHeaderValue(contentType); HttpResponseMessage response = client.PostAsync(url, httpContent).Result; return response.Content.ReadAsStringAsync().Result; } /// /// post異步請求 /// /// 地址 /// 數據 /// application/xml、application/json、application/text、application/x-www-form-urlencoded /// 請求超時時間 /// 請求頭 /// public static async Task HttpPostAsync(string url, string postData = null, string contentType = null, int timeOut = 30, Dictionary headers = null) { using HttpClient client = new HttpClient(); client.Timeout = new TimeSpan(0, 0, timeOut); if (headers != null) { foreach (var header in headers) client.DefaultRequestHeaders.Add(header.Key, header.Value); } postData ??= ""; using HttpContent httpContent = new StringContent(postData, Encoding.UTF8); if (contentType != null) httpContent.Headers.ContentType = new MediaTypeHeaderValue(contentType); HttpResponseMessage response = await client.PostAsync(url, httpContent); return await response.Content.ReadAsStringAsync(); } /// /// get同步請求 /// /// 地址 /// 請求頭 /// public static string HttpGet(string url, Dictionary headers = null) { using HttpClient client = new HttpClient(); if (headers != null) { foreach (var header in headers) client.DefaultRequestHeaders.Add(header.Key, header.Value); } HttpResponseMessage response = client.GetAsync(url).Result; return response.Content.ReadAsStringAsync().Result; } /// /// get異步請求 /// /// /// /// public static async Task HttpGetAsync(string url, Dictionary headers = null) { using HttpClient client = new HttpClient(); if (headers != null) { foreach (var header in headers) client.DefaultRequestHeaders.Add(header.Key, header.Value); } HttpResponseMessage response = await client.GetAsync(url); return await response.Content.ReadAsStringAsync(); } } } 四、在sqlserver下存储并获取openid,这个主要是因为提交消息并不是在微信小程序端,如果是在微信小程序上发起订阅消息,可以忽略这个步骤
// 创建数据库表 create table TBSF_Conmmunicate_WXUser ( ID int identity(1,1) primary key, Staff_ID varchar(10), OpenId varchar(50), SessionKey varchar(50), UnionId varchar(50), IsValid bit, ) // SqlHelper数据库辅助类来自于CommunicationOperateDBUtility,可以自己编写 using System.Data; using System.Text; using CommunicationOperateDBUtility; namespace WXERP.Services.CommunicationOperateDAL { /// /// 微信信息 /// public class WXInforDeal { private SqlHelper sqlHelper = null; /// /// 初始化數據庫輔助對象 /// /// public WXInforDeal(object con) { sqlHelper = new SqlHelper(con); } /// /// 獲取微信登陸用戶信息 /// /// 工號 /// public DataSet GetLoginUserInfo(string staffIdList) { DataSet ds = new DataSet(); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(" SELECT distinct OpenId FROM "); stringBuilder.Append(" TBSF_Conmmunicate_WXUser WHERE Staff_ID IN ("); stringBuilder.Append(staffIdList); stringBuilder.Append(")"); string strSql = stringBuilder.ToString(); sqlHelper.DBRunSql(strSql, ref ds); return ds; } } } 五、编写订阅消息基类模型
using System; using System.Data; using Newtonsoft.Json; using System.Collections.Generic; using WXERP.Services.CommunicationOperateDAL; namespace WXERP.Models { /// /// 訂閲消息請求模型 /// public class SubscribeMessageModel { /// /// 初始化審核訂閲消息 /// /// 數據庫事務 /// 下一個審核通知用戶工號 public SubscribeMessageModel(object dbTransOrCnn, string nextAuditStaffId) { WXInforDeal wxInfoDeal = new WXInforDeal(dbTransOrCnn); DataSet wxUserInfo = wxInfoDeal.GetLoginUserInfo(nextAuditStaffId); if (wxUserInfo != null && wxUserInfo.Tables.Count > 0 && wxUserInfo.Tables[0].Rows.Count > 0) { Touser = wxUserInfo.Tables[0].Rows[0]["OpenId"].ToString(); } } /// /// 消息接收者的openid /// [JsonProperty("touser")] public string Touser { get; set; } /// /// 消息模板ID /// [JsonProperty("template_id")] public string TemplateId { get; set; } /// /// 點擊模板卡片后的跳轉頁面,僅限本小程序内的頁面,支持帶參數(示例index?foo=bar),該字段不填則不跳轉 /// [JsonProperty("page")] public string Page { get; set; } /// /// 跳轉小程序類型:developer開發版、trial體驗版、formal正式版,默认为正式版 /// [JsonProperty("miniprogram_state")] public string MiniprogramState { get; set; } /// /// 進入小程序查看的語言類型,支持zh_CN(簡體中文)、en_US(英文)、zh_HK(繁體中文)、zh_TW(繁體中文),默認為zh_CN /// [JsonProperty("lang")] public string Lang { get; set; } /// /// 模板内容 /// [JsonProperty("data")] public Dictionary Data { get; set; } } /// /// 模板内容關鍵字 /// public class DataValue { /// /// 訂閲消息參數值 /// [JsonProperty("value")] public string Value { get; set; } } /// /// 小程序訂閲消息響應模型 /// public class SubscribeMsgResponseModel { /// /// 錯誤代碼 /// public int Errcode { get; set; } /// /// 錯誤信息 /// public string Errmsg { get; set; } } /// /// 小程序獲取token響應模型 /// public class AccessTokenResponseModel { /// /// 小程序訪問token /// public string Access_token { get; set; } /// /// Token過期時間,單位秒 ///
相关内容
- .NET Core下使用Log4Net记录日志的方法步骤_实用技巧_
- .NET Core下使用Kafka的方法步骤_实用技巧_
- 创建一个ASP.NET MVC5项目的实现方法(图文)_实用技巧_
- .NetCore之接口缓存的实现示例_实用技巧_
- .net 中的 StringBuilder 和 TextWriter 区别详解_实用技巧_
- 深入浅析ASP在线压缩access数据库的方法_实用技巧_
- ASP.net百度主动推送功能实现代码_实用技巧_
- asp .net core静态文件资源的深入讲解_实用技巧_
- .net core实用技巧——将EF Core生成的SQL语句显示在控制台中_实用技巧_
- 使用Seq搭建免费的日志服务的方法_实用技巧_
点击排行
本栏推荐
