Search code examples
javascriptsquare-connect

How to send custom amount Square payment API from web


I'm looking into taking payments through the Square connect API on a website, but I can't figure out how to allow the user to key in any payment amount they wish (like a PayPal pay me button). Is this possible to do, or can you only take payments in pre-set fixed amounts via Square?

It looks like in Square's examples the amount is being set in the backend code and there's no way to send the amount for the transaction through from the frontend.

I am following Square's walkthrough using Node here: https://developer.squareup.com/docs/payment-form/payment-form-walkthrough

Apologies if this has been asked before, but I couldn't find anything recent that addressed the issue.


Solution

  • I ended up solving this by coding the fetch to /process-payment explicitly in the frontend .js code instead of having it in the form submit so it looks like this:

    function submitPaymentRequest(event) {
      let nonce = document.getElementById("card-nonce").value;
    
      fetch("process-payment", {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          nonce: nonce,
          amount: document.querySelector('input[name="amount"]').value
        })
      })
        .then(response => {
          console.log(response);
          response.json().then(data => {
            console.log(data);
            alert(JSON.stringify(data));
          });
        })
        .catch(function(error) {
          console.log("the error was", error);
        });
    }
    

    I posted a full working example of this here.