使用CURL将JSON数据发布到API

Ark*_*Net 11 php api json curl

当我json使用curl- 将数据发布到API时- 我没有得到任何输出.我想向收件人发送电子邮件邀请.

$url_send ="http://api.address.com/SendInvitation?";
$str_data = json_encode($data);

function sendPostData ($url, $post) {

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));

    return curl_exec($ch);
}
Run Code Online (Sandbox Code Playgroud)

这是 JSON $str_data

[
    {
        "authorizedKey"  : "abbad35c5c01-xxxx-xxx",
        "senderEmail"    : "myemail@yahoo.com",
        "recipientEmail" : "jaketalledo86@yahoo.com",
        "comment"        : "Invitation",
        "forceDebitCard" : "false"
    }
] 
Run Code Online (Sandbox Code Playgroud)

和调用功能:

$response = sendPostData($url_send, $str_data);
Run Code Online (Sandbox Code Playgroud)

这是API:https://api.payquicker.com/Help/Api/POST-api-SendInvitation

Dyl*_*mes 23

尝试添加curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
并更改http_build_query($post)$post

实施:

<?php

$data = array(
  "authorizedKey" => "abbad35c5c01-xxxx-xxx",
  "senderEmail" => "myemail@yahoo.com",
  "recipientEmail" => "jaketalledo86@yahoo.com",
  "comment" => "Invitation",
  "forceDebitCard" => "false"
);

$url_send ="http://api.payquicker.com/api/SendInvitation?authorizedKey=xxxxx";
$str_data = json_encode($data);

function sendPostData($url, $post){
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");  
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
  $result = curl_exec($ch);
  curl_close($ch);  // Seems like good practice
  return $result;
}

echo " " . sendPostData($url_send, $str_data);

?>
Run Code Online (Sandbox Code Playgroud)

我得到的回应是:

{"success":false,"errorMessage":"Object reference not set to an instance of an object.","status":"N/A"}
Run Code Online (Sandbox Code Playgroud)

但也许它可以用于有效数据....

编辑: 对于发布xml,它与其网站上的相同,但字符串除外:

$xml = '
<SendInvitationRequest xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/PQApi.Models">
  <authorizedKey>80c587b9-caa9-4e56-8750-a34b17dba0a2</authorizedKey>
  <comment>sample string 4</comment>
  <forceDebitCard>true</forceDebitCard>
  <recipientEmail>sample string 3</recipientEmail>
  <senderEmail>sample string 2</senderEmail>
</SendInvitationRequest>';
Run Code Online (Sandbox Code Playgroud)

然后:

sendPostData($url_send, $xml)
Run Code Online (Sandbox Code Playgroud)


小智 13

你必须添加标题:

$headers= array('Accept: application/json','Content-Type: application/json'); 
Run Code Online (Sandbox Code Playgroud)

和:

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
Run Code Online (Sandbox Code Playgroud)

除此以外 ...

HTTP状态415 - 不支持的媒体类型

......可能会发生.