| 1 | import { Injectable } from '@nestjs/common'; |
| 2 | import Dysmsapi20170525, * as $Dysmsapi20170525 from '@alicloud/dysmsapi20170525'; |
| 3 | import * as $OpenApi from '@alicloud/openapi-client'; |
| 4 | import * as $Util from '@alicloud/tea-util'; |
| 5 | import { AlicloudSmsOptions } from './interfaces/alicloud-sms-options.interface'; |
| 6 | import { ConfigService } from '@nestjs/config'; |
| 7 | |
| 8 | @Injectable() |
| 9 | export class AlicloudSmsService { |
| 10 | private client: Dysmsapi20170525; |
| 11 | private options: AlicloudSmsOptions; |
| 12 | constructor(private configService: ConfigService) { |
| 13 | const options: AlicloudSmsOptions = this.configService.get('SMS_CONFIG'); |
| 14 | this.options = options; |
| 15 | const config = new $OpenApi.Config({ |
| 16 | ...options.config, |
| 17 | }); |
| 18 | |
| 19 | this.client = new Dysmsapi20170525(config); |
| 20 | } |
| 21 | |
| 22 | /** |
| 23 | * Send message. |
| 24 | * @param phone 手机号 |
| 25 | * @param code 验证码 |
| 26 | */ |
| 27 | public async sendLoginSms(phone: string, code: string): Promise<boolean> { |
| 28 | const sendSmsRequest = new $Dysmsapi20170525.SendSmsRequest({ |
| 29 | phoneNumbers: phone, |
| 30 | signName: this.options.defaults.signName, |
| 31 | templateCode: this.options.defaults.templateCode, |
| 32 | templateParam: JSON.stringify({ code }), |
| 33 | }); |
| 34 | |
| 35 | const runtime = new $Util.RuntimeOptions({}); |
| 36 | |
| 37 | try { |
| 38 | const result = await this.client.sendSmsWithOptions( |
| 39 | sendSmsRequest, |
| 40 | runtime, |
| 41 | ); |
| 42 | |
| 43 | if (result.body.code === 'isv.BUSINESS_LIMIT_CONTROL') { |
| 44 | console.log('发送短信失败,请稍后再试'); |
| 45 | return false; |
| 46 | } |
| 47 | |
| 48 | return true; |
| 49 | } catch (error: any) { |
| 50 | console.log('==== sendLoginSms ====', error); |
| 51 | return false; |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 |