Pavan Kakathkar Pavan Kakathkar - 13 days ago 5
JSON Question

PHP How do I run this cURL in PHP

curl -X POST --header 'Content-Type: application/x-www-form-urlencoded' --header 'Accept: text/plain' --header 'apikey: Your API key goes here' -d 'context= "your url encoded contextobj goes here"&message=Hello%20there' 'https://api.gupshup.io/sm/api/bot/demobot/msg'


I tried using other answers but couldnt get output.

Here i what I did:

$msg=urlencode("Hello world");
$headers = ['Content-Type:application/x-www-form-urlencoded','Accept:text/plain','apikey:xxxxxxxxxxxxxxxxxxxxxxxxxxx',];
$context=http_build_query(json_decode('{"botname":"demobot2","channeltype":telegram","contextid":"xxxxxx","contexttype":"p2p"}'));

$ch = curl_init("https://api.gupshup.io/sm/api/bot/botname/msg");
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_POST, 1);
$data = 'context='.$context.'&message=.$msg.';
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result =curl_exec($ch);
echo $result;

Answer

Here is the code generated by the tool PostMan that I took your CURL comment then made a request and clicked generate code

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.gupshup.io/sm/api/bot/demobot/msg",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "context=your%20url%20encoded%20contextobj%20goes%20here&message=Hello%20There",
  CURLOPT_HTTPHEADER => array(
    "accept: text/plain",
    "apikey: Your api key goes here",
    "cache-control: no-cache",
    "content-type: application/x-www-form-urlencoded",
    "postman-token: 7d8384ea-359d-f845-bb72-6063a1aba50c"
  ),    
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
?>
Comments