使用授权标头向API端点发送PHP请求

时间:2016-12-22 07:35:53

标签: php

我想问你如何使用带有授权标头的API请求API。

API端点示例是

Quotation Service : ­ POST https://api.website.com/v4/quotation

Content­type: application/json; charset=utf­8
Accept: application/json
Authorization: hmac $id:$milliSeconds:$signature
{
"serviceType": "CARD",
"specialRequests": [
"ROUNDTRIP"
]}

正如您所提到的,他们使用hmac作为标头中的授权,请求参数是serviceType,specialRequest

我尝试使用PHPCurl提出请求,但我并不擅长。请给我并建议如何在这个API中使用Curl。

编辑:

<?php

    $customerId = "585a-SAMPLE-980dfe0097"; //by provider

    $privKey = "MC4CAQACBQDSk4ghAgMB---SAMPLE---QIDAOPFAgMAk7QIDAMYq"; //by provider

    $requestTime = (int)(microtime(true) * 1000);

    $signature = hash_hmac('sha256', $requestTime, $privKey);

    $headers = array(
        "Authorization: hmac $customerId:$requestTime:$signature"
    );

    $params = array(
        'serviceType' => 'CARD',
        'specialRequests' => array('ROUNDTRIP')
    );

    $curl = curl_init();

    curl_setopt_array($curl, array(
      CURLOPT_URL => "https://api.samplesite.com/v1/quotations",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_HTTPHEADER => $headers,
    ));

    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
      echo "cURL Error #:" . $err;
    } else {
      echo $response;
    }

此致

1 个答案:

答案 0 :(得分:0)

嗯......也许是这样的:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.website.com/v4/quotation');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, true);

/* if you want to use SSL certificate, otherwise delete this */
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_CAPATH , '/path/to/certificate');

$auth = hash_hmac('sha1', $id.':'.$milisecond.':'.$signature, <ENCRYPTION KEY>, true);

$headers = array(
    'Authorization: '.$auth
);

$params = array(
    'serviceType' => 'CARD',
    'specialRequests' => array('ROUNDTRIP')
);

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);