feat: 落库微信 UnionID,支持换公众号昵称+手机号迁移 OpenID
All checks were successful
Build and Deploy / deploy (push) Successful in 1m17s
All checks were successful
Build and Deploy / deploy (push) Successful in 1m17s
注册/绑定写入 UnionID;授权登录可回填。换公众号时昵称命中存量客户可凭手机号确认,更新 WechatOpenid 与 UnionID 后登录。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
40b2b7cb72
commit
c2eae1c327
4
db.sql
4
db.sql
@ -1055,6 +1055,7 @@ CREATE TABLE `t_customer` (
|
|||||||
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是',
|
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是',
|
||||||
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '并发戳',
|
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '并发戳',
|
||||||
`WechatOpenid` VARCHAR(64) NULL COMMENT '微信OpenID',
|
`WechatOpenid` VARCHAR(64) NULL COMMENT '微信OpenID',
|
||||||
|
`WechatUnionid` VARCHAR(64) NULL COMMENT '微信UnionID(开放平台)',
|
||||||
`Password` VARCHAR(64) NOT NULL COMMENT '密码(MD5加密存储)',
|
`Password` VARCHAR(64) NOT NULL COMMENT '密码(MD5加密存储)',
|
||||||
PRIMARY KEY (`Id`),
|
PRIMARY KEY (`Id`),
|
||||||
UNIQUE KEY `uk_cus_code` (`CustomerCode`),
|
UNIQUE KEY `uk_cus_code` (`CustomerCode`),
|
||||||
@ -1065,7 +1066,8 @@ CREATE TABLE `t_customer` (
|
|||||||
KEY `idx_cus_parent_status` (`ParentCustomerId`, `Status`),
|
KEY `idx_cus_parent_status` (`ParentCustomerId`, `Status`),
|
||||||
KEY `idx_cus_status_group` (`Status`, `CustomerGroup`),
|
KEY `idx_cus_status_group` (`Status`, `CustomerGroup`),
|
||||||
KEY `idx_cus_sales_service` (`Salesman`, `CustomerService`),
|
KEY `idx_cus_sales_service` (`Salesman`, `CustomerService`),
|
||||||
KEY `idx_cus_organization` (`OrganizationId`)
|
KEY `idx_cus_organization` (`OrganizationId`),
|
||||||
|
KEY `ix_cus_wechat_unionid` (`WechatUnionid`)
|
||||||
) COMMENT='客户表';
|
) COMMENT='客户表';
|
||||||
|
|
||||||
CREATE TABLE `t_recharge_record` (
|
CREATE TABLE `t_recharge_record` (
|
||||||
|
|||||||
36
sql/migrate_customer_wechat_unionid_20261112.sql
Normal file
36
sql/migrate_customer_wechat_unionid_20261112.sql
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
-- 客户表增加微信 UnionID(可重复执行;禁止 UNIQUE)
|
||||||
|
-- 用途:微信扫码/授权注册与绑定落库 UnionID,便于开放平台下跨应用识别
|
||||||
|
|
||||||
|
SET @db := DATABASE();
|
||||||
|
|
||||||
|
SET @exists := (
|
||||||
|
SELECT COUNT(1)
|
||||||
|
FROM information_schema.COLUMNS
|
||||||
|
WHERE TABLE_SCHEMA = @db
|
||||||
|
AND TABLE_NAME = 't_customer'
|
||||||
|
AND COLUMN_NAME = 'WechatUnionid'
|
||||||
|
);
|
||||||
|
SET @sql := IF(
|
||||||
|
@exists = 0,
|
||||||
|
'ALTER TABLE `t_customer` ADD COLUMN `WechatUnionid` VARCHAR(64) NULL COMMENT ''微信UnionID(开放平台)'' AFTER `WechatOpenid`',
|
||||||
|
'SELECT ''t_customer.WechatUnionid already exists'' AS info'
|
||||||
|
);
|
||||||
|
PREPARE stmt FROM @sql;
|
||||||
|
EXECUTE stmt;
|
||||||
|
DEALLOCATE PREPARE stmt;
|
||||||
|
|
||||||
|
SET @idx_exists := (
|
||||||
|
SELECT COUNT(1)
|
||||||
|
FROM information_schema.STATISTICS
|
||||||
|
WHERE TABLE_SCHEMA = @db
|
||||||
|
AND TABLE_NAME = 't_customer'
|
||||||
|
AND INDEX_NAME = 'ix_cus_wechat_unionid'
|
||||||
|
);
|
||||||
|
SET @sql := IF(
|
||||||
|
@idx_exists = 0,
|
||||||
|
'ALTER TABLE `t_customer` ADD KEY `ix_cus_wechat_unionid` (`WechatUnionid`)',
|
||||||
|
'SELECT ''ix_cus_wechat_unionid already exists'' AS info'
|
||||||
|
);
|
||||||
|
PREPARE stmt FROM @sql;
|
||||||
|
EXECUTE stmt;
|
||||||
|
DEALLOCATE PREPARE stmt;
|
||||||
@ -12,6 +12,7 @@ public static class WeChatRegistrationFieldNormalizer
|
|||||||
public const int CustomerWechatAvatarMaxLength = 255;
|
public const int CustomerWechatAvatarMaxLength = 255;
|
||||||
public const int NicknameMaxLength = 64;
|
public const int NicknameMaxLength = 64;
|
||||||
public const int OpenidMaxLength = 64;
|
public const int OpenidMaxLength = 64;
|
||||||
|
public const int UnionidMaxLength = 64;
|
||||||
|
|
||||||
/// <summary>微信头像仅写入 t_customer;RBAC user.Avatar 列更短,注册时不写入。</summary>
|
/// <summary>微信头像仅写入 t_customer;RBAC user.Avatar 列更短,注册时不写入。</summary>
|
||||||
public static string? NormalizeCustomerWechatAvatar(string? avatar) =>
|
public static string? NormalizeCustomerWechatAvatar(string? avatar) =>
|
||||||
|
|||||||
@ -66,5 +66,8 @@ public class Customer : OmsAuditedAggregateRoot
|
|||||||
|
|
||||||
public string? WechatOpenid { get; set; }
|
public string? WechatOpenid { get; set; }
|
||||||
|
|
||||||
|
/// <summary>微信开放平台 UnionID(同一主体下跨应用唯一;未绑开放平台时可能为空)。</summary>
|
||||||
|
public string? WechatUnionid { get; set; }
|
||||||
|
|
||||||
public string Password { get; set; } = string.Empty;
|
public string Password { get; set; } = string.Empty;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -29,6 +29,11 @@ public interface ICustomerRepository : IRepository<Customer>
|
|||||||
|
|
||||||
Task<bool> ExistsWechatOpenidAnyAsync(string wechatOpenid, CancellationToken cancellationToken = default);
|
Task<bool> ExistsWechatOpenidAnyAsync(string wechatOpenid, CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 是否存在主客户(无上级)且微信昵称精确匹配(已 trim 的值)。
|
||||||
|
/// </summary>
|
||||||
|
Task<bool> ExistsMainByWechatNicknameAsync(string nickname, CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 查询指定年月前缀下的客户编号列表(5 位或 6 位序号体)。
|
/// 查询指定年月前缀下的客户编号列表(5 位或 6 位序号体)。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@ -92,6 +92,13 @@ public class CustomerRepository : OmsSqlSugarRepository<Customer>, ICustomerRepo
|
|||||||
return hit.HasValue;
|
return hit.HasValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public Task<bool> ExistsMainByWechatNicknameAsync(string nickname, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
return AnyAsync(
|
||||||
|
x => x.WechatNickname == nickname && x.ParentCustomerId == null,
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
public async Task<IReadOnlyList<string>> ListCustomerCodesByPrefixAsync(
|
public async Task<IReadOnlyList<string>> ListCustomerCodesByPrefixAsync(
|
||||||
string prefix,
|
string prefix,
|
||||||
CancellationToken cancellationToken = default)
|
CancellationToken cancellationToken = default)
|
||||||
|
|||||||
@ -39,6 +39,7 @@ public class WeChatRouteIntegrationTests
|
|||||||
host.RoutePatterns.Should().Contain("wechat/oauth/user-info");
|
host.RoutePatterns.Should().Contain("wechat/oauth/user-info");
|
||||||
host.RoutePatterns.Should().Contain("wechat/customer/register");
|
host.RoutePatterns.Should().Contain("wechat/customer/register");
|
||||||
host.RoutePatterns.Should().Contain("wechat/customer/bind");
|
host.RoutePatterns.Should().Contain("wechat/customer/bind");
|
||||||
|
host.RoutePatterns.Should().Contain("wechat/customer/rebind-openid");
|
||||||
host.RoutePatterns.Should().Contain("rbac/auth/wx-login/status");
|
host.RoutePatterns.Should().Contain("rbac/auth/wx-login/status");
|
||||||
host.RoutePatterns.Should().Contain("rbac/auth/wx-oauth-login");
|
host.RoutePatterns.Should().Contain("rbac/auth/wx-oauth-login");
|
||||||
}
|
}
|
||||||
|
|||||||
@ -46,6 +46,7 @@ public partial class AuthService(
|
|||||||
FakeRbacDbContext rbacDbContext,
|
FakeRbacDbContext rbacDbContext,
|
||||||
ICustomerRepository customerRepository,
|
ICustomerRepository customerRepository,
|
||||||
IWeChatLoginSessionStore weChatLoginSessionStore,
|
IWeChatLoginSessionStore weChatLoginSessionStore,
|
||||||
|
IWeChatOpenidMigrateTicketStore openidMigrateTicketStore,
|
||||||
IMemoryCache memoryCache,
|
IMemoryCache memoryCache,
|
||||||
IRbacAuthCache rbacAuthCache,
|
IRbacAuthCache rbacAuthCache,
|
||||||
IObjectStorage fileStorage)
|
IObjectStorage fileStorage)
|
||||||
@ -199,10 +200,11 @@ public partial class AuthService(
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 微信网页授权登录(H5 内点按钮授权,无需扫码)。
|
/// 微信网页授权登录(H5 内点按钮授权,无需扫码)。
|
||||||
|
/// OpenID 未绑定但昵称命中存量主客户时返回 NeedOpenidMigrate,不抛「未绑定」。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[AllowAnonymous]
|
[AllowAnonymous]
|
||||||
[HttpPost("/rbac/auth/wx-oauth-login")]
|
[HttpPost("/rbac/auth/wx-oauth-login")]
|
||||||
public async Task<OmsLoginResultDto> WxOAuthLoginAsync(
|
public async Task<OmsWxOAuthLoginResultDto> WxOAuthLoginAsync(
|
||||||
[FromBody] OmsWxOAuthLoginInput input,
|
[FromBody] OmsWxOAuthLoginInput input,
|
||||||
CancellationToken cancellationToken = default)
|
CancellationToken cancellationToken = default)
|
||||||
{
|
{
|
||||||
@ -220,6 +222,31 @@ public partial class AuthService(
|
|||||||
var customer = await customerRepository.GetByWechatOpenidAsync(token.OpenId, cancellationToken);
|
var customer = await customerRepository.GetByWechatOpenidAsync(token.OpenId, cancellationToken);
|
||||||
if (customer == null)
|
if (customer == null)
|
||||||
{
|
{
|
||||||
|
var userInfo = await WeChatMpApiClient.GetOAuthUserInfoAsync(
|
||||||
|
token.AccessToken,
|
||||||
|
token.OpenId,
|
||||||
|
cancellationToken);
|
||||||
|
var nickname = userInfo?.Nickname;
|
||||||
|
var unionid = WeChatRegistrationFieldNormalizer.TruncateOptional(
|
||||||
|
userInfo?.Unionid ?? token.Unionid,
|
||||||
|
WeChatRegistrationFieldNormalizer.UnionidMaxLength);
|
||||||
|
var (hit, migrateTicket) = await WeChatOpenidMigrateSupport.TryIssueMigrateTicketAsync(
|
||||||
|
customerRepository,
|
||||||
|
openidMigrateTicketStore,
|
||||||
|
token.OpenId,
|
||||||
|
nickname,
|
||||||
|
unionid,
|
||||||
|
cancellationToken);
|
||||||
|
if (hit && !string.IsNullOrWhiteSpace(migrateTicket))
|
||||||
|
{
|
||||||
|
return new OmsWxOAuthLoginResultDto
|
||||||
|
{
|
||||||
|
NeedOpenidMigrate = true,
|
||||||
|
MigrateTicket = migrateTicket,
|
||||||
|
Nickname = WeChatOpenidMigrateSupport.NormalizeNickname(nickname)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
throw new BusinessException("未绑定微信,请先注册或绑定账号");
|
throw new BusinessException("未绑定微信,请先注册或绑定账号");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -230,6 +257,28 @@ public partial class AuthService(
|
|||||||
|
|
||||||
ValidateMainCustomerStatus(customer);
|
ValidateMainCustomerStatus(customer);
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(customer.WechatUnionid))
|
||||||
|
{
|
||||||
|
var unionid = WeChatRegistrationFieldNormalizer.TruncateOptional(
|
||||||
|
token.Unionid,
|
||||||
|
WeChatRegistrationFieldNormalizer.UnionidMaxLength);
|
||||||
|
if (string.IsNullOrWhiteSpace(unionid))
|
||||||
|
{
|
||||||
|
var userInfo = await WeChatMpApiClient.GetOAuthUserInfoAsync(
|
||||||
|
token.AccessToken,
|
||||||
|
token.OpenId,
|
||||||
|
cancellationToken);
|
||||||
|
unionid = WeChatRegistrationFieldNormalizer.TruncateOptional(
|
||||||
|
userInfo?.Unionid,
|
||||||
|
WeChatRegistrationFieldNormalizer.UnionidMaxLength);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(unionid))
|
||||||
|
{
|
||||||
|
customer.WechatUnionid = unionid;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
customer.LastLoginIp = httpContextAccessor.HttpContext?.Connection.RemoteIpAddress?.ToString();
|
customer.LastLoginIp = httpContextAccessor.HttpContext?.Connection.RemoteIpAddress?.ToString();
|
||||||
customer.LastLoginTime = DateTime.Now;
|
customer.LastLoginTime = DateTime.Now;
|
||||||
await customerRepository.UpdateAsync(customer, cancellationToken);
|
await customerRepository.UpdateAsync(customer, cancellationToken);
|
||||||
@ -240,6 +289,95 @@ public partial class AuthService(
|
|||||||
throw new BusinessException("客户未关联用户");
|
throw new BusinessException("客户未关联用户");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var login = await BuildLoginResultAsync(userGuid.Value, OmsLoginType.Customer, cancellationToken);
|
||||||
|
return new OmsWxOAuthLoginResultDto
|
||||||
|
{
|
||||||
|
AccessToken = login.AccessToken,
|
||||||
|
RefreshToken = login.RefreshToken,
|
||||||
|
TokenType = login.TokenType,
|
||||||
|
ExpiresIn = login.ExpiresIn,
|
||||||
|
UserId = login.UserId,
|
||||||
|
UserInfo = login.UserInfo
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 换公众号:凭迁移 ticket + 手机号确认后,更新客户 WechatOpenid(及本次授权的 UnionID)并登录。
|
||||||
|
/// </summary>
|
||||||
|
[AllowAnonymous]
|
||||||
|
[HttpPost("/wechat/customer/rebind-openid")]
|
||||||
|
[ApiExplorerSettings(GroupName = "WeChat")]
|
||||||
|
public async Task<OmsLoginResultDto> RebindWechatOpenidAsync(
|
||||||
|
[FromBody] WeChatOpenidRebindInput input,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(input.Ticket))
|
||||||
|
{
|
||||||
|
throw new BusinessException("迁移凭证无效或已过期,请重新授权");
|
||||||
|
}
|
||||||
|
|
||||||
|
var phone = CustomerContactHelper.NormalizeOptionalContact(input.Phone);
|
||||||
|
phone = WeChatRegistrationFieldNormalizer.TruncateOptional(
|
||||||
|
phone,
|
||||||
|
WeChatRegistrationFieldNormalizer.PhoneMaxLength);
|
||||||
|
if (string.IsNullOrWhiteSpace(phone))
|
||||||
|
{
|
||||||
|
throw new BusinessException("请输入手机号");
|
||||||
|
}
|
||||||
|
|
||||||
|
var ticketPayload = await openidMigrateTicketStore.GetAsync(input.Ticket.Trim(), cancellationToken);
|
||||||
|
if (ticketPayload == null
|
||||||
|
|| string.IsNullOrWhiteSpace(ticketPayload.OpenId)
|
||||||
|
|| string.IsNullOrWhiteSpace(ticketPayload.Nickname))
|
||||||
|
{
|
||||||
|
throw new BusinessException("迁移凭证无效或已过期,请重新授权");
|
||||||
|
}
|
||||||
|
|
||||||
|
var customer = await customerRepository.GetByPhoneAsync(phone, cancellationToken);
|
||||||
|
if (customer == null)
|
||||||
|
{
|
||||||
|
throw new BusinessException("未找到该手机号对应的客户");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (customer.ParentCustomerId.HasValue)
|
||||||
|
{
|
||||||
|
throw new BusinessException("子客户不支持更新微信绑定");
|
||||||
|
}
|
||||||
|
|
||||||
|
ValidateMainCustomerStatus(customer);
|
||||||
|
|
||||||
|
var customerNick = WeChatOpenidMigrateSupport.NormalizeNickname(customer.WechatNickname);
|
||||||
|
if (!string.Equals(customerNick, ticketPayload.Nickname, StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
throw new BusinessException("手机号与微信昵称不匹配,无法更新绑定");
|
||||||
|
}
|
||||||
|
|
||||||
|
var newOpenId = WeChatRegistrationFieldNormalizer.TruncateRequired(
|
||||||
|
ticketPayload.OpenId.Trim(),
|
||||||
|
WeChatRegistrationFieldNormalizer.OpenidMaxLength);
|
||||||
|
var occupied = await customerRepository.GetByWechatOpenidAsync(newOpenId, cancellationToken);
|
||||||
|
if (occupied != null && occupied.Id != customer.Id)
|
||||||
|
{
|
||||||
|
throw new BusinessException("当前微信已绑定账号");
|
||||||
|
}
|
||||||
|
|
||||||
|
customer.WechatOpenid = newOpenId;
|
||||||
|
if (!string.IsNullOrWhiteSpace(ticketPayload.Unionid))
|
||||||
|
{
|
||||||
|
customer.WechatUnionid = ticketPayload.Unionid;
|
||||||
|
}
|
||||||
|
|
||||||
|
customer.LastLoginIp = httpContextAccessor.HttpContext?.Connection.RemoteIpAddress?.ToString();
|
||||||
|
customer.LastLoginTime = DateTime.Now;
|
||||||
|
await customerRepository.UpdateAsync(customer, cancellationToken);
|
||||||
|
await openidMigrateTicketStore.RemoveAsync(input.Ticket.Trim(), cancellationToken);
|
||||||
|
|
||||||
|
var userGuid = await GetRbacUserGuidByMapIdAsync(customer.UserId, cancellationToken);
|
||||||
|
if (!userGuid.HasValue)
|
||||||
|
{
|
||||||
|
throw new BusinessException("客户未关联用户");
|
||||||
|
}
|
||||||
|
|
||||||
return await BuildLoginResultAsync(userGuid.Value, OmsLoginType.Customer, cancellationToken);
|
return await BuildLoginResultAsync(userGuid.Value, OmsLoginType.Customer, cancellationToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
16
src/SimpleAdmin.Api/Auth/OmsWxOAuthLoginResultDto.cs
Normal file
16
src/SimpleAdmin.Api/Auth/OmsWxOAuthLoginResultDto.cs
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
namespace SimpleAdmin.Api.Auth;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 微信网页授权登录结果:成功时带令牌;需迁移 OpenID 时仅返回标记与 ticket。
|
||||||
|
/// </summary>
|
||||||
|
public class OmsWxOAuthLoginResultDto : OmsLoginResultDto
|
||||||
|
{
|
||||||
|
/// <summary>新 OpenID 未绑定,但昵称命中存量主客户。</summary>
|
||||||
|
public bool NeedOpenidMigrate { get; set; }
|
||||||
|
|
||||||
|
/// <summary>迁移凭证,配合 /wechat/customer/rebind-openid 使用。</summary>
|
||||||
|
public string? MigrateTicket { get; set; }
|
||||||
|
|
||||||
|
/// <summary>本次授权微信昵称(展示用)。</summary>
|
||||||
|
public string? Nickname { get; set; }
|
||||||
|
}
|
||||||
@ -70,6 +70,27 @@ public class WeChatOAuthUserInfoOutput
|
|||||||
public string? Unionid { get; set; }
|
public string? Unionid { get; set; }
|
||||||
|
|
||||||
public bool AlreadyBound { get; set; }
|
public bool AlreadyBound { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 新 OpenID 未绑定,但存在同微信昵称的主客户,建议走手机号确认迁移 OpenID。
|
||||||
|
/// </summary>
|
||||||
|
public bool SuggestOpenidMigrate { get; set; }
|
||||||
|
|
||||||
|
/// <summary>迁移凭证(SuggestOpenidMigrate 时有值,约 10 分钟)。</summary>
|
||||||
|
public string? MigrateTicket { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>换公众号:手机号确认后仅更新 WechatOpenid。</summary>
|
||||||
|
public class WeChatOpenidRebindInput
|
||||||
|
{
|
||||||
|
/// <summary>探测阶段签发的短时凭证。</summary>
|
||||||
|
[Required]
|
||||||
|
public string Ticket { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
/// <summary>用于唯一定位客户的手机号。</summary>
|
||||||
|
[Required]
|
||||||
|
[StringLength(16)]
|
||||||
|
public string Phone { get; set; } = string.Empty;
|
||||||
}
|
}
|
||||||
|
|
||||||
public class WeChatProfileInput
|
public class WeChatProfileInput
|
||||||
|
|||||||
@ -0,0 +1,18 @@
|
|||||||
|
namespace SimpleAdmin.Api.WeChat.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 换公众号 OpenID 迁移短时凭证(默认 10 分钟,一次性消费)。
|
||||||
|
/// </summary>
|
||||||
|
public interface IWeChatOpenidMigrateTicketStore
|
||||||
|
{
|
||||||
|
Task<string> IssueAsync(
|
||||||
|
WeChatOpenidMigrateTicketPayload payload,
|
||||||
|
TimeSpan ttl,
|
||||||
|
CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
|
Task<WeChatOpenidMigrateTicketPayload?> GetAsync(
|
||||||
|
string ticket,
|
||||||
|
CancellationToken cancellationToken = default);
|
||||||
|
|
||||||
|
Task RemoveAsync(string ticket, CancellationToken cancellationToken = default);
|
||||||
|
}
|
||||||
@ -1,3 +1,4 @@
|
|||||||
|
using Oms.Application.Shared;
|
||||||
using Oms.Domain.CustomersAggregate.Repositories;
|
using Oms.Domain.CustomersAggregate.Repositories;
|
||||||
|
|
||||||
namespace SimpleAdmin.Api.WeChat.Services;
|
namespace SimpleAdmin.Api.WeChat.Services;
|
||||||
@ -66,6 +67,18 @@ public class WeChatEventHandler(
|
|||||||
"未绑定账号,请点击底部菜单「登录注册」完成注册或绑定已有账号。");
|
"未绑定账号,请点击底部菜单「登录注册」完成注册或绑定已有账号。");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrWhiteSpace(customer.WechatUnionid))
|
||||||
|
{
|
||||||
|
var unionid = WeChatRegistrationFieldNormalizer.TruncateOptional(
|
||||||
|
message.UnionId,
|
||||||
|
WeChatRegistrationFieldNormalizer.UnionidMaxLength);
|
||||||
|
if (!string.IsNullOrWhiteSpace(unionid))
|
||||||
|
{
|
||||||
|
customer.WechatUnionid = unionid;
|
||||||
|
await customerRepository.UpdateAsync(customer, cancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var payload = new WeChatLoginSessionPayload
|
var payload = new WeChatLoginSessionPayload
|
||||||
{
|
{
|
||||||
CustomerId = customer.Id,
|
CustomerId = customer.Id,
|
||||||
|
|||||||
@ -32,7 +32,7 @@ public interface IWeChatMpApiClient
|
|||||||
Task InvalidateAccessTokenCacheAsync(CancellationToken cancellationToken = default);
|
Task InvalidateAccessTokenCacheAsync(CancellationToken cancellationToken = default);
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed record WeChatOAuthTokenResult(string AccessToken, string OpenId);
|
public sealed record WeChatOAuthTokenResult(string AccessToken, string OpenId, string? Unionid = null);
|
||||||
|
|
||||||
public sealed record WeChatOAuthUserResult(
|
public sealed record WeChatOAuthUserResult(
|
||||||
string Openid,
|
string Openid,
|
||||||
@ -199,7 +199,7 @@ internal sealed class WeChatMpApiClient(
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return new WeChatOAuthTokenResult(body.AccessToken, body.Openid);
|
return new WeChatOAuthTokenResult(body.AccessToken, body.Openid, body.Unionid);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<WeChatOAuthUserResult?> GetOAuthUserInfoAsync(
|
public async Task<WeChatOAuthUserResult?> GetOAuthUserInfoAsync(
|
||||||
@ -366,6 +366,9 @@ internal sealed class WeChatMpApiClient(
|
|||||||
[JsonPropertyName("openid")]
|
[JsonPropertyName("openid")]
|
||||||
public string? Openid { get; set; }
|
public string? Openid { get; set; }
|
||||||
|
|
||||||
|
[JsonPropertyName("unionid")]
|
||||||
|
public string? Unionid { get; set; }
|
||||||
|
|
||||||
[JsonPropertyName("errcode")]
|
[JsonPropertyName("errcode")]
|
||||||
public int Errcode { get; set; }
|
public int Errcode { get; set; }
|
||||||
|
|
||||||
@ -433,7 +436,8 @@ internal static class WeChatXmlMessageParser
|
|||||||
MsgType = Value("MsgType"),
|
MsgType = Value("MsgType"),
|
||||||
Event = Value("Event"),
|
Event = Value("Event"),
|
||||||
EventKey = Value("EventKey"),
|
EventKey = Value("EventKey"),
|
||||||
Content = Value("Content")
|
Content = Value("Content"),
|
||||||
|
UnionId = Value("UnionId")
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -477,7 +481,8 @@ internal static class WeChatJsonMessageParser
|
|||||||
MsgType = GetString("MsgType"),
|
MsgType = GetString("MsgType"),
|
||||||
Event = GetString("Event"),
|
Event = GetString("Event"),
|
||||||
EventKey = GetString("EventKey"),
|
EventKey = GetString("EventKey"),
|
||||||
Content = GetString("Content")
|
Content = GetString("Content"),
|
||||||
|
UnionId = GetString("UnionId")
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
catch (JsonException)
|
catch (JsonException)
|
||||||
@ -525,6 +530,9 @@ public sealed class WeChatIncomingMessage
|
|||||||
public string? EventKey { get; init; }
|
public string? EventKey { get; init; }
|
||||||
|
|
||||||
public string? Content { get; init; }
|
public string? Content { get; init; }
|
||||||
|
|
||||||
|
/// <summary>开放平台绑定后事件推送可能带 UnionId。</summary>
|
||||||
|
public string? UnionId { get; init; }
|
||||||
}
|
}
|
||||||
|
|
||||||
internal static class WeChatXmlMessageBuilder
|
internal static class WeChatXmlMessageBuilder
|
||||||
|
|||||||
@ -0,0 +1,51 @@
|
|||||||
|
using Oms.Application.Shared;
|
||||||
|
using Oms.Domain.CustomersAggregate.Repositories;
|
||||||
|
|
||||||
|
namespace SimpleAdmin.Api.WeChat.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 换公众号 OpenID 迁移:昵称探测与签发 ticket。
|
||||||
|
/// </summary>
|
||||||
|
internal static class WeChatOpenidMigrateSupport
|
||||||
|
{
|
||||||
|
public static readonly TimeSpan TicketTtl = TimeSpan.FromMinutes(10);
|
||||||
|
|
||||||
|
public static string? NormalizeNickname(string? nickname) =>
|
||||||
|
WeChatRegistrationFieldNormalizer.TruncateOptional(
|
||||||
|
nickname,
|
||||||
|
WeChatRegistrationFieldNormalizer.NicknameMaxLength);
|
||||||
|
|
||||||
|
public static async Task<(bool Hit, string? Ticket)> TryIssueMigrateTicketAsync(
|
||||||
|
ICustomerRepository customerRepository,
|
||||||
|
IWeChatOpenidMigrateTicketStore ticketStore,
|
||||||
|
string openId,
|
||||||
|
string? nickname,
|
||||||
|
string? unionid,
|
||||||
|
CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var normalizedNick = NormalizeNickname(nickname);
|
||||||
|
if (string.IsNullOrWhiteSpace(normalizedNick) || string.IsNullOrWhiteSpace(openId))
|
||||||
|
{
|
||||||
|
return (false, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!await customerRepository.ExistsMainByWechatNicknameAsync(normalizedNick, cancellationToken))
|
||||||
|
{
|
||||||
|
return (false, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
var ticket = await ticketStore.IssueAsync(
|
||||||
|
new WeChatOpenidMigrateTicketPayload
|
||||||
|
{
|
||||||
|
OpenId = openId.Trim(),
|
||||||
|
Nickname = normalizedNick,
|
||||||
|
Unionid = WeChatRegistrationFieldNormalizer.TruncateOptional(
|
||||||
|
unionid,
|
||||||
|
WeChatRegistrationFieldNormalizer.UnionidMaxLength)
|
||||||
|
},
|
||||||
|
TicketTtl,
|
||||||
|
cancellationToken);
|
||||||
|
|
||||||
|
return (true, ticket);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,13 @@
|
|||||||
|
namespace SimpleAdmin.Api.WeChat.Services;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 换公众号 OpenID 迁移凭证:绑定本次授权的 openid / nickname。
|
||||||
|
/// </summary>
|
||||||
|
public sealed class WeChatOpenidMigrateTicketPayload
|
||||||
|
{
|
||||||
|
public string OpenId { get; init; } = string.Empty;
|
||||||
|
|
||||||
|
public string Nickname { get; init; } = string.Empty;
|
||||||
|
|
||||||
|
public string? Unionid { get; init; }
|
||||||
|
}
|
||||||
@ -0,0 +1,55 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using Oms.Application.Helpers;
|
||||||
|
|
||||||
|
namespace SimpleAdmin.Api.WeChat.Services;
|
||||||
|
|
||||||
|
public class WeChatOpenidMigrateTicketStore : IWeChatOpenidMigrateTicketStore
|
||||||
|
{
|
||||||
|
private const string KeyPrefix = "oms:wechat:openid-migrate:";
|
||||||
|
|
||||||
|
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||||
|
{
|
||||||
|
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
|
||||||
|
};
|
||||||
|
|
||||||
|
public async Task<string> IssueAsync(
|
||||||
|
WeChatOpenidMigrateTicketPayload payload,
|
||||||
|
TimeSpan ttl,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var ticket = Guid.NewGuid().ToString("N");
|
||||||
|
var json = JsonSerializer.Serialize(payload, JsonOptions);
|
||||||
|
await RedisHelper.Client.SetAsync(BuildKey(ticket), json, (int)ttl.TotalSeconds);
|
||||||
|
return ticket;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<WeChatOpenidMigrateTicketPayload?> GetAsync(
|
||||||
|
string ticket,
|
||||||
|
CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(ticket))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var raw = await RedisHelper.Client.GetAsync(BuildKey(ticket.Trim()));
|
||||||
|
if (string.IsNullOrWhiteSpace(raw))
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return JsonSerializer.Deserialize<WeChatOpenidMigrateTicketPayload>(raw, JsonOptions);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task RemoveAsync(string ticket, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrWhiteSpace(ticket))
|
||||||
|
{
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
return RedisHelper.Client.DelAsync(BuildKey(ticket.Trim()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string BuildKey(string ticket) => $"{KeyPrefix}{ticket}";
|
||||||
|
}
|
||||||
@ -29,6 +29,7 @@ namespace SimpleAdmin.Api.WeChat;
|
|||||||
public class WeChatCustomerService(
|
public class WeChatCustomerService(
|
||||||
IWeChatMpApiClient weChatMpApiClient,
|
IWeChatMpApiClient weChatMpApiClient,
|
||||||
ICustomerRepository customerRepository,
|
ICustomerRepository customerRepository,
|
||||||
|
IWeChatOpenidMigrateTicketStore openidMigrateTicketStore,
|
||||||
ICustomerReferralCodeRepository referralCodeRepository,
|
ICustomerReferralCodeRepository referralCodeRepository,
|
||||||
IMemberLevelRepository memberLevelRepository,
|
IMemberLevelRepository memberLevelRepository,
|
||||||
IAgentRepository agentRepository,
|
IAgentRepository agentRepository,
|
||||||
@ -66,6 +67,31 @@ public class WeChatCustomerService(
|
|||||||
}
|
}
|
||||||
|
|
||||||
var existing = await customerRepository.GetByWechatOpenidAsync(userInfo.Openid, cancellationToken);
|
var existing = await customerRepository.GetByWechatOpenidAsync(userInfo.Openid, cancellationToken);
|
||||||
|
var unionid = WeChatRegistrationFieldNormalizer.TruncateOptional(
|
||||||
|
userInfo.Unionid ?? token.Unionid,
|
||||||
|
WeChatRegistrationFieldNormalizer.UnionidMaxLength);
|
||||||
|
if (existing != null
|
||||||
|
&& string.IsNullOrWhiteSpace(existing.WechatUnionid)
|
||||||
|
&& !string.IsNullOrWhiteSpace(unionid))
|
||||||
|
{
|
||||||
|
existing.WechatUnionid = unionid;
|
||||||
|
await customerRepository.UpdateAsync(existing, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
var alreadyBound = existing != null;
|
||||||
|
string? migrateTicket = null;
|
||||||
|
var suggestMigrate = false;
|
||||||
|
if (!alreadyBound)
|
||||||
|
{
|
||||||
|
(suggestMigrate, migrateTicket) = await WeChatOpenidMigrateSupport.TryIssueMigrateTicketAsync(
|
||||||
|
customerRepository,
|
||||||
|
openidMigrateTicketStore,
|
||||||
|
userInfo.Openid,
|
||||||
|
userInfo.Nickname,
|
||||||
|
unionid,
|
||||||
|
cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
return new WeChatOAuthUserInfoOutput
|
return new WeChatOAuthUserInfoOutput
|
||||||
{
|
{
|
||||||
Openid = userInfo.Openid,
|
Openid = userInfo.Openid,
|
||||||
@ -75,8 +101,10 @@ public class WeChatCustomerService(
|
|||||||
City = userInfo.City,
|
City = userInfo.City,
|
||||||
Country = userInfo.Country,
|
Country = userInfo.Country,
|
||||||
Headimgurl = userInfo.Headimgurl,
|
Headimgurl = userInfo.Headimgurl,
|
||||||
Unionid = userInfo.Unionid,
|
Unionid = unionid ?? userInfo.Unionid,
|
||||||
AlreadyBound = existing != null
|
AlreadyBound = alreadyBound,
|
||||||
|
SuggestOpenidMigrate = suggestMigrate,
|
||||||
|
MigrateTicket = migrateTicket
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -103,6 +131,9 @@ public class WeChatCustomerService(
|
|||||||
var wechatOpenid = WeChatRegistrationFieldNormalizer.TruncateRequired(
|
var wechatOpenid = WeChatRegistrationFieldNormalizer.TruncateRequired(
|
||||||
input.Wechat.Openid.Trim(),
|
input.Wechat.Openid.Trim(),
|
||||||
WeChatRegistrationFieldNormalizer.OpenidMaxLength);
|
WeChatRegistrationFieldNormalizer.OpenidMaxLength);
|
||||||
|
var wechatUnionid = WeChatRegistrationFieldNormalizer.TruncateOptional(
|
||||||
|
input.Wechat.Unionid,
|
||||||
|
WeChatRegistrationFieldNormalizer.UnionidMaxLength);
|
||||||
var wechatNickname = WeChatRegistrationFieldNormalizer.TruncateOptional(
|
var wechatNickname = WeChatRegistrationFieldNormalizer.TruncateOptional(
|
||||||
input.Wechat.Nickname,
|
input.Wechat.Nickname,
|
||||||
WeChatRegistrationFieldNormalizer.NicknameMaxLength);
|
WeChatRegistrationFieldNormalizer.NicknameMaxLength);
|
||||||
@ -150,6 +181,7 @@ public class WeChatCustomerService(
|
|||||||
Email = email,
|
Email = email,
|
||||||
Password = OmsPasswordHelper.ToMd5(password),
|
Password = OmsPasswordHelper.ToMd5(password),
|
||||||
WechatOpenid = wechatOpenid,
|
WechatOpenid = wechatOpenid,
|
||||||
|
WechatUnionid = wechatUnionid,
|
||||||
WechatNickname = wechatNickname,
|
WechatNickname = wechatNickname,
|
||||||
WechatAvatar = wechatAvatar,
|
WechatAvatar = wechatAvatar,
|
||||||
Status = CustomerStatus.Normal,
|
Status = CustomerStatus.Normal,
|
||||||
@ -229,6 +261,9 @@ public class WeChatCustomerService(
|
|||||||
var wechatOpenid = WeChatRegistrationFieldNormalizer.TruncateRequired(
|
var wechatOpenid = WeChatRegistrationFieldNormalizer.TruncateRequired(
|
||||||
input.Wechat.Openid.Trim(),
|
input.Wechat.Openid.Trim(),
|
||||||
WeChatRegistrationFieldNormalizer.OpenidMaxLength);
|
WeChatRegistrationFieldNormalizer.OpenidMaxLength);
|
||||||
|
var wechatUnionid = WeChatRegistrationFieldNormalizer.TruncateOptional(
|
||||||
|
input.Wechat.Unionid,
|
||||||
|
WeChatRegistrationFieldNormalizer.UnionidMaxLength);
|
||||||
var wechatNickname = WeChatRegistrationFieldNormalizer.TruncateOptional(
|
var wechatNickname = WeChatRegistrationFieldNormalizer.TruncateOptional(
|
||||||
input.Wechat.Nickname,
|
input.Wechat.Nickname,
|
||||||
WeChatRegistrationFieldNormalizer.NicknameMaxLength);
|
WeChatRegistrationFieldNormalizer.NicknameMaxLength);
|
||||||
@ -263,6 +298,11 @@ public class WeChatCustomerService(
|
|||||||
}
|
}
|
||||||
|
|
||||||
customer.WechatOpenid = wechatOpenid;
|
customer.WechatOpenid = wechatOpenid;
|
||||||
|
if (!string.IsNullOrWhiteSpace(wechatUnionid))
|
||||||
|
{
|
||||||
|
customer.WechatUnionid = wechatUnionid;
|
||||||
|
}
|
||||||
|
|
||||||
customer.WechatNickname = wechatNickname ?? customer.WechatNickname;
|
customer.WechatNickname = wechatNickname ?? customer.WechatNickname;
|
||||||
customer.WechatAvatar = wechatAvatar ?? customer.WechatAvatar;
|
customer.WechatAvatar = wechatAvatar ?? customer.WechatAvatar;
|
||||||
await customerRepository.UpdateAsync(customer, cancellationToken);
|
await customerRepository.UpdateAsync(customer, cancellationToken);
|
||||||
|
|||||||
@ -15,6 +15,7 @@ public static class WeChatServiceExtensions
|
|||||||
|
|
||||||
services.AddScoped<IWeChatMpApiClient, WeChatMpApiClient>();
|
services.AddScoped<IWeChatMpApiClient, WeChatMpApiClient>();
|
||||||
services.AddSingleton<IWeChatLoginSessionStore, WeChatLoginSessionStore>();
|
services.AddSingleton<IWeChatLoginSessionStore, WeChatLoginSessionStore>();
|
||||||
|
services.AddSingleton<IWeChatOpenidMigrateTicketStore, WeChatOpenidMigrateTicketStore>();
|
||||||
services.AddTransient<IWeChatEventHandler, WeChatEventHandler>();
|
services.AddTransient<IWeChatEventHandler, WeChatEventHandler>();
|
||||||
|
|
||||||
return services;
|
return services;
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user