duanfan5012 2019-07-22 08:32
浏览 78
已采纳

没有得到预期的PHP cURL响应

I have the following PHP code:

<?php
$data = array("client_id" => "sipgate-app-web", "grant_type" => "password", "username" => "my_username", "password" => "my_password");
$data_string = json_encode($data);

$ch = curl_init('https://api.sipgate.com/login/sipgate-apps/protocol/openid-connect/token');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Accept: application/json'
));

$result = curl_exec($ch);

echo $result;
?>

Unfortunately, I'm not getting the expected response. The response I'm receiving is:

{"error":"invalid_request","error_description":"Missing form parameter: grant_type"}

When using an online cURL tool like https://onlinecurl.com with the same data (URL, header, data) as in my cURL PHP code, I'm getting the right response. This means, there's something wrong with my PHP code. I'm not getting any error in the PHP error log.

The manual says I have to use the following cURL code:

 curl \
--request POST \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Accept: application/json' \
--data-urlencode "client_id=sipgate-app-web" \
--data-urlencode "grant_type=password" \
--data-urlencode "username=my_username" \
--data-urlencode "password=my_password" \
https://api.sipgate.com/login/sipgate-apps/protocol/openid-connect/token

Since I'm new to cURL, after googling a lot, I have no idea what I'm doing wrong.

Can anybody help me?

EDIT: You can test my PHP code above as it is. You should get the following response, if the code is working:

{"error":"invalid_grant","error_description":"Invalid user credentials"}

  • 写回答

2条回答 默认 最新

  • dongya1228 2019-07-22 08:49
    关注

    As per the manual, your request needs to have the Content-Type of application/x-www-form-urlencoded which looks like this:

    key1=value1&key2=value2
    

    Thus you need to convert your array into such a string either manually or with http_build_query, like so:

    $data_string = http_build_query( $data );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