简体   繁体   中英

API requires a encoded API key, how do i send this with curl?

I am working with an api that requires an api key to be sent in basic auth of a curl call.

    $json = "somedata";
    $url = "http.server.com";
    $key = "someKey";

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10 );
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERPWD, $key);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
    curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/2.0");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $output = curl_exec($ch);
    curl_close($ch);

My response is:

    "Server error","data":{"details":"Invalid API key. 

I know the key itself is correct, It works when sending a curl request not using php.

I assume USERPWD is not the correct curlopt to use, which one is?

From docs:

A Base64 encoded string, generated from the combined username:password sequence.

In our case, the API key is set as username, and password is set as an empty string.

For example, if the API Key is equal toN8KzwcqVUxAI1RoPi5jyFJPkPlkDl9vF,

the Base64 encoding should be performed on the following string: N8KzwcqVUxAI1RoPi5jyFJPkPlkDl9vF:

In this case, the content sent to the authorization header is Basic TjhLendjcVZVeEFJMVJvUGk1anlGSlBrUGxrRGw5dkY6.

API Docs

USERPWD is correct, but you likely need to send

$apiuser:$apikey

looks like now, you are just sending the key.

I adjusted how i sent the headers:

  $headers = array( 
        "POST ".$url." HTTP/1.0", 
        "Content-type: text/xml;charset=\"utf-8\"", 
        "Accept: text/xml", 
        "Cache-Control: no-cache", 
        "Pragma: no-cache", 
        "SOAPAction: \"run\"", 
        "Content-length: ".strlen($xml_data), 
        "Authorization: Basic " . $key 
    ); 

and added

     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM