使用cURL返回的值作为Authorization标头进行后续调用

问题描述 投票:0回答:1

我正在使用cURL调用api并且我得到一个成功的调用,但是api要求我使用成功的调用来进行后续调用,具体来说:使用返回的值将后续调用作为Authorization标头。

我不确定究竟要尝试什么。我正在页面正文中得到正确的答案,只需通过curl_exec($ ch);但我不知道该在哪里继续。

<?php

//Set Variables
$username = 'my_username';
$password = 'my_password';
$showcode = 'my_showcode';

//Set url variable with showcode as a query string
$url = "https://api.mysstaging.com/mysRest/v2/Authorize/?showCode=$showcode";

// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url );

//Set un/pw for basic auth
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");

// grab URL and pass it to the browser
curl_exec($ch);

//Expect to store and use variable but not sure how
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  'Authorization: ' . mysGUID,
));


// close cURL resource, and free up system resources
curl_close($ch);
?>

从curl_exec($ ch),我在myskUID的主体中得到一个响应,这是我认为我应该/可以将它作为变量传递但我不确定如何将响应存储为php中的变量然后使用它进行后续通话?我很抱歉我仍然非常环保API,但希望我走在正确的轨道上?

php-curl
1个回答
0
投票

我能够解决这个问题。如果其他人被卡住,我采取的方法是设置CURLOPT_RETURNTRANSFER,以便我可以利用这些值。然后我为返回的键和值创建了一个变量(我称之为GUID)。然后,我使用此变量将输出转换为数组,然后允许我从返回的GUID中获取值,然后将其存储在我可用于后续调用的变量中。

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// create variable for authorization output, this gives us the GUID we need.
$authOutput = curl_exec($ch);

// Convert JSON string to Array to pull the GUID value only
$outputArray = json_decode($authOutput, true);

//create variable for myResult variable
$myResult= $outputArray[0]["myResult"];

echo "My Result = $myResult";

// close cURL resource, and free up system resources
curl_close($ch);

© www.soinside.com 2019 - 2024. All rights reserved.