feat: 完成支持微信扫码功能

This commit is contained in:
ccnetcore
2025-08-27 23:42:46 +08:00
parent 28fcd6c9ce
commit b768bca638
21 changed files with 618 additions and 17 deletions

View File

@@ -3,8 +3,16 @@ using System.Text.Json;
using System.Xml.Serialization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using Volo.Abp.Application.Services;
using Volo.Abp.Caching;
using Volo.Abp.Users;
using Yi.Framework.AiHub.Application.Contracts.Dtos.Fuwuhao;
using Yi.Framework.AiHub.Domain.Managers.Fuwuhao;
using Yi.Framework.AiHub.Domain.Shared.Enums.Fuwuhao;
using Yi.Framework.Rbac.Application.Contracts.Dtos.Account;
using Yi.Framework.Rbac.Application.Contracts.IServices;
namespace Yi.Framework.AiHub.Application.Services;
@@ -15,25 +23,41 @@ public class FuwuhaoService : ApplicationService
{
private readonly ILogger<FuwuhaoService> _logger;
private readonly IHttpContextAccessor _accessor;
private readonly FuwuhaoManager _fuwuhaoManager;
private IDistributedCache<SceneCacheDto> _sceneCache;
private IAccountService _accountService;
private IFileService _fileService;
public FuwuhaoService(ILogger<FuwuhaoService> logger, IHttpContextAccessor accessor)
public FuwuhaoService(ILogger<FuwuhaoService> logger, IHttpContextAccessor accessor, FuwuhaoManager fuwuhaoManager,
IDistributedCache<SceneCacheDto> sceneCache, IAccountService accountService, IFileService fileService)
{
_logger = logger;
_accessor = accessor;
_fuwuhaoManager = fuwuhaoManager;
_sceneCache = sceneCache;
_accountService = accountService;
_fileService = fileService;
}
/// <summary>
/// 查询已登录的账户信息
/// 服务器号测试回调
/// </summary>
/// <returns></returns>
[HttpGet("fuwuhao/callback")]
public async Task<string> GetCallbackAsync([FromQuery] string signature, [FromQuery] string timestamp,
[FromQuery] string nonce, [FromQuery] string echostr)
{
return echostr;
}
/// <summary>
/// 服务号关注回调
/// </summary>
/// <param name="signature"></param>
/// <param name="timestamp"></param>
/// <param name="nonce"></param>
/// <param name="openId"></param>
/// <returns></returns>
[HttpPost("fuwuhao/callback")]
public async Task<string> PostCallbackAsync([FromQuery] string signature, [FromQuery] string timestamp,
[FromQuery] string nonce)
@@ -42,16 +66,124 @@ public class FuwuhaoService : ApplicationService
// 1. 读取原始 XML 内容
using var reader = new StreamReader(request.Body, Encoding.UTF8);
var xmlString = await reader.ReadToEndAsync();
var serializer = new XmlSerializer(typeof(FuwuhaoCallModel));
using var stringReader = new StringReader(xmlString);
var body = (FuwuhaoCallModel)serializer.Deserialize(stringReader);
_logger.LogError("服务号Post回调通知" + JsonSerializer.Serialize(body, new JsonSerializerOptions()
//获取场景值,后续通过场景值设置缓存状态,前端轮询这个场景值用户是否已操作即可
var scene = body.EventKey;
if (scene is null)
{
WriteIndented = true
}));
throw new UserFriendlyException("服务号返回无场景值");
}
var cache = await _sceneCache.GetAsync($"fuwuhao:{scene}");
//根据操作类型,进行业务处理,返回处理结果,再写入缓存,10s过去相当于用户10s扫完app后轮询要在10秒内完成
var scenResult = await _fuwuhaoManager.CallBackHandlerAsync(cache.SceneType, body.FromUserName, cache.UserId);
cache.SceneResult = scenResult;
await _sceneCache.SetAsync($"fuwuhao:{scene}", cache,
new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(10) });
return "success";
}
/// <summary>
/// 创建带参数的二维码
/// </summary>
/// <returns>二维码URL</returns>
[HttpPost("fuwuhao/qrcode")]
public async Task<QrCodeOutput> GetQrCodeAsync([FromQuery] SceneTypeEnum sceneType)
{
//生成一个随机场景值
var scene = Guid.NewGuid().ToString("N");
var qrCodeUrl = await _fuwuhaoManager.CreateQrCodeAsync(scene);
await _sceneCache.SetAsync($"fuwuhao:{scene}", new SceneCacheDto()
{
UserId = CurrentUser.IsAuthenticated ? CurrentUser.GetId() : null,
SceneType = sceneType
}, new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) });
return new QrCodeOutput()
{
QrCodeUrl = qrCodeUrl,
Scene = scene
};
}
/// <summary>
/// 扫码登录/注册/绑定,轮询接口
/// </summary>
/// <param name="scene"></param>
/// <returns></returns>
[HttpGet("fuwuhao/qrcode/result")]
public async Task<QrCodeResultOutput> GetQrCodeResultAsync([FromQuery] string scene)
{
var output = new QrCodeResultOutput();
var cache = await _sceneCache.GetAsync($"fuwuhao:{scene}");
if (cache is null)
{
output.SceneResult = SceneResultEnum.Expired;
return output;
}
output.SceneResult = cache.SceneResult;
switch (output.SceneResult)
{
case SceneResultEnum.Login:
var loginInfo = await _accountService.PostLoginAsync(cache.UserId!.Value);
output.Token = loginInfo.Token;
output.RefreshToken = loginInfo.RefreshToken;
break;
}
return output;
}
/// <summary>
/// 注册账号需要微信code
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
[HttpPost("fuwuhao/register")]
public async Task<LoginOutputDto> RegisterByCodeAsync([FromQuery] string code)
{
//根据code获取到openid、微信用户昵称、头像
var userInfo = await _fuwuhaoManager.GetUserInfoByCodeAsync(code);
var files = new FormFileCollection();
// 下载头像并添加到系统文件中
if (!string.IsNullOrEmpty(userInfo.HeadImgUrl))
{
using var httpClient = new HttpClient();
var imageBytes = await httpClient.GetByteArrayAsync(userInfo.HeadImgUrl);
var imageStream = new MemoryStream(imageBytes);
// 从URL中提取文件扩展名默认为png
var fileName = $"avatar_{userInfo.OpenId}.png";
var formFile = new FormFile(imageStream, 0, imageBytes.Length, "avatar", fileName)
{
Headers = new HeaderDictionary(),
ContentType = "image/png"
};
files.Add(formFile);
}
var result = await _fileService.Post(files);
var userId = await _accountService.PostSystemRegisterAsync(new RegisterDto
{
UserName = userInfo.Nickname,
Password = Guid.NewGuid().ToString("N"),
Phone = null,
Email = null,
Nick = userInfo.Nickname,
Icon = result.FirstOrDefault()?.Id.ToString()
});
return await _accountService.PostLoginAsync(userId);
}
}
[XmlRoot("xml")]