使用curl通过API发布Json,没有结果

时间:2015-06-01 13:49:40

标签: php api post curl

我对此很新,所以希望它不是我想念的傻事。我正在尝试为使用API​​的人创建订单。

我已经搜索了几个小时如何在stackoverflow上执行此操作,并且所有帖子都提供了很好的帮助。但是现在我碰到了一堵砖墙。这段代码在访问PHP页面时似乎没有出现任何错误,也没有将该项目从库存中移除,就像它的意图一样。

我错过了一些非常简单的东西,还有办法检查它是否有效吗?

<?php

$today = date("D M j Y G:i:s T");
$data = array(
	"order" => [
	  "order_number" => "",
          "company_id" => 690094,
          "billing_address_id" => 1018327, 
          "shipping_address_id" => 1018327, 
          "stock_location_id" => 16377,
          "ship_at" => $today,
          "issued_at" => $today, 
          "tax_type" => "exclusive", 
          "payment_status" => "unpaid",
          "fulfillment_status" => "shipped",
          "email" => null,
          "reference_number" => 7784,
          "status" => "fulfilled",
          "order_line_items" => [
              "quantity" => 1, "discount" => null, "price" => 1, 
              "tax_rate_override" => null, "freeform" => false,
              "variant_id" => 6983077
          ],
        ],
);

$url ="https://api.tradegecko.com/orders/";
$str_data = json_encode($data);

function sendPostData($url, $str_data){
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',  
    'Accept: application/json',                                                                                                                               
	'http' => array(
        'header'  => "Authorization: Bearer 872ed5e72dfc7e4e0adaa7c663cab7d81415078fdbe4f486d085b718c93b3eb3")
    )                                                                       
);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS,$str_data);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
  $result = curl_exec($ch);
  curl_close($ch);  // Seems like good practice
  return $result;
}

echo sendPostData($url, $str_data);
?>

1 个答案:

答案 0 :(得分:0)

未以正确的方式设置Authorization标头。它应该在:

中完成
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',  
    'Accept: application/json',                                                                                                                               
    'Authorization: Bearer 872ed5e72dfc7e4e0adaa7c663cab7d81415078fdbe4f486d085b718c93b3eb3')
);

出于调试目的,添加:

会很有帮助
curl_setopt($ch, CURLOPT_VERBOSE, 1);

最后,您应该为此服务创建一个新的访问令牌,因为您的服务现已公开。