2017-08-29 37 views
-3

我完全不熟悉PHP中的cURL請求。cURL PHP新手需要一隻手

我有一個API給了我下面的信息,並希望我通過cURL發送POST請求。我已經嘗試了一些基本的cURL示例,但不知道應該如何發送附加數據。

API文檔包含以下內容:

curl https://api.23andme.com/token/ 
     -d client_id=xxx \ 
     -d client_secret=yyy \ 
     -d grant_type=authorization_code \ 
     -d code=zzz \ 
     -d "redirect_uri=https://localhost:5000/receive_code/" 
     -d "scope=basic%20rs3094315" 

這裏是我的示例代碼:

$data = array(
     "client_id" => $client_id, 
     "client_secret" => $client_secret, 
     "grant_type" => "authorization_code", 
     "code" => $code, 
     "redirect_uri" => "http://localhost/23andme/", 
     "scope" => "basic" 
     ); 



$ch = curl_init($url); 
    curl_setopt($ch, CURLOPT_POST, true); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, $data); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 


    $response = curl_exec($ch); //Uncomment to make it live again 

    if (!$response) 
    { 
     return false; 
    } 

    echo json_decode($response); 

回答

-1

你只是錯過了你的代碼兩件事情,這裏是使用你的代碼爲基礎的完整例子:

<?php 

    /* you must define an URL to POST to */ 
    $url = ""; 

    $data = array(
        "client_id" => $client_id, 
        "client_secret" => $client_secret, 
        "grant_type" => "authorization_code", 
        "code" => $code, 
        "redirect_uri" => "http://localhost:8080/nope", 
        "scope" => "basic" 
       ); 

    $ch = curl_init($url); 
      curl_setopt($ch, CURLOPT_POST, true); 
      curl_setopt($ch, CURLOPT_HTTPHEADER, $data); 
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) 

      /* this line below was missing in your code */; 
      curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));   

    $response = curl_exec($ch); 

    if (!$response) 
    { 
     echo 'A error has occurred ' . curl_error($ch); 
     return false; 
    } 

    echo json_decode($response); 

?> 

嘗試並根據您的需求進行調整。

+0

非常感謝。我還需要通過SSL提出請求。它正在工作。 –

+1

您離開'CURLOPT_HTTPHEADER'並且'CURLOPT_POST'是一個類似於其他的布爾值,而不是後置參數的計數。你也不能從if語句中echo出一個對象'echo json_decode(..)'.. AND'return false;'?看起來像一個屠殺的複製和粘貼。 –

1

你可以嘗試

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); 

與您的數據陣列將發送的POST數據因爲你已經有curl_setopt($ch, CURLOPT_POST, true);

http://php.net/manual/en/function.curl-setopt.php

所以

$ch = curl_init($url); 
curl_setopt($ch, CURLOPT_POST, true); 
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

乾杯

+0

謝謝。我在$ response變量中沒有收到任何東西。我應該收到帶有訪問令牌和到期日期或錯誤代碼的JSON響應。我也沒有收到。我是否從API規範正確地轉換了我的$ data數組? –