【发布时间】:2021-12-14 19:38:57
【问题描述】:
当在 checkout.html 上单击 <button> 时,我正在使用 async/await 来获取包含数组的文件 (createCharge.php)
如果我使用print_r,我可以在控制台中看到所有结果,例如名称、描述、金额,甚至是新生成的“hosted_url”
客户将用于继续付款。
问题是我不知道如何将hosted_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 带入<script> 内的<a> 标记中。
这是我的 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'];
createCharge.php 中的这段代码对我有用! :)
【问题讨论】:
-
我只弄乱了 PHP 大约 20 分钟,但您的
echo print_r echo在 return 语句之后。这通常是一件坏事,不是吗? -
@Travis 你好,是的,但是如果我把它放回去,它只会返回同样的东西,所有数据而不仅仅是 hosts_url
-
到目前为止您尝试过什么?你被困在哪里了?是什么让您无法准确返回您想要返回的内容,而不是
<pre>和转储数组? -
@NicoHaase 我只是不确定我是否应该获取所有数据,然后以某种方式选择
<a>标签href中的哪些数据,或者我是否应该只返回一条数据(托管网址)。我也不确定<script>是否需要await response.json或.text作为链接,我认为这无关紧要 -
console.log(data) 记录什么?
标签: php arrays curl async-await coinbase-api