Hi, I'm trying to setup crypto payments using coinbase commerce but I'm having a hard time returning the hosted URL, The charge.php file seems correct but the button on my checkout.html page is not fetching the information from charge.php.
The button should fetch the CURLOPT_URL and API-KEY from the PHP file along with the arrays for description, customerUID, price etc. If I fetch from the data.json file I receive the Object information but I need to fetch the information from charge.php instead, How do I do this using Async/Await?
Any help will be much appreciated :) Thanks.
Here is my checkout.html...
<button id="btn">Pay with Crypto?</button>
<p id="pay"></p>
<script>
const btn = document.getElementById('btn');
const pay = document.getElementById('pay');
btn.onclick = async() => {
const response = await fetch('coinbasePHPtest/charge.php');
const charge= await response.json();
console.log(charge);
pay.innerHTML = `<a href="${charge}">Pay Now!</a>`
}
</script>
And here is my charge.php file...
<?php
$userdetails = $_SESSION['usr_name'];
$repairprice = $_POST['price'];
$customerUID = $_POST['uid'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.commerce.coinbase.com/charges/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$post = array(
"name" => "TeZe",
"description" => "Repair Service",
"local_price" => array(
'amount' => "$repairprice",
'currency' => 'GBP'
),
"pricing_type" => "fixed_price",
"metadata" => array(
'customer_id' => "$customerUID",
'customer_name' => "$userdetails"
)
);
$post = json_encode($post);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'X-Cc-Api-Key: df-xxxxxxx-1';
$headers[] = 'X-Cc-Version: 2018-03-22';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
$response = json_decode($result, TRUE);
return $response->data->hosted_url;
?>
Here is the old data.json file..
{
"name":"TeZe",
"description":"Selected Repair Service",
"pricing_type":"fixed_price"
}
What I have tried:
This script worked in returning an object {description:Repair service, name:TeZe, pricing_type:fixed_price}
<script>
const btn = document.getElementById('btn');
const pay = document.getElementById('pay');
btn.onclick = async() => {
const res = await fetch('coinbasePHPtest/data.json');
const charge= await res.json();
console.log(charge);
pay.innerHTML = `<a href="${charge}">Pay Now!</a>`
}
</script>