Skip to content

Node.js एकीकरण

तपाईंको Node.js अनुप्रयोगमा SMSBAT API एकीकृत गर्ने नेटिभ fetch API (Node.js 18+) वा लोकप्रिय axios पुस्तकालय प्रयोग गरेर गर्न सकिन्छ।

Axios प्रयोग गर्दै (सिफारिस गरिएको)

पहिले, npm वा यार्न मार्फत Axios स्थापना गर्नुहोस्:

npm install axios
# or
yarn add axios

त्यसपछि, सन्देश पठाउन निम्न कोड प्रयोग गर्नुहोस्:

const axios = require('axios');

async function sendMessage() {
  const url = 'https://api.smsbat.com/bat/messagelist';
  const apiKey = 'YOUR_API_KEY_HERE';

  const payload = {
    messages: [
      {
        from: 'ALPHANAME',
        to: '380501234567',
        text: 'Hello from Node.js and Axios!',
        type: 'sms'
      }
    ]
  };

  try {
    const response = await axios.post(url, payload, {
      headers: {
        'Content-Type': 'application/json',
        'X-Authorization-Key': apiKey
      },
      timeout: 10000
    });

    console.log(`Status Code: ${response.status}`);
    console.log('Response:', response.data);
  } catch (error) {
    console.error('An error occurred:', error.message);
    if (error.response) {
      console.error('Error Details:', error.response.data);
    }
  }
}

sendMessage();

नेटिभ फेच प्रयोग गर्दै (Node.js 18+)

यदि तपाइँ Node.js 18 वा नयाँ प्रयोग गर्दै हुनुहुन्छ भने, तपाइँ बिल्ट-इन ग्लोबल fetch API प्रयोग गर्न सक्नुहुन्छ:

async function sendMessageWithFetch() {
  const url = 'https://api.smsbat.com/bat/messagelist';
  const apiKey = 'YOUR_API_KEY_HERE';

  const payload = {
    messages: [
      {
        from: 'ALPHANAME',
        to: '380501234567',
        text: 'Hello from Node.js Native Fetch!',
        type: 'sms'
      }
    ]
  };

  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Authorization-Key': apiKey
      },
      body: JSON.stringify(payload)
    });

    const data = await response.json();

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}, details: ${JSON.stringify(data)}`);
    }

    console.log(`Status Code: ${response.status}`);
    console.log('Response:', data);
  } catch (error) {
    console.error('An error occurred:', error.message);
  }
}

sendMessageWithFetch();