Demo URL: http://wechat.magicodes.net/app/AppDemo/WeChatOAuthTest?tenantId=1
For official documentation on retrieving user information via WeChat Official Accounts, refer to: WeChat Developer Guide.
This example demonstrates how to use the WeChatOAuth attribute in Magicodes.WeiChat to obtain basic user profile data through WeChat's web page authorization flow.
1. Configure Authorization Domain
Before implementation, configure the "Web Page Authorization Domain" in the WeChat Official Account admin panel. Enter you're root domain (e.g., wechat.magicodes.net) in the provided field.
2. Implement Controller Logic
After domain setup, implement the controller as follows:
// Must inherit from AppBaseController
public class AppDemoController : AppBaseController
{
[WeChatOAuth]
public ActionResult WeChatOAuthTest()
{
return View(CurrentUser);
}
}
Key points:
- AppBaseController: Handles tenant ID resolution (from query or route parameters) and integrates with WeChat context management.
- [WeChatOAuth]: Automatically initiates the OAuth flow. After successful authorization, user data is accessible via
CurrentUser(or equivalentlyWeiChatApplicationContext.Current.WeiChatUser). The framework caches this data to avoid redundant API calls and improve performance. - CurrentUser: Provides the authenticated WeChat user object of type
WeiChat_User.
3. Render User Data in View
The corresponding Razor view displays user details:
@using Magicodes.WeiChat.Unity;
@model Magicodes.WeiChat.Data.Models.WeiChat_User
@{
ViewBag.Title = "WeChat OAuth Demo";
}
<div class="aui-content">
<ul class="aui-list-view">
<li class="aui-list-view-cell aui-img">
<img class="aui-img-object aui-pull-left" src="@Model.HeadImgUrl" />
<div class="aui-img-body">
@Model.NickName
<p>
<span class="aui-label aui-label-default">@Model.Remark</span><br />
<span class="aui-label aui-label-primary">@Model.City</span><br />
<span class="aui-label aui-label-success">OPENID: @Model.OpenId</span><br />
<span class="aui-label aui-label-success">@(Model.Sex.GetEnumMemberDisplayName())</span><br />
<a href="#">View Details</a>
</p>
</div>
</li>
</ul>
</div>
4. Set Up Custom Menu (Optional but Recommended)
To easily access the demo, configure a custom menu item in the WeChat admin panel that links to the demo URL.
5. Test the Integration
Open the demo URL in the WeChat mobile app (or desktop WeChat browser). The OAuth flow will trigger automatically, and upon approval, the user’s profile will be displayed.
In summary, the integration requires:
- Setting the authorized redirect domain in WeChat settings.
- Creating a controller inheriting from
AppBaseControllerand applying the[WeChatOAuth]attribute. - Accessing user data via
CurrentUser. - (Optional) Adding a custom menu for easy access.
- Testing via WeChat client.