Payment form issues

Creating first payment form, for integration within my clients website hosted elsewhere than with Square. Two issues.

  1. I cannot seem to find in the docs how to submit the form with the amount anywhere other than in the ‘submit’ button. I need to be able to show a ‘Pay now’ button and the form parameters to include the payment value.

  2. I get an error when submitting the payment form, where the code was copied and pasted from Squares own walkthrough page. Using the sandbox values too, the result I get in FF console is as follows:
    POST https://squareup.com/1.0/as-reporter/csp/H1RIu78lArbEkNnMnJ_Dc3rlPQ8hFsEvQGLIzjtY
    [HTTP/2 401 Unauthorized 156ms]

Can anyone please point me to tutorials.

Ambrose

  1. The payment form has a function called requestCardNonce which you need to call. You can call it from anywhere you like; in the example we use a submit button but you can use it anywhere else (it’s just a Javascript function call).
  2. 401 unauthorized implies you didn’t fill out the applicationId of the SqPaymentForm object, which is a required field to work properly. If you did include it, be sure to include either sandbox or production application id depending on what you’re trying to use. The walkthrough uses sandbox throughout it.
  1. The nonce is being called and retrieved successfully. And then I moved on using the walkthrough page, to add the JS etc.

  2. There’s a failure which seems to be the applicationID but I am using the applicationID that the sandbox is showing me. Equally, I am using the Access token that it provides. One thing I have noticed (but which doesn’t fix my issue) is that I have created an application I have named ‘1st application’. With that blue square on the page (in the developers dashboard), it shows the applicationID to begin with ‘sq0idp’ whereas, if I open that application, the applicationID is shown to be the same but with the beginning being ‘sandbox-sq0idp’. However, as mentioned, neither brings me success and I still get a 401 error in the javascript console.

My other issue is with the card payment form. the default layout shows the submit button to be containing the value to be paid. I want the submit button to show ‘Make Payment’ and for the payment amount to be submitted perhaps as a parameter because it will be dynamic. I see nothing in the docs to enable me to learn how to do that.

I am hosting the page online so, if I send you a link to it, might you able, more easily, to help me?

Are you able to access the developers dashboard on this account to see the ‘1st gateway’ application I have created?

Kind regards,

Ambrose

OK, I have spoken to your staff by phone but they can’t help because it’s technical stuff so I can only contact you by this means.

The application ID is correct as per the developer dashboard sandbox. We need to fix whatever is causing it not to work.

