使用cURL和PHP调用wrikeapi

使用cURL和PHP调用wrikeapi,php,curl,Php,Curl,这在控制台中可以工作,但当我尝试使用PHP时却无法工作 $cURL = "curl -X POST -d 'client_id=".$CLIENT_ID."&client_secret=".$CLIENT_SECRET."&grant_type=authorization_code&code=".$CODE."' https://www.wrike.com/oauth2/token"; 编写PHP代码 $postData = array("client_id" =>

这在控制台中可以工作,但当我尝试使用PHP时却无法工作

$cURL = "curl -X POST -d 'client_id=".$CLIENT_ID."&client_secret=".$CLIENT_SECRET."&grant_type=authorization_code&code=".$CODE."' https://www.wrike.com/oauth2/token";
编写PHP代码

$postData = array("client_id" => $CLIENT_ID, 
            "client_secret" => $CLIENT_SECRET, 
            "grant_type" => "authorization_code",
            "code" => $CODE);

$handler = curl_init();  
curl_setopt($handler, CURLOPT_URL, $url);  
curl_setopt($handler, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($handler, CURLOPT_POST, sizeof($postData));  
curl_setopt($handler, CURLOPT_POSTFIELDS, $postData);  
$response = curl_exec ($handler);  
curl_close($handler);
当我运行这段代码时,结果是“资源id#2”,我期望的结果是

{
   "access_token": "2YotnFZFEjr1zCsicMWpAA",
   "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",
   "token_type": "bearer",
   "expires_in": 3600
}
在控制台中可以很好地工作,但当我尝试使用PHP时不起作用,

我建议使用它,这将使您的生活更加轻松。您的代码将是:

        $postData = array("client_id" => $CLIENT_ID, 
            "client_secret" => $CLIENT_SECRET, 
            "grant_type" => "authorization_code",
            "code" => $CODE);
        $headers = array('Content-Type' => 'application/json');  // assuming you post JSON
        $response = Requests::post($$url, $headers, json_encode($obj));
        if ($response->status_code !== 200) {
             // handle OK
        } else {
             // handle ERROR
        }
请求库还处理PHP中没有curl的情况;将在一个对象中返回完整的标题、正文、cookies等。

有几件事(一些评论已经指出):

  • CURLOPT_POST
    只应设置为
    1
    而不是数据大小
  • 如果您看到的是
    资源id#2
    ,则可能是从
    $handler
    而不是
    $result
    测试结果
  • 虽然可能没有必要,但您可以在发送之前对数据使用,以确保编码正确
  • 始终值得使用检查任何卷曲错误
一个完整的例子:

$postData = array("client_id" => $CLIENT_ID, 
            "client_secret" => $CLIENT_SECRET, 
            "grant_type" => "authorization_code",
            "code" => $CODE);

$handler = curl_init();

curl_setopt($handler, CURLOPT_URL, $url);
curl_setopt($handler, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($handler, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($handler, CURLOPT_POST, 1);

$response = curl_exec($handler);
if (curl_errno($handler)) {
    echo 'Error:' . curl_error($handler);
}
curl_close ($handler);

var_dump($response);

附带说明,这是一个方便的工具,用于将curl命令转换为PHP。

为所有感兴趣的人更新。我最近在HPLeague的库中添加了一个工作包,允许您连接Wrike Api:


(在这个问题上要解决的另一个问题可能是PHP的SSL配置,更多示例如下:)

CURLOPT_POST
预期为0或1。不要使用PASDATA长度。考虑使用GuffsHTTP客户端库:您确定您正在访问$响应而不是$处理程序吗?如果能看到您的代码实际尝试使用返回的数据,那就太好了。