简体   繁体   中英

PHP cURL won't POST JSON to API

I have a dashboard with a link that triggers a DB to update an application status to "approved" and posts to an API. The database is being updated, but the recipient is not being emailed.

The database step is working but not posting to the API. The API is what triggers an email to the individual.

Disclaimer: I'm brand new to coding so apologies if I'm not providing the correct/enough information.

<?php

require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db); //Connect DB
$id = $_GET['id'];
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error()); 
  }

//Create query based on the ID passed from table
// sql to update a record
$sql = "UPDATE all_contacts SET status='Approved' WHERE id = '$id'"; 

$url = 'https://mail.com/messages/email';
$data = array(
  "subject" => "Hello!",
  "body" => "hi",
  "recipients" => array (
    "email" => "example@email.com")
  );
$data_string = json_encode($data);
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "Content-Type: application/json",
    "X-AUTH-TOKEN: mytoken",
    "Content-Length: ". strlen($data_string)));

$result = curl_exec($ch);
echo $result;
curl_close($ch);

if (mysqli_query($conn, $sql)) {
    mysqli_close($conn);
    header("Location: dashboard.php"); 
    exit;
} else {
    echo "Error changing status";
}

?>

Expected result: Update the DB with the new application status and trigger an email to the email listed in $data.

Actual result: It updates the DB but does not post to the API.

Tested your code, and it's working correctly.

I tested it to Beeceptor.

在此处输入图片说明

在此处输入图片说明

What are you getting as an error?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM