如何将Square付款集成到自定义网站的购物车中?

时间:2019-10-28 18:09:11

标签: javascript jquery html node.js square

我已成功将Square Payments API集成到我的网站中。但是现在看来,它只能收取1个数量和1个数量。我需要做到这一点,以便当用户更新购物车中的物品数量时-价格也会上涨,而这个价格就是他们的信用卡所要支付的价格。

我在我的自定义网站上建立了一个购物车,当数量增加或减少时,该购物车会更新总价。现在,我只需要弄清楚如何将Payments API链接到“总价”,以便向客户收取该金额。请帮忙。

Payment.html中的

脚本

      // Create and initialize a payment form object
      const paymentForm = new SqPaymentForm({
        // Initialize the payment form elements

        //TODO: Replace with your sandbox application ID
        applicationId: "applicationId",
        inputClass: 'sq-input',
        autoBuild: false,
        // Customize the CSS for SqPaymentForm iframe elements
        inputStyles: [{
            fontSize: '16px',
            lineHeight: '24px',
            padding: '16px',
            placeholderColor: '#a0a0a0',
            backgroundColor: 'transparent',
        }],
        // Initialize the credit card placeholders
        cardNumber: {
            elementId: 'sq-card-number',
            placeholder: 'Card Number'
        },
        cvv: {
            elementId: 'sq-cvv',
            placeholder: 'CVV'
        },
        expirationDate: {
            elementId: 'sq-expiration-date',
            placeholder: 'MM/YY'
        },
        postalCode: {
            elementId: 'sq-postal-code',
            placeholder: 'Zip Code'
        },
        // SqPaymentForm callback functions
        callbacks: {
            /*
            * callback function: cardNonceResponseReceived
            * Triggered when: SqPaymentForm completes a card nonce request
            */
            cardNonceResponseReceived: function (errors, nonce, cardData) {
            if (errors) {
                // Log errors from nonce generation to the browser developer console.
                console.error('Encountered errors:');
                errors.forEach(function (error) {
                    console.error('  ' + error.message);
                });
                alert('Encountered errors, check browser developer console for more details');
                return;
            }
                 // alert(`The generated nonce is:\n${nonce}`);
                fetch('process-payment', {
                  method: 'POST',
                  headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                  },
                  body: JSON.stringify({
                    nonce: nonce
                  })
                })
                .catch(err => {
                  alert('Network error: ' + err);
                })
                .then(response => {
                  if (!response.ok) {
                    return response.text().then(errorInfo => Promise.reject(errorInfo));
                  }
                  return response.text();
                })
                .then(data => {
                  console.log(JSON.stringify(data));
                  alert('Payment complete successfully!\nCheck browser developer console form more details');
                })
                .catch(err => {
                  console.error(err);
                  alert('Payment failed to complete!\nCheck browser developer console form more details');
                });
            }
        }
      });
           paymentForm.build();
     // onGetCardNonce is triggered when the "Pay $1.00" button is clicked
     function onGetCardNonce(event) {
       // Don't submit the form until SqPaymentForm returns with a nonce
       event.preventDefault();
       // Request a nonce from the SqPaymentForm object
       paymentForm.requestCardNonce();
     }

    </script>

server.js

const bodyParser = require("body-parser");
const crypto = require("crypto");
const squareConnect = require("square-connect");

const app = express();
const port = 3000;

// Set the Access Token
const accessToken =
  "accessToken";

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(__dirname));

// Set Square Connect credentials and environment
const defaultClient = squareConnect.ApiClient.instance;

// Configure OAuth2 access token for authorization: oauth2
const oauth2 = defaultClient.authentications["oauth2"];
oauth2.accessToken = accessToken;

// Set 'basePath' to switch between sandbox env and production env
// sandbox: https://connect.squareupsandbox.com
// production: https://connect.squareup.com
defaultClient.basePath = "https://connect.squareupsandbox.com";

app.post("/process-payment", async (req, res) => {
  const request_params = req.body;

  // length of idempotency_key should be less than 45
  const idempotency_key = crypto.randomBytes(22).toString("hex");

  // Charge the customer's card
  const payments_api = new squareConnect.PaymentsApi();
  const request_body = {
    source_id: request_params.nonce,
    amount_money: {
      amount: 100, // $1.00 charge
      currency: "USD"
    },
    idempotency_key: idempotency_key
  };

  try {
    const response = await payments_api.createPayment(request_body);
    res.status(200).json({
      title: "Payment Successful",
      result: response
    });
  } catch (error) {
    res.status(500).json({
      title: "Payment Failure",
      result: error.response.text
    });
  }
});

app.listen(port, () => console.log(`listening on - http://localhost:${port}`));

0 个答案:

没有答案