Как я могу сделать этот пост API запрос на PHP? - PullRequest
0 голосов
/ 24 сентября 2019

Я сделал почтовый запрос на API, используя ajax.Интересно, как я могу сделать то же самое в php.

<script type="text/javascript">
  var cbIntegrationId = "xxxxxx"; // I have it
  var clientId = "xxxxxxx"; //I have it
  var clientSecret = "xxxxx"; //I have it
  var tableName = "Test_Database";

    //Get access token
    $.post(
      "https://" + cbIntegrationId + ".caspio.com/oauth/token",
      {
        grant_type: "client_credentials",
        client_id: clientId,
        client_secret: clientSecret
      },
      function(cbAuth){
        //Run POST call
        $.ajax({
          url: "https://" + cbIntegrationId + ".caspio.com/rest/v2/tables/" + tableName + "/records?response=rows",
          type: 'POST',
          'data': JSON.stringify({"UniqueID":"988"}), //Define record values
          headers: {
            "Authorization": "Bearer " + cbAuth.access_token, //Extracts the access token from the initial authorization call
            "Content-Type": "application/json", //Required, otherwise 415 error is returned
            "Accept": "application/json"
          },
          dataType: 'json',
          success: function (data) {
            console.log(data.Result); //Check the console to view the new added row
          },
          error: function(data) {
            console.log(data.responseJSON); //Check the console to view error message if any
          }
        });
      }
    );
</script>

Я провел некоторое исследование, но не смог найти ничего, что решило бы мою проблему.Мне действительно нужна твоя помощь.

1 Ответ

0 голосов
/ 24 сентября 2019

Вы можете использовать cURL для вызова API с использованием PHP.

Таким образом, в соответствии с вашим случаем вы отправляете данные с использованием метода POST.Таким образом, мы можем использовать cURL следующим образом с некоторыми заголовками:

$apiURL = "https://yourURL";
$uniqueID = "UniqueID:988";
$postData = json_encode($uniqueID); // Encode the data into a JSON string
$authorization = "Authorization: Bearer " . $token; // Prepare the authorization token

$curl = curl_init();

curl_setopt($curl, CURLOPT_HTTPHEADER, array($authorization, 'Content-Type: application/json', 'Accept : application/json')); // Inject the token into the header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // To get actual result from the successful operation
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); // Specify HTTP protocol version to use;
curl_setopt($curl, CURLOPT_POST, 1); // Specify the request method as POST
curl_setopt($curl, CURLOPT_URL, $apiURL); // Pass the API URL
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); // Set the posted fields
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // This will follow any redirects

$response = curl_exec($curl); // Here you will get the response after executing
$error = curl_error($curl); // Return a string containing the last error for the current session

curl_close($curl); // Close a cURL session

Надеюсь, это поможет вам!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...