Untitled

mail@pastecode.io avatar
unknown
typescript
2 years ago
1.5 kB
3
Indexable
Never
import {Axios} from 'axios';

export class Dialog360 {
  private axios: Axios;
  constructor(private apiKey: string) {
    this.axios = new Axios({
      baseURL: 'https://waba.360dialog.io/v1',
      headers: {
        'D360-API-KEY': this.apiKey,
        'Content-Type': 'application/json',
      },
    });
  }

  private async retrieveWhatsappId(phone: string) {
    const body = {
      blocking: 'wait',
      contacts: [phone],
      force_check: true,
    };
    const {data} = await this.axios.post('/contacts', JSON.stringify(body));
    const parsed = JSON.parse(data);
    console.log(parsed);

    if (!parsed.contacts) return null;
    return parsed.contacts[0].wa_id;
  }

  public async sendTemplateMessage(phone: string) {
    const body = {
      to: phone,
      type: 'template',
      template: {
        namespace: '2c617ca1_6c79_4041_9a2b_6575f0e83391',
        language: {
          policy: 'deterministic',
          code: 'pt_br',
        },
        name: 'testeaf',
      },
    };
    const {data} = await this.axios.post('/messages', JSON.stringify(body));
    console.log(data);
  }

  public async sendTextMessage(phone: string, text: string) {
    const whatsappId = await this.retrieveWhatsappId(phone);
    if (!whatsappId) throw new Error('Invalid contact');
    const body = {
      recipient_type: 'individual',
      to: whatsappId,
      type: 'text',
      text: {
        body: text,
      },
    };
    const {data} = await this.axios.post('/messages', JSON.stringify(body));
    console.log(data);
  }
}