PayPal Node SDK: сумма валюты должна быть неотрицательным числом - PullRequest
0 голосов
/ 10 июля 2019

Я использую Paypal-Node-SDK для выполнения платежей в моем приложении реагирования, у меня уже есть корзина покупок с избыточным кодом, и когда я отправляю форму, у меня всегда появляется эта ошибка:

Сумма валюты должна быть неотрицательным числом, при желании может содержать ровно 2 десятичных знака, разделенных '.', Необязательный разделитель тысяч ',', ограничено 7 цифрами перед десятичной точкой и валютой, которая является действительной валютой ISOКод

На моем сервере у меня есть этот код:

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);
      }
  });
});

В моем приложении реакции у меня есть этот код:

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);
...