Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twilio rest api, sending sms [closed]

Tags:

php

twilio

I am trying to (and have to) use the twilio rest api to send sms and not using the helper php library. Below is my code: The problem i am facing is, its giving me the error that 91xxxxxxxxxx is not a valid phone number. But I am passing the phone number to rest api with '+' prefixed.

I am using the trial account and the number is verified with twilio, and tested using the helper library.

<?php
$url = "https://api.twilio.com/2010-04-01/Accounts/MYID/SMS/Messages.json";
$from = "MY_TWILIO_NUMBER without + prefix";
$to = "+91xxxxxxxxxx"; // twilio trial verified number
$body = "using twilio rest api";
$id = "MY_ID";
$token = "MY_TOKEN";
$data = array (
        'From' => $from,
        'To' => $to,
        'Body' => $body,

    );
$post = '';
foreach ($data as $parameter => $value)
{
    $post .= "&$parameter=$value";
}
$x = curl_init($url );
curl_setopt($x, CURLOPT_POST, true);
curl_setopt($x, CURLOPT_RETURNTRANSFER, true);
curl_setopt($x, CURLOPT_USERPWD, "$id:$token");
curl_setopt($x, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($x, CURLOPT_POSTFIELDS, $post);
$y = curl_exec($x);
var_dump($y);
curl_close($x);
?>

The complete dump of curl request

string(157) "{"status":400,"message":"The 'To' number  91xxxxxxxxxx is not a valid phone number.","code":21211,"more_info":"http://www.twilio.com/docs/errors/21211"}"

It does says wrong number (missing '+') but i am not getting where.

like image 262
amitchhajer Avatar asked Dec 04 '25 12:12

amitchhajer


1 Answers

Well was missing something, so finally solved.

here's the code

<?php
$url = "https://api.twilio.com/2010-04-01/Accounts/MYID/SMS/Messages.json";
$from = "MY_TWILIO_NUMBER without + prefix";
$to = "+91xxxxxxxxxx"; // twilio trial verified number
$body = "using twilio rest api";
$id = "MY_ID";
$token = "MY_TOKEN";
$data = array (
        'From' => $from,
        'To' => $to,
        'Body' => $body,

    );
$post = http_build_query($data);
$x = curl_init($url );
curl_setopt($x, CURLOPT_POST, true);
curl_setopt($x, CURLOPT_RETURNTRANSFER, true);
curl_setopt($x, CURLOPT_USERPWD, "$id:$token");
curl_setopt($x, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($x, CURLOPT_POSTFIELDS, $post);
var_dump($post);
$y = curl_exec($x);
var_dump($y);
curl_close($x);
?>
like image 116
amitchhajer Avatar answered Dec 06 '25 05:12

amitchhajer