You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从PHP返回特定数组数据并将Coinbase支付hosted_url填充到前端<a>标签中

解决方案:修正后端PHP的返回逻辑

问题的核心在于后端PHP代码的响应输出方式,以及JSON解析后的访问方式错误。以下是修正后的代码:

修改后的createCharge.php

<?php
$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);
// 关键修改:用echo输出hosted_url,且使用数组索引访问
echo $response['data']['hosted_url'];
?>

前端代码无需修改

保持原来的前端代码即可,此时fetch会直接拿到纯净的hosted_url字符串,正确填充到<a>标签的href中。


问题原因分析

  1. PHP的return无法输出响应:在PHP脚本中,return仅用于函数内部返回值,不会将内容输出到HTTP响应体中。前端需要后端返回具体内容,所以必须使用echo来输出hosted_url。
  2. JSON解析类型错误:因为json_decode($result, true)的第二个参数为true,解析后的$response是关联数组,而非对象。因此不能用$response->data->hosted_url这种对象属性的访问方式,必须使用数组索引$response['data']['hosted_url']。

这样修改后,前端就能正确获取到支付链接并渲染出可用的支付按钮了。

内容的提问来源于stack exchange,提问作者kbmzeeC0de

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 22:57:46