This is a premium alert message you can set from Layout! Get Now!

Getting started with the Square Node.js SDK

0

Square is a full-scale business application that enables organizations to run and grow their ecommerce business, manage payroll, and run business banking services. Square allows for the integration of numerous third-party applications relating to analytics, tax, accounting, team management, and more.

This article will demonstrate how to use the Square Node.js SDK to easily integrate Square’s credit card processing functionality into an application. By the end of this tutorial, you’ll have a working code you can start using to take advantage of the many features the Square SDK has to offer.

N.B.there is a depreciated Square Connect SDK that is no longer supported and should not be used; in fact, most of the functions in this tutorial can not be found in the depreciated version

Jump ahead:

Prerequisites

To follow along with this tutorial, you’ll need the following:

  • Node.js v12 or higher installed
  • Familiarity with React and Vite or Create React App

What is the Square SDK?

To better understand what the Square SDK is, let’s first quickly review the definitions of APIs and SDKs.

An API is an intermediary that enables applications to access each other’s capabilities and send information. Application programming interfaces enhance the functionality of applications.

Meanwhile, an SDK is a set of tools that allows you to access an application’s functionalities and services, including its APIs. Software development kits simplify app development by equipping you with almost everything you need to kickstart your development, allowing you to focus on your application business logic.

The Square SDK enables you to easily integrate Square into your application. In this tutorial, you’ll see that with the Square SDK you don’t need to concern yourself with how to call an API endpoint or worry about how Square processes your payment. You just need to know what SDK functions are required and what data the SDK is expecting in order complete an order.

Setting up Square

To explore and use Square’s suite of business tools, we’ll need to set up a Square account and get an Application ID, Location ID, and an Access token. These credentials are required to use the Square SDK.

Start by signing up on the Square website as a developer and get your credentials. For this tutorial, we’ll be using the Sandbox environment so, ensure you get the Sandbox credentials to follow along.

Log into your dashboard and click on the Credentials tab to view your Application ID and your Access token. To get your Location ID, click on the Locations tab as shown below.

Locations Tab

Integrating with a Node.js backend (server)

It’s important to note that the Square Node.js SDK should only be used in the backend. There are frontend integrations for the Square SDK that we’ll review later in this article.

To start, we’ll create a basic server with Fastify, an open source Node.js framework.

First, initialize the application using the yarn init command. Then, update the package.json file to include the following dependencies:

"dependencies": {
    "@fastify/cors": "^7.0.0",
    "dotenv": "^16.0.1",
    "fastify": "^3.29.0",
    "square": "^19.0.0",
    "uuid4": "^2.0.2"
  }

Now, run the command yarn on your terminal to install the dependencies.

Next, create an index.js file. This will be the main file and also the server file. Add the following code:

const { fastify } = require('fastify');
const PORT = 3001;

const app = fastify();
async function startApp() {
    try {
        app.register(require('@fastify/cors'), {
            origin: '*',
        });
        app.post("/pay", async (request, reply) => {
            // our logic will go here.
        });
        await app.listen(PORT);
        console.log('listening on port', PORT);
    } catch (e) {
        console.error(e);
    }
}
startApp();

This code will set up a server for us on PORT 3001 with a post route /pay.

Next, add your Square integration code. In order to keep the code clean, create a new file called square.connect.js. Now, add the following:

const dotenv = require('dotenv');
const { Client, Environment } = require("square");
dotenv.config();

const client = new Client({
  accessToken: process.env.SQUARE_ACCESS_TOKEN,
  environment: Environment.Sandbox,
});

module.exports = client;

This code will initialize Square and then allow you to authenticate your account with your access token. Without this setup, you’ll be unable to access Square.

Be sure to add your Square Access token to your .env file using this key: SQUARE_ACCESS_TOKEN.

Next, modify the index file, import uuidv4, and the Square client you just initialized. Also, modify the /pay endpoint to include the payment API function.

const { fastify } = require('fastify');
const uuidv4 = require('uuid4');
const { paymentsApi } = require("./connect.square.js");
const PORT = 3001;
const app = fastify();

async function startApp() {
    try {
        app.register(require('@fastify/cors'), {
            origin: '*',
        });
        app.post("/pay", async (request, reply) => {
            let body = request.body;
            body.idempotencyKey = uuidv4();
            body.amountMoney = {
                amount: 1,
                currency: 'GBP',
            };
            let paymentResponse = paymentsApi.createPayment(body);
            paymentResponse.then((response) => {
                console.log(response)
                reply.send(response)
            })
        });
        await app.listen(PORT);
        console.log('listening on port', PORT);
    } catch (e) {
        console.error(e);
    }
}
startApp();

