File size: 2,419 Bytes
db3d93b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
70
71
72
73
74
75
76
77
78
79
80
81
import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { SmsConfig } from './sms.config';

interface AuthkeyResponse {
  LogID?: string;
  Message?: string;
  Status?: string;
  Details?: string;
}

@Injectable()
export class SmsService {
  private readonly logger = new Logger(SmsService.name);
  private readonly config: SmsConfig;

  constructor(private configService: ConfigService) {
    this.config = new SmsConfig(configService);
  }

  async sendOtpSms(phone: string, otp: string): Promise<void> {
    try {
      this.logger.log(`πŸ“± Attempting to send SMS OTP to: ${phone}`);
      this.logger.log(`πŸ“± OTP Code: ${otp}`);

      // Create form data
      const formData = new FormData();
      formData.append('authkey', this.config.apiKey);
      formData.append('mobile', phone);
      formData.append('country_code', '91'); // Default to India
      formData.append('sid', '30718'); // Default SID for OTP
      formData.append('otp', otp);
      formData.append('company', this.config.companyName);

      this.logger.log('πŸ“± Request payload:', {
        authkey: this.config.apiKey.substring(0, 8) + '...',
        mobile: phone,
        country_code: '91',
        sid: '30718',
        otp: otp,
        company: this.config.companyName,
      });

      const response = await fetch(
        'https://console.authkey.io/restapi/request.php',
        {
          method: 'POST',
          body: formData,
        },
      );

      const responseText = await response.text();
      this.logger.log(`πŸ“± Raw Response: ${responseText}`);

      let result: AuthkeyResponse;
      try {
        result = JSON.parse(responseText);
      } catch (parseError) {
        this.logger.error('πŸ“± Failed to parse response as JSON:', parseError);
        throw new Error(`Invalid response from SMS service: ${responseText}`);
      }

      this.logger.log('πŸ“± Parsed Response:', result);

      if (!response.ok || !result.LogID) {
        this.logger.error('πŸ“± Failed to send OTP SMS:', result);
        throw new Error(
          result.Details || result.Message || 'Failed to send OTP SMS',
        );
      }

      this.logger.log(
        `πŸ“± βœ… OTP SMS sent successfully to ${phone}. LogID: ${result.LogID}`,
      );
    } catch (error) {
      this.logger.error('πŸ“± ❌ Error sending OTP SMS:', error);
      throw error;
    }
  }
}