0

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

bart2puck
  • 2,432
  • 3
  • 27
  • 53
  • Possible duplicate of [How do I make a request using HTTP basic authentication with PHP curl?](http://stackoverflow.com/questions/2140419/how-do-i-make-a-request-using-http-basic-authentication-with-php-curl) – dmgig Mar 11 '16 at 16:53
  • Can you add some details of where the API is telling you to put the key? – ryantxr Mar 11 '16 at 16:54
  • edited with some info from docs. – bart2puck Mar 11 '16 at 16:57

2 Answers2

0

USERPWD is correct, but you likely need to send

$apiuser:$apikey

looks like now, you are just sending the key.

dmgig
  • 4,400
  • 5
  • 36
  • 47
0

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);
bart2puck
  • 2,432
  • 3
  • 27
  • 53