sunpengfei
2025-08-29 5f935374836ec8b89c209eae174eb3f2f3d4eca5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using Azure.Core;
using Furion;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Furion.UnifyResult;
using Mapster;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace FlexJobApi.Core
{
    /// <summary>
    /// 短信工具
    /// </summary>
    public class SmsUtils
    {
        private readonly IRepository<SmsLog, LogDbContextLocator> rep;
        private readonly AliyunSmsUtils aliyunSmsUtils;
 
        public SmsUtils(
            IRepository<SmsLog, LogDbContextLocator> rep,
            AliyunSmsUtils aliyunSmsUtils)
        {
            this.rep = rep;
            this.aliyunSmsUtils = aliyunSmsUtils;
        }
 
        public async Task<Guid> SendVerifyCode(SendVerifyCodeModel model, CancellationToken cancellationToken = default)
        {
            var code = new Random().Next(100000, 999999).ToString();
            var entity = new SmsLog();
            model.Adapt(entity);
            entity.Expiry = DateTime.Now.AddMinutes(10);
            entity.TemplateParam = new { code }.ToJson();
            await aliyunSmsUtils.SendAsync(model.PhoneNumber, model.TemplateCode, entity.TemplateParam, cancellationToken);
            await rep.InsertAsync(entity);
            if (App.HostEnvironment.IsDevelopment())
            {
                UnifyContext.Fill(new
                {
                    Code = code
                });
            }
            return entity.Id;
        }
 
        public async Task CheckVerifyCode(CheckVerifyCodeModel model, CancellationToken cancellationToken = default)
        {
            var entity = await rep.AsQueryable().AsNoTracking()
                .Where(it =>
                    it.PhoneNumber == model.PhoneNumber
                    && it.TemplateCode == model.TemplateCode.ToString()
                    && it.TemplateParam == new { code = model.VerifyCode }.ToJson()
                    && it.Expiry > DateTimeOffset.Now
                    && !it.IsUsed)
                .FirstOrDefaultAsync(cancellationToken);
            if (entity == null) throw Oops.Oh(EnumErrorCodeType.s400, "验证码无效");
            entity.IsUsed = true;
            await rep.UpdateAsync(entity);
        }
    }
}