PayPal Node SDK:货币金额必须为非负数

时间:2019-07-10 16:15:04

标签: node.js reactjs paypal paypal-sandbox paypal-rest-sdk

我正在使用Paypal-Node-SDK在我的React应用中执行付款,我已经有一个带有redux的购物车,并且当我发布表格时,我总是会遇到此错误:

  

货币金额必须为非负数,可以选择包含正好用'。'分隔的2个小数位,可选的千位分隔符',',限于小数点前7位数字和有效的ISO货币代码< / p>

在我的服务器上,我有以下代码:

const express = require('express'),
path = require('path'), 
app = express(),
bodyParser = require('body-parser'),
paypal = require('paypal-rest-sdk');

paypal.configure({
  'mode': 'sandbox', //sandbox or live
  'client_id': 'myclientId',
  'client_secret': 'myClientSecret'
});

var tempTotal=0;
app.post('/api/pay-with-paypal',(req,res)=>{

  const create_payment_json = {
    "intent": "order",
    "payer": {
        "payment_method": "paypal"
    },
    "redirect_urls": {
        "return_url": "https://localhost:49652/paypal/success",
        "cancel_url": "https://localhost:49652/paypal/cancel"
    },
    "transactions": [{
        "item_list": {
            "items": req.body.items
        },
        "amount": {
            "currency": "USD",
            "total": req.body.total,
            "details":{
              "subtotal": req.body.subtotal,
              "tax": req.body.tax,
              "shipping": req.body.shipping
            }
        },
        "description": "Hat for the best team ever."
    }]
  };
  paypal.payment.create(create_payment_json, function (error, payment) {
    if (error) {
      console.log('An error occurs in  paypal.payment.create');
      console.log(error);
      res.send(error);
    } else {
        for(let i =0;i<payment.links.length;i++){
            if(payment.links[i].rel==='approval_url'){
              tempTotal=req.body.total;
              res.json(payment.links[i].href+"&total="+req.body.total);
            }
        }
    } 
  });
});
app.get('/paypal/success',(req,res)=>{
    const payerId=req.query.PayerID,
    paymentId=req.query.paymentId;
    var execute_payment_json = {
      "payer_id": payerId,
      "transactions": [{
          "amount": {
              "currency": "USD",
              "total": tempTotal
          }
      }]
    };
    paypal.payment.execute(paymentId, execute_payment_json, function (error, payment) {
      if (error) {
        console.log('An error occurs in  paypal.payment.create');
        console.log(error);
        res.send(error);
      } else {
          console.log("Get Payment Response");
          console.log(JSON.stringify(payment));
          res.send(payment);
      }
  });
});

在我的React应用中,我有以下代码:

import React from 'react';
import {connect} from 'react-redux';
import api from './apis/api';
class CheckoutPaypalForm extends React.Component{
    constructor (props) {
        super(props);
        this.state = {
            total:0,
            items:[]
        }
    }
    componentDidMount(){
        var total=0;
        this.props.orders.orders.forEach(function(order) {
            total+=order.quantity*order.price;
        });
        this.setState({
            total:total
        })
        var items=[];
        var tempItem={};
        this.props.orders.orders.forEach(function(order) {
            tempItem.name=order.name.toString();
            tempItem.sku=order.id;
            tempItem.price=order.price.toString();
            tempItem.currency=order.currency.toString();
            tempItem.quantity=order.quantity;

            items.push(tempItem);
        });
        this.setState({
            items
        })
    }
    submitPaypalForm=(e)=>{
        e.preventDefault();
        var shipping="1";
        var tax="0.15";
        var total=(this.state.subtotal+parseFloat(tax)+parseFloat(shipping)).toFixed(2);
        api.post('/api/pay-with-paypal', {
            total:total,
            items: this.state.items,
            subtotal: this.state.subtotal,
            shipping:shipping,
            tax:tax
        })
        .then(function (response) {
            window.location.replace(response.data);
            console.log(response);
        })
        .catch(function (error) {
            console.log('An error occurs on post submitPaypalForm()');
            console.log(error);
        });
    }
    render(){
        return(
            <div className="form-payment method-to-pay">
                <form onSubmit={(e)=>this.submitPaypalForm(e)} 
                >                    
                    <p>To complete the transaction, we will send you to PayPal's secure servers.</p>
                    <button className="btn btn-danger" type="submit">Proceed</button>
                    <span>By completing the purchase, you agree to these <a href="#">Terms of Use</a></span>
                </form>
            </div>
        )
    }
}
const mapStateToProps=(state)=>{
    return{
      orders:state.orders
    }
}
export default connect(mapStateToProps)(CheckoutPaypalForm);

1 个答案:

答案 0 :(得分:0)

我使用以下代码解决了此问题:

var tempTotal=parseFloat(req.body.total).toFixed(2);