6

I am trying to connect twilio api using Curl php. The following is the code from Twilio api

I used an online tool php to curl but it didn't converted the code with data encode url.

The question which was marked as duplicate has no information about --data-urlencode. I have tried the solution mentioned there but still it is not working the way it is suppose to.

curl -X POST https://api.twilio.com/2010-04-01/Accounts/ACCOUNTID/Messages.json \
--data-urlencode "From=+122344444" \
--data-urlencode "Body=Body" \
--data-urlencode "To=+13101111111" \
-u ACCOUNTID:PASSWORD

PHP Code:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, 'ACCOUNTID' . ':' . 'PASSWORD');

The expected result is to get message but I am getting

{"code": 21603, "message": "A 'From' phone number is required.", "more_info": "https://www.twilio.com/docs/errors/21603", "status": 400} 

The reason I am getting this is I am not sure how to pass from, body and to in curl php.

chmod777
  • 73
  • 5

1 Answers1

12

What you're missing is

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));

where $payload is

$payload = [
    'From' => '+122344444',
    'To' => '+13101111111',
    'Body'   => 'This is the body...'
];


PHP Code:
$payload = [
    'From' => '+122344444',
    'To' => '+13101111111',
    'Body'   => 'This is the body...'
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERPWD, 'ACCOUNTID' . ':' . 'PASSWORD');
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
Alex Baban
  • 9,954
  • 3
  • 23
  • 36