简体   繁体   English

如何使用节点 https 请求发送 twilio 短信

[英]how to send twilio sms using node https request

I'm trying to send an sms without the twilio sdk by using the nodejs https module however the twilio post api keeps responding with this error "400, Bad Request", which means I'm probably not crafting the request the right way.我正在尝试使用 nodejs https 模块在没有 twilio sdk 的情况下发送短信,但是 twilio post api 不断响应此错误“400,错误请求”,这意味着我可能没有以正确的方式制作请求。 I've followed the nodejs docs https example, and also twilio's.我遵循了 nodejs docs https 示例,以及 twilio 的示例。 I've also tried making curl post request and it works perfectly fine.我也试过发出 curl 帖子请求,它工作得很好。 Where I'm I getting it wrong.我在哪里我弄错了。 Here's my code这是我的代码

// Send an SMS message via Twilio
helpers.sendTwilioSms = (phone, message, callback) => {
  // validate parameters
  phone =
    typeof phone == "string" && phone.trim().length == 10
      ? phone.trim().length
      : false;
  message =
    typeof message == "string" &&
    message.trim().length > 0 &&
    message.trim().length <= 1600
      ? message.trim()
      : false;

  if (phone && message) {
    // Configure the request payload
    const payload = {
      from: config.twilio.fromPhone,
      to: `+234${phone}`,
      body: message
    };

// stringify payload using querystring module instead of JSON.stringify because the reqeust we'll be sending is not of application/json but 'application/x-www-form-urlencoded' form content-type as specified by Twilio
const stringPayload = querystring.stringify(payload);

// Configure the request details
var requestDetails = {
  hostname: "api.twilio.com",
  method: "POST",
  path: `/2010-04-01/Accounts/${config.twilio.accountSid}/Messages.json`,
  auth: `${config.twilio.accountSid}:${config.twilio.authToken}`,
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    "Content-Length": Buffer.byteLength(stringPayload)
  }
};

// Instantiate the request
const req = https.request(requestDetails, res => {
  // grab the status of the sent request
  const status = res.statusCode;
  console.log([
    `(sendTwilioSms) making https post request`,
    `(sendTwilioSms) response completed: ${res.complete}`,
    `(sendTwilioSms) response statusCode: ${res.statusCode}`,
    { "(sendTwilioSms) response headers:": res.headers },
    { "(sendTwilioSms) response body:": res.body }
  ]);
  // callback successfully if the request went through
  if (status == 200 || status == 201) {
    callback(false);
  } else {
    callback(500, {
      Error: `Status code returned was ${status}: ${res.statusMessage}`
    });
  }
});

    // Alert the user as to a change in their check status
workers.alertUserToStatusChange = newCheckData => {
  const message = `Alert: Your check for ${newCheckData.method.toUpperCase()} ${
    newCheckData.protocol
  }://${newCheckData.url} is currently ${newCheckData.state}`;
  helpers.sendTwilioSms(newCheckData.userPhone, message, err => {
    if (!err) {
      console.log(
        "Success: User was aterted to a status change in their check, via sms: ",
        msg
      );
    } else {
      console.log(
        "Error: Could not send sms alert to user who add a state change in their check"
      );
    }
  });

Here's the Response:这是回应:

    [
  '(workers) making check request',
  '(workers) check response completed: false',
  '(workers) check response statusCode: 200'
]
logging to file succeeded
Check outcome has not changed no alert needed
[
  '(sendTwilioSms) making https post request',
  '(sendTwilioSms) response completed: false',
  '(sendTwilioSms) response statusCode: 400',
  {
    '(sendTwilioSms) response headers:': {
      date: 'Fri, 17 Jan 2020 09:49:39 GMT',
      'content-type': 'application/json',
      'content-length': '127',
      connection: 'close',
      'twilio-request-id': 'RQ7ee0b52d100c4ac997222f235e760fb7',
      'twilio-request-duration': '0.025',
      'access-control-allow-origin': '*',
      'access-control-allow-headers': 'Accept, Authorization, Content-Type, If-Match, '
+
        'If-Modified-Since, If-None-Match, ' +
        'If-Unmodified-Since',
      'access-control-allow-methods': 'GET, POST, DELETE, OPTIONS',
      'access-control-expose-headers': 'ETag',
      'access-control-allow-credentials': 'true',
      'x-powered-by': 'AT-5000',
      'x-shenanigans': 'none',
      'x-home-region': 'us1',
      'x-api-domain': 'api.twilio.com',
      'strict-transport-security': 'max-age=31536000'
    }
  },
  { '(sendTwilioSms) response body:': undefined }
]
Error: Could not send sms alert to user who add a state change in their check

Try with something like this:尝试这样的事情:

// authentication
var authenticationHeader = "Basic "
    + new Buffer(config.twilio.accountSid
        + ":"
        + config.twilio.authToken).toString("base64");

// Configure the request details
var requestDetails = {
    host: "api.twilio.com",
    port: 443,
    method: "POST",
    path: `/2010-04-01/Accounts/${config.twilio.accountSid}/Messages.json`,
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Content-Length": Buffer.byteLength(stringPayload),
        "Authorization": authenticationHeader
    }
};

and this:和这个:

// Instantiate the request
const req = https.request(requestDetails, res => {
    // grab the status of the sent request
    const status = res.statusCode;

    res.setEncoding('utf8');
    res.on('data', (chunk) => body += chunk);
    res.on('end', () => {
        console.log('Successfully processed HTTPS response');
        // If we know it's JSON, parse it
        if (res.headers['content-type'] === 'application/json') {
            body = JSON.parse(body);
        }
        callback(null, body);
    });

    // callback successfully if the request went through
    if (status == 200 || status == 201) {
        callback(false);
    } else {
        callback(500, {
            Error: `Status code returned was ${status}: ${res.statusMessage}`
        });
    }
});

I hope it works, I have not tested.我希望它有效,我还没有测试过。 If it doesn't let me know and I'll try on my side and post a complete tested code.如果它没有让我知道,我会尝试站在我这边并发布完整的测试代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM