Home > Net >  Passing variable in body parameters with guzzle or curl
Passing variable in body parameters with guzzle or curl

Time:07-07

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();

CodePudding user response:

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.

  • Related