我正在使用 async/await 來獲取一個檔案 (createCharge.php),當<button>點擊 checkout.html時,該檔案包含帶有資料的陣列
如果我使用,print_r我可以在控制臺中看到所有結果,例如名稱、描述、金額,甚至是客戶將用來繼續付款的新生成的“hosted_url”。
問題是我不知道如何將 hosts_url 結果提取到結帳頁面和<a href="">Pay now!</a>.
這是我在 checkout.html 上的內容...
<button id="btn">Pay with Crypto?</button>
<p id="pay"></p>
<script>
btn.addEventListener('click', async (e) => {e.preventDefault();
const response = await fetch('coinbasePHPtest/createCharge.php/');
if (!response.ok) {
const errorMessage = await response.text();
console.error(response.status, response.statusText, errorMessage);
alert('There was an error creating the charge.');
return;
}
const newurl = await response.text();
console.log(newurl);
pay.innerHTML = `<a href="${newurl}">Pay Now! - Coinbase</a>`;
});
</script>
你可以看到我試圖把hosted_url入<a>內的標簽<script>。
這是我的 createCharge.php,它實際上創建了 hosts_url...(例如:https ://commerce.coinbase.com/charges/xxxxx )
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.commerce.coinbase.com/charges');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(
array (
'name' => 'My-Company',
'description' => 'Selected Product',
'local_price' =>
array (
'amount' => '147.00',
'currency' => 'GBP',
),
'pricing_type' => 'fixed_price',
'metadata' =>
array (
'customer_id' => 'id_1',
'customer_name' => 'Satoshi Nakamoto',
),
'redirect_url' => 'https://www.my-site.co.uk/Checkout/payment_successful.php',
'cancel_url' => 'https://www.my-site.co.uk/Checkout/payment_cancelled.php',
)
));
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'X-Cc-Api-Key: MY-API-KEY';
$headers[] = 'X-Cc-Version: 2018-03-22';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close($ch);
$response = json_decode($result, true);
return $response->data->hosted_url;
?>
我也試過了。。
pay.innerHTML = `<a href="${hosted_url}">Pay Now!</a>`
pay.innerHTML = `<a href="{hosted_url}">Pay Now!</a>`
pay.innerHTML = `<a href="${newurl->hosted_url}">Pay Now!</a>`
pay.innerHTML = `<a href="{.hosted_url}">Pay Now!</a>`
沒有運氣。
和...
btn.onclick = async() => {
const response = await fetch('coinbasePHPtest/charge.php/hosted_url');
const data = await response.json();
&
btn.onclick = async() => {
const resp = await fetch(`coinbasePHPtest/createCharge.php/${hosted_url}`);
const data = await resp.json();
解決方案:
$result = curl_exec($ch);
curl_close($ch);
$response = json_decode($result, true);
echo $response['data']['hosted_url'];
This code within the createCharge.php worked for me! :)
uj5u.com熱心網友回復:
我認為您只想輸出資料而不是使用回傳。代替
return $response->data->hosted_url;
和
echo $response['data']['hosted_url'];
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/350847.html
標籤:php arrays curl async-await coinbase-api
