增加初始化类文件
xiyunfei authored at 2026-02-27 00:31:51
10.59 KiB
NewLife.WeChat
# NewLife.WeChat 快速开始指南 ## 1. 配置数据库连接 ### 使用 SQLite(推荐开发环境) 在 `appsettings.json` 中添加: ```json { "ConnectionStrings": { "WeChat": "Data Source=Data/WeChat.db" } } ``` ### 使用 MySQL ```json { "ConnectionStrings": { "WeChat": "Server=localhost;Database=WeChat;Uid=root;Pwd=password;" } } ``` ### 使用 SQL Server ```json { "ConnectionStrings": { "WeChat": "Server=.;Database=WeChat;Integrated Security=True" } } ``` ## 2. 初始化数据表 首次运行时,XCode 会自动创建数据表。你也可以手动初始化: ```csharp using NewLife.WeChat.Entities; // XCode 会自动检测并创建表结构 var count = 微信配置.Meta.Count; ``` ## 3. 创建微信配置 ### 添加公众号配置 ```csharp using NewLife.WeChat.Entities; var config = new 微信配置 { AppName = "我的公众号", AppId = "wx1234567890", AppSecret = "your_app_secret", AppType = "公众号", AppCategory = 1, // 1=公众号 IsEnabled = true, Token = "your_token", EncodingAESKey = "your_aes_key" }; config.Insert(); ``` ### 添加小程序配置 ```csharp var miniConfig = new 微信配置 { AppName = "我的小程序", AppId = "wx_mini_123456", AppSecret = "your_mini_secret", AppType = "小程序", AppCategory = 2, // 2=小程序 IsEnabled = true }; miniConfig.Insert(); ``` ## 4. 核心功能使用 ### 4.1 获取 AccessToken ```csharp using NewLife.WeChat.Services; var service = new WeChatService(); // 获取 Token(自动缓存) var token = await service.GetAccessTokenAsync("wx1234567890"); Console.WriteLine($"AccessToken: {token}"); // 强制刷新 var newToken = await service.GetAccessTokenAsync("wx1234567890", forceRefresh: true); ``` ### 4.2 获取用户信息 ```csharp // 在微信回调中处理 [HttpGet("/wechat/callback")] public async Task<IActionResult> WeChatCallback(String code) { if (code.IsNullOrEmpty()) return BadRequest("授权码不能为空"); var service = new WeChatService(); var userInfo = await service.GetUserInfoByCodeAsync("wx1234567890", code); // 保存登录状态 HttpContext.Session.SetString("OpenId", userInfo.OpenId); HttpContext.Session.SetString("UnionId", userInfo.UnionId ?? ""); return Redirect("/home"); } ``` ### 4.3 跨应用用户识别 ```csharp // 获取用户在不同应用的 OpenId var service = new WeChatService(); // 用户在公众号登录后,获取其在小程序的 OpenId var unionId = "user_union_id"; var miniOpenId = service.GetOpenIdByUnionId(unionId, "wx_mini_123456"); if (!miniOpenId.IsNullOrEmpty()) { Console.WriteLine($"用户在小程序的OpenId: {miniOpenId}"); } // 获取该用户在所有应用的信息 var allUsers = service.GetAllOpenIdsByUnionId(unionId); foreach (var user in allUsers) { Console.WriteLine($"AppId: {user.AppId}, OpenId: {user.OpenId}"); } ``` ### 4.4 发送模板消息 #### 配置模板 ```csharp using NewLife.WeChat.Entities; var template = new 微信模板消息配置 { AppId = "wx1234567890", TemplateId = "template_order_success", TemplateName = "订单完成通知", TemplateType = 1, // 1=公众号模板消息 Fields = @"{ ""first"": ""标题"", ""keyword1"": ""订单号"", ""keyword2"": ""金额"", ""remark"": ""备注"" }", FieldsDesc = @"{ ""first"": ""消息标题"", ""keyword1"": ""订单编号"", ""keyword2"": ""订单金额"", ""remark"": ""备注说明"" }", IsEnabled = true }; template.Insert(); ``` #### 发送公众号模板消息 ```csharp var service = new WeChatService(); var data = new { first = new { value = "您的订单已完成", color = "#173177" }, keyword1 = new { value = "202401010001", color = "#173177" }, keyword2 = new { value = "¥99.00", color = "#173177" }, remark = new { value = "感谢您的支持!", color = "#173177" } }; var success = await service.SendTemplateMessageAsync( appid: "wx1234567890", openid: "user_openid_123", templateid: "template_order_success", data: data, url: "https://example.com/order/202401010001" ); Console.WriteLine($"发送结果: {success}"); ``` #### 发送小程序订阅消息 ```csharp var miniData = new { thing1 = new { value = "订单支付成功" }, amount2 = new { value = "99.00元" }, date3 = new { value = DateTime.Now.ToString("yyyy-MM-dd HH:mm") } }; var miniSuccess = await service.SendSubscribeMessageAsync( appid: "wx_mini_123456", openid: "mini_user_openid", templateid: "mini_template_order", data: miniData, page: "pages/order/detail?id=202401010001" ); ``` #### 批量发送 ```csharp var openIds = new List<String> { "openid1", "openid2", "openid3" }; var results = await service.SendBatchTemplateMessagesAsync( "wx1234567890", openIds, "template_order_success", data ); foreach (var result in results) { Console.WriteLine($"OpenId: {result.Key}, 成功: {result.Value}"); } ``` ## 5. 完整业务示例 ### 订单完成后跨应用推送 ```csharp using NewLife.WeChat.Services; using NewLife.WeChat.Entities; /// <summary>订单完成通知服务</summary> public class OrderNotificationService { private readonly WeChatService _wechatService; public OrderNotificationService() { _wechatService = new WeChatService(); } /// <summary>订单完成后通知用户(所有应用)</summary> /// <param name="unionid">用户UnionId</param> /// <param name="orderid">订单号</param> /// <param name="amount">金额</param> public async Task NotifyOrderComplete(String unionid, String orderid, Decimal amount) { // 1. 获取用户在所有应用的信息 var users = _wechatService.GetAllOpenIdsByUnionId(unionid); if (users.Count == 0) { Console.WriteLine($"未找到UnionId为 {unionid} 的用户"); return; } // 2. 遍历所有应用,发送消息 foreach (var user in users) { var config = 微信配置.FindByAppId(user.AppId); if (config == null || !config.IsEnabled) continue; try { if (config.AppCategory == 1) // 公众号 { var data = new { first = new { value = "订单支付成功" }, keyword1 = new { value = orderid }, keyword2 = new { value = $"¥{amount}" }, remark = new { value = "点击查看订单详情" } }; await _wechatService.SendTemplateMessageAsync( user.AppId, user.OpenId, "template_order_success", data, $"https://example.com/order/{orderid}" ); } else if (config.AppCategory == 2) // 小程序 { var data = new { thing1 = new { value = "订单支付成功" }, amount2 = new { value = $"{amount}元" }, date3 = new { value = DateTime.Now.ToString("yyyy-MM-dd HH:mm") } }; await _wechatService.SendSubscribeMessageAsync( user.AppId, user.OpenId, "mini_template_order", data, $"pages/order/detail?id={orderid}" ); } Console.WriteLine($"消息发送成功: {config.AppName}"); } catch (Exception ex) { Console.WriteLine($"消息发送失败: {config.AppName}, {ex.Message}"); } } } } ``` ## 6. ASP.NET Core 集成 ### 6.1 配置服务 在 `Program.cs` 中注册服务: ```csharp using XCode.DataAccessLayer; // 配置 XCode 数据库连接 var connStr = builder.Configuration.GetConnectionString("WeChat"); DAL.AddConnStr("WeChat", connStr, null, "SQLite"); // 注册微信服务 builder.Services.AddSingleton<WeChatService>(); ``` ### 6.2 控制器示例 ```csharp using Microsoft.AspNetCore.Mvc; using NewLife.WeChat.Services; using NewLife.WeChat.Entities; [ApiController] [Route("api/[controller]")] public class WeChatController : ControllerBase { private readonly WeChatService _wechatService; public WeChatController(WeChatService wechatService) { _wechatService = wechatService; } /// <summary>获取AccessToken</summary> [HttpGet("token/{appid}")] public async Task<IActionResult> GetToken(String appid) { var token = await _wechatService.GetAccessTokenAsync(appid); return Ok(new { token }); } /// <summary>微信授权回调</summary> [HttpGet("callback")] public async Task<IActionResult> Callback(String code, String state) { var userInfo = await _wechatService.GetUserInfoByCodeAsync(state, code); return Ok(userInfo); } /// <summary>发送模板消息</summary> [HttpPost("send-template")] public async Task<IActionResult> SendTemplate([FromBody] SendTemplateRequest request) { var success = await _wechatService.SendTemplateMessageAsync( request.AppId, request.OpenId, request.TemplateId, request.Data, request.Url ); return Ok(new { success }); } } public class SendTemplateRequest { public String AppId { get; set; } public String OpenId { get; set; } public String TemplateId { get; set; } public Object Data { get; set; } public String Url { get; set; } } ``` ## 7. 常见问题 ### Q1: AccessToken 获取失败? **A**: 检查 AppId 和 AppSecret 是否正确,确保网络可以访问微信API。 ### Q2: UnionId 为空? **A**: UnionId 只有在应用绑定到微信开放平台后才返回。 ### Q3: 模板消息发送失败? **A**: 检查: - 模板是否已在微信公众平台配置 - 模板是否已启用 - 用户是否关注公众号(公众号模板消息) - 用户是否已订阅(小程序订阅消息) ### Q4: 如何测试功能? **A**: 可以使用微信公众平台的测试号功能进行开发测试。 ## 8. 下一步 - 查看 [架构设计文档](/NewLife/NewLife.WeChat/Blob/master/docs/Architecture.md) 了解详细设计 - 查看 [核心功能实现说明](/NewLife/NewLife.WeChat/Blob/master/docs/CoreFunctions.md) 了解实现细节 - 参考 [README](/NewLife/NewLife.WeChat/Blob/master/docs/../README.md) 了解更多 API --- **文档版本**: v1.0 **更新时间**: 2024-01 **维护者**: NewLife 开发团队