API 需要一个编码的 API 密钥,我如何使用 curl 发送它


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

>我正在使用一个 api,它需要在 curl 调用的基本身份验证中发送 api 密钥。

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

我的回答是:

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

我知道密钥本身是正确的,它在不使用 php 发送 curl 请求时有效。

我认为 USERPWD 不是使用的正确 curlopt,哪一个是?

从文档中:

Base64 编码字符串,由组合的用户名:密码生成序列。

在我们的例子中,API密钥设置为用户名,密码设置为空字符串。

例如,如果 API 密钥等于 N8KzwcqVUxAI1RoPi5jyFJPkPlkDl9vF,

应对以下字符串执行 Base64 编码:N8KzwcqVUxAI1RoPi5jyFJPkPlkDl9vF:

在这种情况下,内容发送到授权标头为Basic TjhLendjcVZVeEFJMVJvUGk1anlGSlBrUGxrRGw5dkY6.

接口文档

USERPWD 是正确的,但您可能需要发送

$apiuser:$apikey

看起来现在,您只是在发送密钥。

我调整了发送标头的方式:

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

并添加

     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);