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

Javascript 如何将方形付款集成到自定义网站的购物车中?,javascript,jquery,html,node.js,square,Javascript,Jquery,Html,Node.js,Square,我已经成功地将Square Payments API集成到我的网站中。但现在,它似乎只能收取1个金额和1个数量。我需要这样做,当用户更新他们购物车中物品的数量时,价格也会上涨,而这个价格就是他们卡上的费用 我在我的自定义网站上建立了一个购物车,当数量增加或减少时,它会更新总价格。现在我只需要弄清楚如何将支付API与总价联系起来,以便向客户收取该金额。请帮忙 payment.html中的脚本 // Create and initialize a payment form object

我已经成功地将Square Payments API集成到我的网站中。但现在,它似乎只能收取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
中,您使用的是
amount:100
。您应该从保存购物车信息的任何位置检索金额。如果您使用的是items,那么您可能更喜欢使用CreateOrder(),这样您就可以实际传入item和quantity信息。然后将
order\u id
传递给
createPayment
端点的
request\u body
。@sjosey感谢您的回复。关于金额字段的观点很好。我只有一个产品要卖,所以这可能真的有效!如果我有多个项目,我可能需要使用CreateOrder,尽管CreateOrder表示已弃用。我还注意到Square的所有示例都使用cURL、Ruby或Python。我希望只使用ajax。Square是否将订单和发货信息保存到我的仪表板?或者我必须创建一个表单来输入所有这些信息,以便我可以将产品发送给该人员?也许有一个formspree表单可以在1个按钮中向我发送发货信息并处理卡付款?您需要从后端服务器进行API调用。如果您的AJAX调用是调用后端服务器(PHP、Ruby、Python、Node等),那么就可以了。我们不允许从客户端调用API,因为这将允许任何人查看您的访问令牌并访问您的帐户。完成交易后,它将在您的仪表板上显示,但您需要询问配送信息并将其传递给他人。谢谢--我正在使用Node。我已经设置好付款表并开始工作。我会将AJAX调用放在server.js文件中吗?我是否可以在信用卡付款表中包含发货字段?还是在AJAX请求中?您知道创建支付端点的示例AJAX调用是什么样的吗?还是创建订单端点?或者哪一个最适合这个?不幸的是,我没有任何关于这个的AJAX请求示例。不过,我们的演练使用Node,所以您可以看到它是如何实现的:但不是Ajax。基本上,您需要在调用
CreatePayment
的位置或不希望重新加载页面的位置执行客户端AJAX调用。
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}`));