I need also to get accurate info from you on how to adjust the hard-coded values in server.js so that it won’t always submit 1.00 USD for payment but, instead, it will be specific to the transaction.
Also, that the settings placed by one transaction won;t be used by another, which may be got through more quickly than the other.
My client wants this completed by Monday morning so, if it means getting one of your authorised people to provide a copy-and-paste completed solution, then please advise of their contact details. (Though given that its the application ID that is the problem, I’m not sure someone else’s code will address the matter.

Need to hear back more quickly if at all possible, please.

Can you share a code snippet or public page? It sounds like the application is not being set correctly regarding the 401 issue.

As for the button: this is just an HTML button, and you can change the text of it any way you like. You can see it in the code snippet here: https://developer.squareup.com/docs/payment-form/payment-form-walkthrough#112--add-an-html-div, the text is “Pay $1.00”, but this is just an example - you can change that to be whatever you like.

As for the $1.00 charge on the server-side, again, this is something you can make it to be whatever you want. The CreatePayment request takes in an integer amount, so if you want to figure out the cost of an item, for example, you could call the Catalog API, pull the item and its cost, and pass in the amount instead of 100.

Thanks.

Here’s the live page which uses the sandbox.
(domain removed)
Is there anywhere I can view sample code for getting and calculating the amount to be charged as well as currency. Perhaps similarly, the order_reference. Remember, I’m running the website separately from Square on our own servers. I’ve been through lots of docs but seemingly, “I’m not getting it”. :frowning:

I looked at your site, and can confirm the application id is being set. I tested a fake card, and do not see a 401 error, although there is another error due to an unexpected token in the JSON in the error returned from your POST attempt. Looking up the logs on our side, we did return a valid nonce, but I do not see it hitting the CreatePayment, so it must be failing somewhere in your /process-payment call, which I do not have access to or cannot see as it’s on your server.

What do you mean by “calculating the amount to be charge” → what is your logic for calculating the amount; where is it coming from? There’s this example, which shows you how to use the Orders API and grab the value from an item in the Catalog API, but it’s geared to pushing an order to the Square POS, so you’d need to extract the logic you want. Currency can be obtained via ListMerchants.

I read somewhere in the docs that you have a series of partners who can provide complete code for insertion. Please let me know their contact details so I can get this project over the line.

I wonder what code should be in the /process-payment file? The page exists but I have no idea what the API is expecting it to output. I previously thought it was the output to the user, the response from the payment process but now, I’m not so sure.

If you’d like to reach out to a solutions partner you can find them listed here: Square | Find an agency. You may also be interested in complete solutions on our marketplace already: Square App Marketplace

process-payment would be where you actually call the CreatePayment API, to charge the card that was entered on the form. In the walkthrough it can be seen in step 2.2.

Thank you sjosey,

  1. I’ve read that and copied it to the process-payment file. The error now comes from the first character ‘a’ in that file which is just as copied from the location you directed me to. I’ve looked for the createpayment API doc and what I found is simply confusing. There seems to be nothing to relate that to integrate it with that which you directed me to. I copied step 2.2 3 in the page you directed me to and then from the create payment doc I found:

I am at a loss because I can find no seamless documentation.

  1. I also need to know at what stage the actual details of a payment are to be added to server.js given that, as far as I can see, there’s nothing in the card data form being submitted, to relate to an actual order and its data in the clients db.

So, if you can provide me with the following, I should be able to make progress:-

a. the coding required by the process-payment file
b. explanation of the method and when the actual data for a specific order is to be submitted to the server.js file so the payment will relate to that specific order

I appreciate your assistance. I’m proficient in perl and php DBs, CSS AJAX etc but not so much with your APIs. Yet.

Yay, some progress made. (Reinstalled and started npm server). And some questions…

As I understand, the card form does not pass data such as order_id.
So, at what stage and in what way, is it best to send the order and payment data to server.js for use by the square system?

Why is process-payment almost (if not actually) identical to index.html?

Thanks

I can’t speak to the front end, but I send the order_id, total_money, and generated nonce to my back-end in a single request. If you want to see what that looks like, here is how I do it in my Express back end.

This script also includes a route to create an invoice instead of capturing payment, so that an unpaid order can be accessed outside of your individual application, and instead be visible in a POS. The code snippet below just contains the section that is relevant to your specific inquiry.

/**
 * Matches: POST /checkout/payment/
 *
 * Description:
 *  Take the payment information that is submitted from the /checkout/payment page,
 *  then call payment api to pay the order
 *
 *  You can learn more about the CreatePayment endpoint here:
 *  https://developer.squareup.com/reference/square/payments-api/create-payment
 *
 * Request Body:
 *  orderId: Id of the order to be updated
 *  idempotencyKey: Unique identifier for request from client
 *  nonce: Card nonce (a secure single use token) created by the Square Payment Form
 */
router.post("/payment", async (req, res, next) => {
  const {
    orderId,
    idempotencyKey,
    nonce
  } = req.body;
  try {
    // get the latest order information in case the price is changed from a different session
    const { result: { order } } = await ordersApi.retrieveOrder(orderId);
    if (order.totalMoney.amount > 0) {
      // Payment can only be made when order amount is greater than 0
      const orderRequestBody = {
        sourceId: nonce, // Card nonce created by the payment form
        idempotencyKey,
        amountMoney: order.totalMoney, // Provides total amount of money and currency to charge for the order.
        orderId: order.id, // Order that is associated with the payment
      };
    } else {
      // Settle an order with a total of 0.
      await ordersApi.payOrder(order.id, {
        idempotencyKey
      });
    }
    const { result: { payment } } = await paymentsApi.createPayment(orderRequestBody);
    const paymentParsed = JSONBig.parse(JSONBig.stringify(payment));
    res.json(
      {
          result: "Success! Order paid!",
          payment: paymentParsed
        })
  } catch (error) {
    next(error);
  }
});

Thank you very much mniaey, for taking the time.

I’m going through that to try to get a handle on it.

I’m keen to know what each of the following files does:

…/models/cart
…/util/square-client
/create-invoice
/payment

I’m guessing they (or some), may be php scripts that return JSON-formatted results?

Close - it’s a node.js app, so everything is written in Javascript, not PHP; you have the correct premise, though. It’s a simple call-and-response back end that interacts with Square’s API. It’s the equivalent of the server.js file you are referencing, but as a full standalone application for decoupled/microservices environment.

I’m still working on finishing up the documentation by adding a full walkthrough of the app, but almost all of the scripts/routes are fully commented with an explanation of what each does.

models/cart.js is used to abstract data for handling orders and parse BigInt. In Javascript, regular numbers can only go so high, and as a result, big integers are required to prevent overflow. Unfortunately, Javascript’s native JSON.parse() functions cannot handle BigInt types, so without the wrappers I made in in this file, it throws an error. You can check out more info in this thread:

util/square-client.js is the backbone of the app. This sets up credentials for accessing Square’s API, and initializes an instance of each of the required APIs (Orders, Payments, etc.)

The create-invoice and payment routes are two different paths that the checkout flow can take. If you want to capture payment right there on the spot, generate a nonce through the front-end (as you did,) and then send a POST request with that nonce, the order_id (Javascript does not play well with underscores, so order_id = orderId, location_id = locationId,) and the idempotency_key (idempotencyKey) that was generated on the checkout page.

If, on the other hand, you want the order to be visible outside of your application (i.e. in the Square dashboard or POS app) then you will need to create an invoice. Unpaid orders through the API are only visible within the app, so you can’t just create an order on a website and have someone pay for it in-store. Instead, you need to generate an invoice for that order and then access the order via the invoice to complete payment.

Let me know if you have any other questions. I would not call this app production ready, but it can at least be used as a base for testing/building your own backend, since a lot of the Square examples from GitHub are a few versions behind.

Blimey, thank you for the detailed response. It’ll take a while to believe I understand it all.

I have the sandbox version working on my port 3000.

When I say working, it works with server.js, which (as you know), is hard-coded with the values for currency and amount.

Three things I need to be sure of…

  1. How to ensure the orderId as set in the MySQL Db is sent to the gateway/processing software (either along with the payment form, so server.js can become obsolete and, instead, proper data used?

  2. How to ensure the response of the gateway (as well as any authorisation code), and the orderId are sent to a page on my server (eg https://example.com/squareup/payment-response) so I can output a receipt and mark the order as paid (with payment reference).

  3. Once it may work in sandbox (on node.js on my terminal), how can I be sure it’ll work on the live server without node.js being installed? Or does it need to be installed on the webserver as well? (Square docs inadequate throughout).

To clarify; My software handles all sales orders, invoices and receipts. I only need to have the card payments processed in PCI compliant way and for the response, authorisation code (if any) and the orderId to be sent back to my server.

Once again, thank you very much for your time.

I had the same issues as I wasn’t able to submit the form anywhere I want. The error described in the post is also present in my case too but the solutions provided didn’t help. I don’t know what to do :frowning:

This is the 401 error that you are getting @Dawidgreen? Do you have any additional information?

Yeah, this is 401 error. Haven’t noticed anything extra.

Yeah, I also had issues using the sandbox version while creating a payment form. The most significant issue was with the card payment form because the default layout shows only the value to be paid. Our website needs to have a submit button that would be dynamic (button showing the "make payment" option and the submission of a payment account).

Don’t know if I can find it somewhere in the docs, so our online gaming merchant account be a little more flexible to satisfy clients. Sometimes I also get 401 errors, but it seems that I was able to fix the issue thanks to this thread.