All files / src/services/sms index.ts

0% Statements 0/29
0% Branches 0/6
0% Functions 0/6
0% Lines 0/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                               
import ovh = require('ovh');
import fetch from 'node-fetch';
import { smsConfig } from '../../config/sms';
 
export class SmsService {
  static generateCode(): number {
    return Math.floor(100000 + Math.random() * 900000);
  }
 
  // OVH Service
  static sendSmsWithOvh(phoneNumber: string, message: string): Promise<{ success: boolean; error?: string }> {
    return new Promise((resolve, reject) => {
      const ovhClient = ovh({
        appKey: smsConfig.OVH_APP_KEY!,
        appSecret: smsConfig.OVH_APP_SECRET!,
        consumerKey: smsConfig.OVH_CONSUMER_KEY!
      });
 
      ovhClient.request('POST', `/sms/${smsConfig.OVH_SMS_SERVICE_NAME}/jobs`, {
        message: message,
        receivers: [phoneNumber],
        senderForResponse: false,
        sender: 'not.IT Fact',
        noStopClause: true
      }, (error: any, result: any) => {
        if (error) {
          console.error('Erreur OVH SMS:', error);
          resolve({ success: false, error: 'Échec de l\'envoi du SMS via OVH' });
        } else {
          resolve({ success: true });
        }
      });
    });
  }
 
  // SMS Factor Service
  static async sendSmsWithSmsFactor(phoneNumber: string, message: string): Promise<{ success: boolean; error?: string }> {
    try {
      const url = new URL('https://api.smsfactor.com/send/simulate');
      url.searchParams.append('to', phoneNumber);
      url.searchParams.append('text', message);
      url.searchParams.append('sender', 'LeCoffre');
      url.searchParams.append('token', smsConfig.SMS_FACTOR_TOKEN!);
 
      const response = await fetch(url.toString());
 
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
 
      return { success: true };
    } catch (error) {
      console.error('Erreur SMS Factor:', error);
      return { success: false, error: 'Échec de l\'envoi du SMS via SMS Factor' };
    }
  }
 
  // Main method
  static async sendSms(phoneNumber: string, message: string): Promise<{ success: boolean; error?: string }> {
    // Try first with OVH
    const ovhResult = await this.sendSmsWithOvh(phoneNumber, message);
 
    if (ovhResult.success) {
      return ovhResult;
    }
 
    // If OVH fails, try with SMS Factor
    console.log('OVH SMS failed, trying SMS Factor...');
    return await this.sendSmsWithSmsFactor(phoneNumber, message);
  }
}