Building WeChat Integrations with Magicodes.Wx.Sdk

Magicodes.Wx.Sdk is a streamlined, developer-friendly library designed for seamless integration with WeChat Official Accounts, Mini Programs, and WeChat Work. It includes native support for ABP vNext, simpilfying the implementation of complex WeChat ecosystem features.

Quick Setup

To start, install the necessary NuGet package for ASP.NET Core applications:

Install-Package Magicodes.Wx.PublicAccount.Sdk.AspNet

You can cofnigure your WeChat credentials directly in appsettings.json:

{
 "Wx": {
   "PublicAccount": {
     "AppId": "YOUR_APP_ID",
     "AppSecret": "YOUR_APP_SECRET"
   }
 }
}

Register the SDK services in your Program.cs or Startup.cs:

builder.Services.AddMPublicAccountSdk()
   .AddDistributedMemoryCache();

// In the middleware pipeline
app.UseMPublicAccountSdk()
  .UseWxDistributedCacheForAccessToken();

Consuming APIs

The library uses dependency injection to expose specific functional APIs. For example, to manage menus, inject IMenuApi:

public class MenuController : ControllerBase
{
   private readonly IMenuApi _menuApi;

   public MenuController(IMenuApi menuApi) => _menuApi = menuApi;

   public async Task UpdateMenu()
   {
       var result = await _menuApi.CreateAsync(new CreateMenuInput {
           Button = new List<MenuButtonBase> {
               new ClickButton { Name = "Hello", Key = "GREETING" }
           }
       });
       result.EnsureSuccess();
   }
}

Handling WeChat Events

To process incoming messages or events from WeChat servers, implement the IWxEventsHandler interface:

public class MyEventHandler : IWxEventsHandler
{
   public async Task<ToMessageBase> Execute(IFromMessage fromMessage)
   {
       return fromMessage switch
       {
           FromTextMessage text => new ToTextMessage { Content = $"Echo: {text.Content}" },
           FromSubscribeEvent _ => new ToTextMessage { Content = "Welcome!" },
           _ => new ToNullMessage()
       };
   }
}

Ensure you register this implementation in your service container to enable automatic event routing.

Web OAuth Integration

The SDK simplifies the OAuth flow for ASP.NET Controllers. Inherit from WxPublicAccountControllerBase and apply the WxPublicAccountOAuthFilter to enforce authentication:

public class AccountController : WxPublicAccountControllerBase
{
   [WxPublicAccountOAuthFilter(OAuthLevel = OAuthLevels.OpenIdAndUserInfo)]
   public async Task<IActionResult> Profile()
   {
       var userInfo = await GetWeChatUserInfoAsync();
       return View(userInfo);
   }
}

ABP vNext Support

For modular applications, import the ABP module to leverage distributed caching and lifecycle management automatical:

[DependsOn(typeof(WxPublicAccountSdkModule))]
public class MyProjectModule : AbpModule { }

Tags: WeChat DotNetCore ABP oauth sdk

Posted on Fri, 14 Aug 2026 16:36:59 +0000 by lszanto