If you examine the code carefully, you’ll notice a key called idempotencyKey. This is a requirement that prevents a user from making duplicate transactions; no transaction can have more than one idempotencyKey.

Normally, you’d generate and store this key in your database to validate a transaction, but for this tutorial, we’ll use a universally unique identifier, uuidv4, to generate this key and then use it to make payments.

Also, you’ll notice that the amountMoney is an object. This is also a compulsory requirement as every payment must have an amount to pay. To avoid exploitation, you should get this value from your database, rather than sending it from the frontend. But for the purpose of this tutorial, we’ll hard code the amountMoney:

body.amountMoney = {
    amount: 1,
    currency: 'GBP',
};

You can use any of Stripe’s supported currencies but for the sandbox account, only GBP is supported.

With this data in the backend, along with one payload from the client, you should be able to create a payment by calling the createPayment() method.

paymentsApi.createPayment(body)

Now that we’ve set up the Node.js backend and integrated the Square Node.js SDK, let’s integrate it with a client.

Integrating with a React app (client)

Let’s create a basic React app that will accept user credit card information and payments.

It is preferable to use Vite to set up the React app, but if you prefer you can set up the app with Create React App.

Next, install the Square React community-powered web payment SDK, react-square web-payments-sdk, by running the following command:

yarn add react-square-web-payments-sdk

Now that you have React set up and the SDK installed, create a component, SqurePayment.jsx, and add the following code:

import * as React from 'react';
import { CreditCard, PaymentForm } from 'react-square-web-payments-sdk';
const SquarePaymentForm = () => (
   {
      console.info({ token, buyer });
      let body = JSON.stringify({
        sourceId: token.token
      });
      const paymentResponse = await fetch('http://localhost:3001/pay', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body,
      });
      if (paymentResponse.ok) {
        return paymentResponse.json();
      }
    }}

    /**
     * This function enables the Strong Customer Authentication (SCA) flow
     *
     * It's important you use this function to verify a user to reduce the 
     * chances of fraudulent transactions
     */

    createVerificationDetails={() => ({
      amount: '1.00',
      /* collected from the buyer */
      billingContact: {
        addressLines: ['123 Main Street', 'Apartment 1'],
        familyName: 'Doe',
        givenName: 'John',
        countryCode: 'GB',
        city: 'London',
      },
      currencyCode: 'GBP',
      intent: 'CHARGE',
    })}
    /**
     * Identifies the location of the merchant that is taking the payment.
     */
    locationId="LPWYFGdds9"
  >
    
  
);
export default SquarePaymentForm;

Here we use the PaymentForm and Card components to collect the user’s credit card details and payment information to then send it to Square.

Import this component in the App.jsx file and render it as shown below:

import SquarePaymentForm from './SquarePayment'
import { Button, Container } from 'react-bootstrap';
import './App.css'
function App() {
  return (
    <Container>
      <h1>My Payment Page</h1>
      <p>
        Ensure you enter the correct test card details from <a href="https://developer.squareup.com/docs/devtools/sandbox/payments" target="_blank">here</a>
      </p>
      <p>
        <SquarePaymentForm  />
      </p>
    </Container>
  )
}
export default App

It should look like this:

My Payment Page

You can create a form to collect the user’s billing information as well:

billingContact: {
  addressLines: ['123 Main Street', 'Apartment 1'],
  familyName: 'Doe',
  givenName: 'John',
  countryCode: 'GB',
  city: 'London',
},

Now, make the API call to your server, which will make a request to the Square server and return a response. Remember that we created the /pay endpoint earlier; the request should be there with all the information as shown in the code above.

Conclusion

Square’s SDK for Node.js gives you the power to use the Square API effortlessly. You just have to focus on calling functions, passing data around, and manipulating the response. I hope you found this article helpful for getting started with integrating Square into your Node.js workflow.

The Square Node.js SDK offers many features that can be advantageous for improving the effectiveness of ecommerce business operations. Check out the documentation to learn more about all the things you can do with the Square SDK.

You can find all the code used in this tutorial in the following GitHub repositories:

 

The post Getting started with the Square Node.js SDK appeared first on LogRocket Blog.



from LogRocket Blog https://ift.tt/DRQNL67
via Read more

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment

Search This Blog

To Top