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

React中从JSON获取商品价格并集成到Paystack支付表单

从商品JSON获取价格并传入Paystack支付表单

核心注意事项

Paystack的amount字段要求传入最小货币单位数值(比如尼日利亚奈拉需转换为Kobo,即原价格×100),处理商品价格时必须完成单位转换,否则支付金额会出错。

修改后的完整代码

// 定义商品JSON数据
const product = {
  "id1":1,
  "id":"fjuei567dhdjdggSw",
  "name":"Gemu",
  "price":1000,
  "thumbnail":"/images/gemu/g1.png",
  "longname":"Gemu - Game Store App UI Kit",
  "banner1":"/images/gemu/g1.png",
  "banner2":"/images/gemu/g2.png",
  "banner3":"/images/gemu/g3.png",
  "banner4":"/images/gemu/g4.png",
  "banner5":"/images/gemu/g5.png",
  "banner6":"/images/gemu/g6.png",
  "banner7":"/images/gemu/g7.png",
  "banner8":"/images/gemu/g8.png"
};

const onSuccess = (reference) => {
  console.log(reference);  
};

const onClose = () => {
  console.log('closed')
}

const PaystackHookExample = () => {
  // 动态生成配置,直接从商品数据中获取价格并转换单位
  const config = {
    reference: (new Date()).getTime().toString(),
    email: "user@example.com", // 建议替换为当前登录用户的真实邮箱
    amount: product.price * 100, // 转换为Paystack要求的最小货币单位
    publicKey: 'pk_test_89aaa3531bf6c9xxxxxxxxx',   
  };

  const initializePayment = usePaystackPayment(config);
  
  return (
    <div>
      <button 
        onClick={() => initializePayment(onSuccess, onClose)} 
        className="btn mt-3 me-2 d-flex justify-content-center"
      >
        Start Purchase
      </button>
    </div>
  );
 };

异步获取商品数据的扩展方案

如果商品数据是从后端API异步获取的,可通过useState和useEffect处理加载逻辑:

import { useState, useEffect } from 'react';

const PaystackHookExample = () => {
  const [product, setProduct] = useState(null);

  // 模拟从API获取指定商品数据
  useEffect(() => {
    fetch('/api/products/fjuei567dhdjdggSw')
      .then(res => res.json())
      .then(data => setProduct(data));
  }, []);

  // 商品数据未加载完成时显示占位内容
  if (!product) return <div>加载中...</div>;

  const config = {
    reference: (new Date()).getTime().toString(),
    email: "user@example.com",
    amount: product.price * 100,
    publicKey: 'pk_test_89aaa3531bf6c9xxxxxxxxx',   
  };

  const initializePayment = usePaystackPayment(config);
  
  return (
    <div>
      <button 
        onClick={() => initializePayment(onSuccess, onClose)} 
        className="btn mt-3 me-2 d-flex justify-content-center"
      >
        Start Purchase
      </button>
    </div>
  );
 };

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 06:05:28