簡體   English   中英

在 PHP 中做一個 REST PUT

[英]doing a REST PUT in PHP

我希望我的問題會被理解,我的英語不太好。

我幾乎是 PHP 新手,我剛剛發現了 REST API:我正在嘗試從我的 PHP 腳本中使用 REST API。 可以在此處找到 API 的文檔

我的最終目標是從這個網絡服務中獲取單個產品並通過添加批發價格數組來更新它。

我已經設法使用 file_get_contents() 執行 GET 請求,以獲取我想要更新的產品 ID。 現在我有這樣的 id 但無法理解如何執行 PUT 請求:據我所知,在 PHP 中主要有兩種方法來進行 REST 調用:一種使用 file_get_contents,另一種使用 cURL。

由於我將 file_get_contents 用於我的 GET 請求,因此我繼續使用這種方法,但我的代碼:

$wholesalePrices = json_encode($wholesalePrices);
$dataRAW = array(
                  "wholesalePrices" => $wholesalePrices 
                );
$dataToPut = http_build_query($dataRAW);
$context = [
              'http' => [
                          'method' => 'PUT',
                          'header' =>  "Authorization: apikeystring\r\n" . "Content-Length: " . strlen($dataToPut) . "\r\n" . "Content-Type: application/json\r\n",
                          'content' => $dataToPut
                        ]                             
           ];
$context = stream_context_create($context);
$url = "https://app.ecwid.com/api/v3/xxxxxxx/products/".urlencode($productId)."?token=".urlencode(myToken);   
$result = file_get_contents ($url, false, $context);

返回一個 PHP 警告:

