Google trends Public Holidays Coupon Code Code Compiler

Square Payment gateway integration using php

Mar 3, 2019

Square Payment gateway integration using php

Seamlessly integrate Square Payment Gateway into your PHP application for secure online transactions with our easy step-by-step guide.

Payment gateway integration in a PHP website is a process of connecting your website to a payment gateway service provider. This allows you to accept payments from customers directly on your website.

Square payment gateway is allows people to make money transfer through internet. And most of the eCommerce stores integrate Square payment gateway to provide online payment option. In this tutorial we will explain about the complete process of Square payment gateway integration in PHP.

Start developing with Square payment gateway in a matter of minutes. The Square gateway PHP library supports Square APIs in a language-idiomatic way that descrease the complexity without sacrificing API functionality.

Integrating Square Payment Gateway into your PHP application enables secure and seamless online transactions. Here's a step-by-step guide to help you set up Square Payment Gateway integration using PHP:

Step 1: Create a Square Developer Account

  1. Visit the Square Developer Portal ( and sign up for a developer account.
  2. Create a new application in the developer dashboard to obtain your unique application ID and other necessary credentials.

Step 2: Obtain API Credentials

  1. In your Square Developer Dashboard, navigate to the "Credentials" section.
  2. Copy the Application ID, Access Token, and Location ID. These credentials will be used to authenticate your application with Square's API.

Create a Square App from Square and get Application ID and Access Token.

Step 3: Install the Square PHP SDK

Now download the square SDK from Square SDK

Pay with a Credit Card form with test card information:

Card Number: 4532759734545858

CVV: any three non-consecutive numbers

Expiration Date: any month and year in the future

Postal Code: 94103

Let's Start Code Integration In PHP

Here, we’ll need following files to integrate Square Payment Gateway

  1. index.html
  2. sqpaymentform.js
  3. sqpaymentform-basic.css
  4. payment-process.php

Step 4: Implement Payment Form


<title>Square Payment Gateway</title>
<meta charset="utf-8">
    <!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><![endif]-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!-- link to the SqPaymentForm library -->
    <script type="text/javascript" src="">

    <!-- link to the local SqPaymentForm initialization -->
    <script type="text/javascript" src="sqpaymentform.js">

    <!-- link to the custom styles for SqPaymentForm -->
    <link rel="stylesheet" type="text/css" href="sqpaymentform-basic.css">
	 document.addEventListener("DOMContentLoaded", function(event) {
    if (SqPaymentForm.isSupportedBrowser()) {;

<div id="form-container">
  <div id="sq-ccbox">
      Be sure to replace the action attribute of the form with the path of
      the Transaction API charge endpoint URL you want to POST the nonce to
      (for example, "/process-card")
    <form id="nonce-form" novalidate action="payment-process.php" method="post">
        <span class="label">Card Number</span>
        <div id="sq-card-number"></div>

        <div class="third">
          <span class="label">Expiration</span>
          <div id="sq-expiration-date"></div>

        <div class="third">
          <span class="label">CVV</span>
          <div id="sq-cvv"></div>

        <div class="third">
          <span class="label">Postal</span>
          <div id="sq-postal-code"></div>

      <button id="sq-creditcard" class="button-credit-card" onclick="requestCardNonce(event)">Pay $1.00</button>

      <div id="error"></div>

        After a nonce is generated it will be assigned to this hidden input field.
	  <input type="hidden" id="amount" name="amount" value="100">
      <input type="hidden" id="card-nonce" name="nonce">
  </div> <!-- end #sq-ccbox -->

</div> <!-- end #form-container -->

Step 5: Set Up Payment Form Configuration


// Set the application ID
var applicationId = "APPLICATION-ID";

// Set the location ID
var locationId = "LOCATION-ID";

function buildForm(form) {
  if (SqPaymentForm.isSupportedBrowser()) {;
function buildForm1() {
    if (SqPaymentForm.isSupportedBrowser()) {
      var paymentDiv = document.getElementById("form-container");
      if ( === "none") {
 = "block";
    } else {
      // Show a "Browser is not supported" message to your buyer
 * function: requestCardNonce
 * requestCardNonce is triggered when the "Pay with credit card" button is
 * clicked
 * Modifying this function is not required, but can be customized if you
 * wish to take additional action when the form button is clicked.
function requestCardNonce(event) {

  // Don't submit the form until SqPaymentForm returns with a nonce

  // Request a nonce from the SqPaymentForm object

// Create and initialize a payment form object
var paymentForm = new SqPaymentForm({

  // Initialize the payment form elements
  applicationId: applicationId,
  locationId: locationId,
  inputClass: 'sq-input',
  autoBuild: false,

  // Customize the CSS for SqPaymentForm iframe elements
  inputStyles: [{
    fontSize: '16px',
    fontFamily: 'Helvetica Neue',
    padding: '16px',
    color: '#373F4A',
    backgroundColor: 'transparent',
    lineHeight: '24px',
    placeholderColor: '#CCC',
    _webkitFontSmoothing: 'antialiased',
    _mozOsxFontSmoothing: 'grayscale'

  // Initialize Apple Pay placeholder ID
  applePay: false,

  // Initialize Masterpass placeholder ID
  masterpass: false,

  // Initialize the credit card placeholders
  cardNumber: {
    elementId: 'sq-card-number',
    placeholder: 'XXXX XXXX XXXX XXXX'
  cvv: {
    elementId: 'sq-cvv',
    placeholder: 'CVV'
  expirationDate: {
    elementId: 'sq-expiration-date',
    placeholder: 'MM/YY'
  postalCode: {
    elementId: 'sq-postal-code',
    placeholder: '12345'

  // SqPaymentForm callback functions
  callbacks: {
     * callback function: createPaymentRequest
     * Triggered when: a digital wallet payment button is clicked.
     * Replace the JSON object declaration with a function that creates
     * a JSON object with Digital Wallet payment details
    createPaymentRequest: function () {

      return {
        requestShippingAddress: false,
        requestBillingInfo: true,
        currencyCode: "USD",
        countryCode: "US",
        total: {
          label: "MERCHANT NAME",
          amount: "100",
          pending: false
        lineItems: [
            label: "Subtotal",
            amount: "100",
            pending: false

     * 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 Javascript console
        console.log("Encountered errors:");
        errors.forEach(function (error) {
          console.log(' er= ' + error.message);

      // Assign the nonce value to the hidden form field
      document.getElementById('card-nonce').value = nonce;

      // POST the nonce form to the payment processing page


     * callback function: unsupportedBrowserDetected
     * Triggered when: the page loads and an unsupported browser is detected
    unsupportedBrowserDetected: function () {

     * callback function: inputEventReceived
     * Triggered when: visitors interact with SqPaymentForm iframe elements.
    inputEventReceived: function (inputEvent) {
      switch (inputEvent.eventType) {
        case 'focusClassAdded':
          /* HANDLE AS DESIRED */
        case 'focusClassRemoved':
          /* HANDLE AS DESIRED */
        case 'errorClassAdded':
          document.getElementById("error").innerHTML = "Please fix card information errors before continuing.";
        case 'errorClassRemoved':
          /* HANDLE AS DESIRED */
          document.getElementById("error").style.display = "none";
        case 'cardBrandChanged':
          /* HANDLE AS DESIRED */
        case 'postalCodeChanged':
          /* HANDLE AS DESIRED */

     * callback function: paymentFormLoaded
     * Triggered when: SqPaymentForm is fully loaded
    paymentFormLoaded: function () {
      console.log("The form loaded!");


* {
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;

body, html {
  color: #373F4A;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-weight: normal;

iframe {
  margin: 0;
  padding: 0;
  border: 0;

button {
  border: 0;

hr {
  height: 1px;
  border: 0;
  background-color: #CCC;

fieldset {
  margin: 0;
  padding: 0;
  border: 0;

#form-container {
  position: relative;
  width: 380px;
  margin: 0 auto;
  top: 50%;
  transform: translateY(-50%);

.label {
  font-size: 14px;
  font-weight: 500;
  line-height: 24px;
  letter-spacing: 0.5;
  text-transform: uppercase;

.third {
  float: left;
  width: calc((100% - 32px) / 3);
  padding: 0;
  margin: 0 16px 16px 0;

.third:last-of-type {
  margin-right: 0;

/* Define how SqPaymentForm iframes should look */
.sq-input {
  box-sizing: border-box;
  border: 1px solid #E0E2E3;
  border-radius: 4px;
  outline-offset: -2px;
  display: inline-block;
  -webkit-transition: border-color .2s ease-in-out, background .2s ease-in-out;
     -moz-transition: border-color .2s ease-in-out, background .2s ease-in-out;
      -ms-transition: border-color .2s ease-in-out, background .2s ease-in-out;
          transition: border-color .2s ease-in-out, background .2s ease-in-out;

/* Define how SqPaymentForm iframes should look when they have focus */
.sq-input--focus {
  border: 1px solid #4A90E2;
  background-color: rgba(74,144,226,0.02);

/* Define how SqPaymentForm iframes should look when they contain invalid values */
.sq-input--error {
  border: 1px solid #E02F2F;
  background-color: rgba(244,47,47,0.02);

#sq-card-number {
  margin-bottom: 16px;

/* Customize the "Pay with Credit Card" button */
.button-credit-card {
  width: 100%;
  height: 56px;
  margin-top: 10px;
  background: #4A90E2;
  border-radius: 4px;
  cursor: pointer;
  display: block;
  color: #FFFFFF;
  font-size: 16px;
  line-height: 24px;
  font-weight: 700;
  letter-spacing: 0;
  text-align: center;
  -webkit-transition: background .2s ease-in-out;
     -moz-transition: background .2s ease-in-out;
      -ms-transition: background .2s ease-in-out;
          transition: background .2s ease-in-out;

.button-credit-card:hover {
  background-color: #4281CB;

#error {
  width: 100%;
  margin-top: 16px;
  font-size: 14px;
  color: red;
  font-weight: 500;
  text-align: center;
  opacity: 0.8;


require 'connect-php-sdk-master/vendor/autoload.php';

$access_token = 'ACCESS-TOKEN';
# setup authorization
# create an instance of the Transaction API class
$transactions_api = new \SquareConnect\Api\TransactionsApi();
$location_id = 'LOCATION-ID';
$nonce = $_POST['nonce'];

$request_body = array (
    "card_nonce" => $nonce,
    # Monetary amounts are specified in the smallest unit of the applicable currency.
    # This amount is in cents. It's also hard-coded for $1.00, which isn't very useful.
    "amount_money" => array (
        "amount" => (int) $_POST['amount'],
        "currency" => "USD"
    # Every payment you process with the SDK must have a unique idempotency key.
    # If you're unsure whether a particular payment succeeded, you can reattempt
    # it with the same idempotency key without worrying about double charging
    # the buyer.
    "idempotency_key" => uniqid()

try {
    $result = $transactions_api->charge($location_id,  $request_body);
    // print_r($result);
	// echo '
'; if($result['transaction']['id']){ echo '

Payment success!

'; echo ""; } } catch (\SquareConnect\ApiException $e) { echo "Exception when calling TransactionApi->charge:"; var_dump($e->getResponseBody()); } ?>

Step 6: Test in Sandbox

Perform testing in the Square Sandbox environment to ensure seamless integration.

Switch to the live environment by replacing sandbox credentials with production credentials when ready.

By following these steps, you'll successfully integrate Square Payment Gateway into your PHP application, allowing for secure and efficient online transactions.

Copyright 2024. All rights are reserved