Passing variable in body parameters with guzzle or curl

Issue

I am trying to pass a variable in body parameters. But it’s not working . Please help .

I have tried $otp and {$otp} but api says invalid . How can I pass variable correctly in body parameters .

require_once('../vendor/autoload.php');

$phnno="9187698699";
$otp = rand ( 10000 , 99999 );
$client = new \GuzzleHttp\Client();


$response = $client->request('POST', 'https://live-server-5673.wati.io/api/v1/sendTemplateMessage?whatsappNumber='.$phnno, [
  'body' => '{"parameters":[{"name":"otpstring","value":$otp}],"broadcast_name":"brd_otp","template_name":"tn_otp"}',
  'headers' => [
    'Authorization' => 'Bearer wgqhjqbjhbvhxvjvajvdjhqjj187268731dvajhsvjsvajvjsvjasvj',
    'Content-Type' => 'text/json',
  ],
]);

echo $response->getBody();

Solution

You will need to use string concatenation via the concatenation operator .. Try changing the 'body' => line to:

'body' => '{"parameters":[{"name":"otpstring","value":' . $otp . '}],"broadcast_name":"brd_otp","template_name":"tn_otp"}',

PHP variables can only be parsed in strings specified with double quotes, you have this string within single quotes.

Answered By – Andrew

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published