using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using QYZH.InteractiveMagazine.Infrastructure.Auth; using QYZH.InteractiveMagazine.Infrastructure.Context; using QYZH.InteractiveMagazine.Models.Dto; using QYZH.InteractiveMagazine.Models.Enum; using System.Security.Claims; namespace QYZH.InteractiveMagazine.WeChatApi.Controllers; /// /// 小程序基础控制器 /// [Authorize] [ApiController] [Route("wechat/api/[controller]")] [ApiExplorerSettings(GroupName = nameof(ApiVersionEnum.Wechat))] public abstract class WeChatBaseController : ControllerBase { /// /// 获取当前激活用户ID(Users.Id,来自 JWT NameIdentifier) /// /// User ID(无激活用户时为 0) protected long GetCurrentUserId() { var userIdClaim = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier); if (userIdClaim != null && long.TryParse(userIdClaim.Value, out var userId)) { return userId; } return 0; } /// /// 获取当前微信用户ID(WxUser.Id,来自 JWT WxUserId claim) /// /// WxUser ID protected long? GetCurrentWxUserId() { var wxUserIdClaim = User.Claims.FirstOrDefault(c => c.Type == JwtHelper.WxUserIdClaimType); if (wxUserIdClaim != null && long.TryParse(wxUserIdClaim.Value, out var wxUserId)) { return wxUserId; } return null; } /// /// 获取当前用户名 /// /// 用户名 protected string? GetCurrentUserName() { return User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value; } /// /// 成功响应 /// /// 数据类型 /// 数据 /// 提示信息 /// 统一响应对象 protected BaseResponse Success(T data, string message = "操作成功") { return BaseResponse.Success(data, message); } /// /// 失败响应 /// /// 提示信息 /// 状态码 /// 统一响应对象 protected BaseResponse Fail(string message, int code = 500) { return BaseResponse.Fail(ResultCode.GLOBAL_ERROR, message); } }