警告:file_get_contents( https://app.ecwid.com/api/v3/xxxxxxxxx/products/xxxxxxxxx?token=xxxxxxxxxxx ): 無法打開流:HTTP 請求失敗! HTTP/1.1 400 錯誤的 JSON 格式:JSONObject 文本必須以 '{' at 1 [character 2 line 1] in upload.php on line 95

var_dumping $wholesalePrices 在 json_encode() 結果之后

字符串 '[{"quantity":1,"price":0},{"quantity":5,"price":6},{"quantity":25,"price":12},{"quantity": 100,"price":25}]' (長度=106)

我錯在哪里?


好的,我嘗試使用 RamRaider 方法,現在我的代碼是這樣的

$data = json_encode(array('wholesalePrices' => $wholesalePrices)/*, JSON_FORCE_OBJECT*/);
          $dataRAW = array(
                            "wholesalePrices" => $wholesalePrices 
                     );      
          $dataToPut = $dataRAW;
          $dataToPut = http_build_query($dataRAW);
$context = array('http' => array('method'    =>  'PUT',
                           'header'    =>  "Authorization: apikeystring\r\nContent-Length: ".strlen($data)."\r\nContent-Type: application/json\r\n",
                           'content'   =>  $data));

          $context = stream_context_create($context);
          $url = "https://app.ecwid.com/api/v3/".urlencode(MY_STORE_ID)."/products/".urlencode($productId)."?token=".urlencode(MY_TOKEN);   
$result = file_get_contents ($url, false, $context);

但是我獲取一個HTTP request failed! HTTP/1.1 400 Field Product.wholesalePrices should be an array HTTP request failed! HTTP/1.1 400 Field Product.wholesalePrices should be an array消息。 如果我評論, JSON_FORCE_OBJECT ,則 HTTP 消息變為409 Conflict並且它引用$result = file_get_contents ($url, false, $context); 所以也許我在正確的軌道上,但是我該如何解決此類錯誤?


好的,做了一些修改:現在 - 在 json_encode() 之后 - 我的 dataToPut(我把它放在 HTTP 請求中的“內容”中) var_dumps 如下(WPPair 是我專門創建的一個類來重現所需的格式):

object(stdClass)[3]
  public 'wholesalePrices' => 
    array (size=3)
      1 => 
        object(WPpair)[5]
          public 'quantity' => int 5
          public 'price' => int 6
      2 => 
        object(WPpair)[4]
          public 'quantity' => int 25
          public 'price' => int 12
      3 => 
        object(WPpair)[6]
          public 'quantity' => int 100
          public 'price' => int 25

所以我認為它必須適合 api。 但我仍然收到一個 HTTP 請求失敗! HTTP/1.1 400 錯誤請求


好的,最后我設法為我的 JSON 形成了一個(也許)正確的結構,尤其是 Postman 使用 HTTP 驗證我的 dataToPut

200 正常

我的測試記錄結果更新了。 這是 json_encode() 之后 dataToPut 上的 print_r() 輸出:

字符串 '{"id":56782231,"wholesalePrices":[{"quantity":5,"price":5.64},{"quantity":25,"price":5.28},{"quantity":100,"價格":4.5}]}' (長度=121)

但是,如果我嘗試從我的 PHP 頁面發送相同的 JSON,我仍然會收到

無法打開流:HTTP 請求失敗!

事實上,我的記錄仍然沒有更新。

這是我的代碼:

$dataToPut = $dataRAW;
$dataRAW = http_build_query($dataRAW);
$context = [
            'http' => [
                       'method' => 'PUT',
                       'header' =>  "Authorization: apikeystring\r\n" . "Content-Length: ".sizeof($dataToPut)."\r\n" . "Content-Type: application/json\r\n",
                       'content' => $dataToPut
                      ]                             
           ];
$context = stream_context_create($context);
$url = "https://app.ecwid.com/api/v3/xxxxxxx/products/".urlencode($productId)."?token=".urlencode(myToken);
$dataToPut = json_encode($dataToPut);
$result = file_get_contents($url, false, $context); 

這次我錯在哪里?


通過使用 cURL 而不是 file_get_contents 重寫我的代碼以連接到 API 后,我設法讓它工作。 現在 API 調用部分如下所示:

      $dataToPut = $dataRAW;
      $dataRAW = http_build_query($dataRAW);
      $context = [
                    'http' => [
                                'method' => 'PUT',
                                'header' =>  "Authorization: apikeystring\r\n" . "Content-Length: ".sizeof($dataToPut)."\r\n" . "Content-Type: application/json\r\n",
                                'content' => $dataToPut
                              ]                             
                 ];
      $context = stream_context_create($context);


      $url = "https://app.ecwid.com/api/v3/xxxxxxx/products/".urlencode($productId)."?token=".urlencode($myToken);
      $curl = curl_init();
      curl_setopt($curl, CURLOPT_URL, $url);
      curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
      curl_setopt($curl, CURLOPT_HTTPHEADER, array('Host: app.ecwid.com','Content-Type: application/json;charset=utf-8','Cache-Control: no-cache'));
      curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($curl, CURLOPT_POSTFIELDS, $dataToPut);

      // Make the REST call, returning the result
      $response = curl_exec($curl);
      echo ($response."<br/>");
      if (!$response) {
        echo("Connection Failure: ".curl_error($curl));
        die();
      }
      curl_close($curl);

如果沒有看到他們 api 的文檔,我可能會讓你誤入歧途,但錯誤消息確實表明他們的 api 需要 json 數據,而你對數據進行編碼,然后添加到一個似乎以某種方式回到前面的數組。

$data = json_encode( array( 'wholesalePrices' => $wholesalePrices  ), JSON_FORCE_OBJECT );

/* Perhaps this also is not required */
#$data = http_build_query( $data );

$context = array(
    'http' => array(
            'method'    =>  'PUT',
            'header'    =>  "Authorization: apikeystring\r\nContent-Length: " . strlen( $data ) . "\r\nContent-Type: application/json\r\n",
            'content'   =>  $data
        )                             
    );

$context = stream_context_create( $context );
$url = "https://app.ecwid.com/api/v3/7560546/products/".urlencode( $productId )."?token=".urlencode( myToken );   
$result = file_get_contents( $url, false, $context );

快速瀏覽了 api 文檔后,我發現了以下內容:

PUT https://app.ecwid.com/api/v3/ {storeId}/products/{productId}?token={token}

請求正文

具有以下字段的“產品”類型的 JSON 對象:

wholesalePrices -> Array<WholesalePrice>
 described as: "Sorted array of wholesale price tiers (quantity limit and price pairs)"

更新產品的給定示例請求是:

PUT /api/v3/4870020/products/39766764?token=123456789abcd HTTP/1.1
Host: app.ecwid.com
Content-Type: application/json;charset=utf-8
Cache-Control: no-cache

{
  "compareToPrice": 24.99,
  "categoryIds": [
    9691094
  ]
}

所以使用測試數據

        $wholesalePrices=array(
            array('quantity'=>10,'price'=>1000),
            array('quantity'=>2,'price'=>43),
            array('quantity'=>43,'price'=>34),
            array('quantity'=>7,'price'=>5),
            array('quantity'=>9,'price'=>63),
        );
        $data = json_encode( array( 'wholesalePrices' => $wholesalePrices  ) );
        echo '<pre>',$data,'</pre>';

提供以下格式的數據:

{
    "wholesalePrices":[
        {"quantity":10,"price":1000},
        {"quantity":2,"price":43},
        {"quantity":43,"price":34},
        {"quantity":7,"price":5},
        {"quantity":9,"price":63}
    ]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM