FarrisFahad 103 Junior Poster

I want to post Pins using Pinterest API. I have tried to generate code using ChatGPT but it returns an error.

Here is my code so far ...

<?php

$clientId = "xxx"; // Replace with your App ID
$clientSecret = "xxx"; // Replace with your App Secret
$redirectUri = "xxx"; // Must match the one used earlier
$authCode = "xxx"; // Paste the code from the URL

// Pinterest API token endpoint
$tokenUrl = "https://api.pinterest.com/v5/oauth/token";

$postFields = [
    'grant_type' => 'authorization_code',
    'code' => $authCode,
    'redirect_uri' => $redirectUri,
    'continuous_refresh' => true
];

$authHeader = base64_encode("$clientId:$clientSecret");

$ch = curl_init($tokenUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postFields));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
   'Content-Type: application/json',
   'Authorization: Basic ' . $authHeader
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

if ($response === false) {
    die("cURL Error: " . htmlspecialchars($error));
}

$data = json_decode($response, true);

// Error handling for HTTP response
if ($httpCode !== 200) {
    die("Pinterest API Error: HTTP $httpCode - " . htmlspecialchars($response));
}

// Error handling for API response
if (!isset($data['access_token'])) {
    die("Error: Invalid response from Pinterest API. Full response: " . json_encode($data, JSON_PRETTY_PRINT));
}

// Successfully received access token
$accessToken = $data['access_token'];
echo "Access Token: " . htmlspecialchars($accessToken);

?>

Here is the error message I am getting ...

Failed to create pin. Response: {"code":2,"message":"Authentication failed.","status":"failure"}

I tried many things but it always return an error.

Here is the docs page: https://developers.pinterest.com/docs/api/v5/oauth-token

Is there something I am missing?

Any help would be appreciated.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.