网站集成微信公众号(订阅号)登录

打印 上一主题 下一主题

主题 884|帖子 884|积分 2652

前一阵子,想着给我的站点集成一个微信登录,由于我之前从未有过微信相关的开发,所以我自己跟着网上的资料,一步一步的慢慢的探索,过程难免的遇到了很多坑,才把我的网站微信登录集成完成,所以这里分享一下我的探索的过程。由于我的是订阅号,所以一下的内容均针对订阅号而言的
一、相识微信的交互流程

这里假设我们都已经申请号了微信开发的相关信息,那么我们就要设置微信认证服务器地点(api地点),这一步是必须的,微信与我们交互都是都是通过这一个地点,开始我一直不知道,我以为自己要对每一个功能都要写一个api,其实不需要的。我们只需要完成我们的微信认证服务器地点,然后里面处理我们相关的业务逻辑。

sequenceDiagram  用户->>微信: 发送消息“hello!”  微信->>我的网站: 认证服务api校验  我的网站-)微信: 校验乐成  微信->>我的网站: 发送“hello!”到认证服务api  我的网站-)业务逻辑: 认证服务api接收“hello!”而且处理业务逻辑 我的网站-->> 用户: 也可返回给用户相关信息用我的话就是
假设我的认证api是:/api/check
1.用户发送消息”你好“到微信公众号
2.微信公众号发起Get请求调用 /api/check 进行认证
3.认证乐成时微信公众号再次Post请求调用/api/check,而且携带”你好“信息
4./api/check接口里面处理相关业务逻辑,或者返回特定信息给用户
二、集成相关sdk

对于微信的消息处理,其实有点复杂,这里我网上搜了一下,大部门推荐的是盛派微信sdk,博客园也有相关的教程https://www.cnblogs.com/szw/archive/2013/05/20/3089479.html,个人用起来我觉得还是可以的,可以省去我们大部门工作,专注处理业务逻辑。
封装CustomMessageHandler

首先我是要对盛派微信sdk的封装,所以我新建了一个CustomMessageHandler,然后继续自MessageHandler,然后重新DefaultResponseMessage方法,这里比较简单,直接
public override IResponseMessageBase DefaultResponseMessage(IRequestMessageBase requestMessage)
{
var responseMessage = base.CreateResponseMessage();
return responseMessage;
}
处理用户关注事件

当微信用户关注公众号时我需要发送问候语给用户,那么这里就需要重写OnEvent_SubscribeRequestAsync
public override Task OnEvent_SubscribeRequestAsync(RequestMessageEvent_Subscribe requestMessage)
{
var responseMessage = base.CreateResponseMessage();
responseMessage.Content = “接待关注”;
return Task.FromResult(responseMessage as IResponseMessageBase);
}
处理用户关键字

当微信用户给公众号发送特点消息(关键字)时,我需要回复用户,那么就重写OnTextRequestAsync
public override Task OnTextRequestAsync(RequestMessageText requestMessage)
{
var responseMessage = base.CreateResponseMessage();
return Task.FromResult(responseMessage as IResponseMessageBase);
}
抽离业务逻辑方法

在开发中,我们往往希望封装一个功能时,不需要牵扯太多业务逻辑,就例如不想在CustomMessageHandler里去写业务逻辑,那么我这里采用的委托的形式,新建一个CustomParam,然后里面定义一个两个委托
  1. public class CustomParam
  2.     {
  3.         /// <summary>
  4.         /// 普通文本事件处理
  5.         /// </summary>
  6.         public Func<RequestMessageText, ResponseMessageText, string, ResponseMessageText> OnTextFunc;
  7.         /// <summary>
  8.         /// 订阅事件处理
  9.         /// </summary>
  10.         public Func<string> OnSubscribeFunc;
  11.     }
复制代码
然后通过CustomMessageHandler的构造函数传入
  1.         private CustomParam customParam;
  2.         public CustomMessageHandler(CustomParam customParam)
  3.         {
  4.             this.customParam = customParam;
  5.         }
复制代码
然后在具体的处理事件里面调用这个委托

通过接口调用微信CustomMessageHandler的方法

我接着在建一个接口,里面包含了认证,消息处理,创建CustomMessageHandler的方法,来给业务调用
  1. using Core.WeXin.WxOfficial;
  2. using Senparc.Weixin.AspNet.MvcExtension;
  3. using Senparc.Weixin.MP.Entities;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace Core.WeXin
  10. {
  11.     public interface IWxCommonHandler
  12.     {
  13.         /// <summary>
  14.         /// 校验服务
  15.         /// </summary>
  16.         /// <returns></returns>
  17.         bool CheckSign(string signature, string timestamp, string nonce, string echostr);
  18.         /// <summary>
  19.         /// 创建消息处理器
  20.         /// </summary>
  21.         /// <param name="inputStream"></param>
  22.         /// <param name="messageAbsService"></param>
  23.         void CreateMessageHandler(Stream inputStream, CustomParam param);
  24.         /// <summary>
  25.         /// 公众号消息处理
  26.         /// </summary>
  27.         /// <param name="inputStream"></param>
  28.         /// <returns></returns>
  29.         Task<WeixinResult> ExecuteMessageHandler();
  30.         /// <summary>
  31.         /// 获取当前opentid
  32.         /// </summary>
  33.         /// <returns></returns>
  34.         string GetOpenId();
  35.         /// <summary>
  36.         /// 获取微信消息
  37.         /// </summary>
  38.         /// <returns></returns>
  39.         string GetMessgeText();
  40.     }
  41. }
复制代码
  1. using Core.Log;
  2. using Core.WeXin.WxOfficial;
  3. using Microsoft.Extensions.Configuration;
  4. using Senparc.NeuChar;
  5. using Senparc.NeuChar.Entities;
  6. using Senparc.Weixin.AspNet.MvcExtension;
  7. using Senparc.Weixin.MP;
  8. using Senparc.Weixin.MP.Entities;
  9. using System;
  10. namespace Core.WeXin
  11. {
  12.     internal class WxCommonHandler:IWxCommonHandler
  13.     {
  14.         private CustomMessageHandler customMessageHandler = null;
  15.         private IConfiguration configuration;
  16.         public WxCommonHandler(IConfiguration configuration)
  17.         {
  18.           this.configuration = configuration;
  19.         }
  20.         public bool CheckSign(string signature, string timestamp, string nonce, string echostr)
  21.         {
  22.             string token = configuration.GetSection("SenparcWeixinSetting:Token").Value;
  23.             return CheckSignature.Check(signature, timestamp, nonce, token);
  24.         }
  25.         public void CreateMessageHandler(Stream inputStream,CustomParam customParam)
  26.         {
  27.             customMessageHandler = new CustomMessageHandler(inputStream, null, customParam);
  28.             customMessageHandler.OmitRepeatedMessage = true;
  29.         }
  30.         public async Task<WeixinResult> ExecuteMessageHandler()
  31.         {
  32.             await customMessageHandler.ExecuteAsync(new CancellationToken());
  33.             string result = "";
  34.             if (customMessageHandler.ResponseDocument != null)
  35.             {
  36.                  result = customMessageHandler.ResponseDocument.ToString();
  37.             }
  38.             return new WeixinResult(result);
  39.         }
  40.         public string GetOpenId()
  41.         {
  42.             return customMessageHandler.OpenId;
  43.         }
  44.         public string GetMessgeText()
  45.         {
  46.             var requestMsg= customMessageHandler.RequestMessage;
  47.             if (requestMsg.MsgType == RequestMsgType.Text)
  48.             {
  49.                 RequestMessageText requestText = requestMsg as RequestMessageText;
  50.                 return requestText.Content;
  51.             }
  52.             return string.Empty;
  53.         }
  54.     }
  55. }
复制代码
注册微信sdk相关内容
  1. using Core.Log;
  2. using Microsoft.AspNetCore.Builder;
  3. using Microsoft.Extensions.Configuration;
  4. using Microsoft.Extensions.DependencyInjection;
  5. using Newtonsoft.Json;
  6. using Senparc.CO2NET;
  7. using Senparc.CO2NET.AspNet;
  8. using Senparc.Weixin.AspNet;
  9. using Senparc.Weixin.Entities;
  10. using Senparc.Weixin.MP;
  11. using Senparc.Weixin.RegisterServices;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.Linq;
  15. using System.Text;
  16. using System.Threading.Tasks;
  17. namespace Core.WeXin
  18. {
  19.     public static class ConfigureWxService
  20.     {
  21.         public static IServiceCollection AddWxOfficialServices(this IServiceCollection services, IConfiguration configuration)
  22.         {
  23.             services.AddScoped<IWxCommonHandler, WxCommonHandler>();
  24.             services.AddSenparcWeixinServices(configuration);
  25.             return services;
  26.         }
  27.         public static void UseWxOfficial(this WebApplication app, ConfigurationManager configuration)
  28.         {
  29.             var registerService = app.UseSenparcWeixin(app.Environment, null, null, register => { },
  30.                 (register, weixinSetting) =>
  31.                 {
  32.                     register.RegisterMpAccount(weixinSetting, configuration.GetSection("WxOfficialName").Value);
  33.                 });
  34.         }
  35.     }
  36. }
复制代码
二、新建认证api(Get请求)

前面说到,我们和微信打交道始终是这一个微信,所以我们需要用一个api既能接收认证又能接收消息,所以我先建一个Get请求的方法
  1.   [HttpGet("handler")]
  2.    public ContentResult Handler()
  3.         {
  4.             string signature = Request.Query["signature"];
  5.             string timestamp = Request.Query["timestamp"];
  6.             string nonce = Request.Query["nonce"];
  7.             string echostr = Request.Query["echostr"];
  8.             if (wxCommonHandler.CheckSign(signature, timestamp, nonce, echostr))
  9.             {
  10.                 return new ContentResult()
  11.                 {
  12.                     Content = echostr
  13.                 };
  14.             }
  15.             else
  16.             {
  17.                 return new ContentResult()
  18.                 {
  19.                     Content = "false"
  20.                 };
  21.             }
  22.         }
复制代码
三、新建微信处理的Service

关注事件业务

我想在用户关注时发送对应的问候语,则我直接新建一个方法OnSubscribeEvent
[code]     public string OnSubscribeEvent()        {            StringBuilder sb = new StringBuilder();            sb.Append("您好!接待关注【闲蛋】
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

钜形不锈钢水箱

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表