Как интегрировать платежи Square в корзину моего пользовательского веб-сайта? - PullRequest
0 голосов
/ 28 октября 2019

Я успешно интегрировал API Square Payments в свой веб-сайт. Но сейчас кажется, что он может взимать только 1 сумму и 1 количество. Мне нужно сделать так, чтобы, когда пользователь обновлял количество товаров в своей корзине - цена также повышалась, и эта цена была той, которая списывается с его карты.

Я построил корзину для покупок вмой пользовательский веб-сайт, который обновляет общую цену, когда количество увеличивается или уменьшается. Теперь мне просто нужно выяснить, как я должен связать 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}`));
...