title: Square Payment Gateway integration in PHP website doesn't redirect to payment portal
body: <p>I m trying Square payment gateway using the API code found in the below URL </p>
  
  <p>[<a href="http://significanttechno.com/square-payment-gateway-integration-using-php]" rel="nofollow noreferrer">http://significanttechno.com/square-payment-gateway-integration-using-php]</a></p>
  
  <p>However, although i have replicated and tried to test the same code in my server, nothing seems to work.</p>
  
  <p>The form doesn't allow me to input card details, and even if i add input tags to it and try to submit the form it doesn't redirect to action page..</p>
  
  <p>The code goes as:</p>
  
  <p><strong>Index.php</strong></p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;
  &lt;title&gt;Square Payment Gateway&lt;/title&gt;
  &lt;meta charset="utf-8"&gt;
      &lt;!--[if IE]&gt;&lt;meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"&gt;&lt;![endif]--&gt;
      &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
  
      &lt;!-- link to the SqPaymentForm library --&gt;
      &lt;script type="text/javascript" src="https://js.squareup.com/v2/paymentform"&gt;
      &lt;/script&gt;
  
      &lt;!-- link to the local SqPaymentForm initialization --&gt;
      &lt;script type="text/javascript" src="sqpaymentform.js"&gt;
      &lt;/script&gt;
  
      &lt;!-- link to the custom styles for SqPaymentForm --&gt;
      &lt;link rel="stylesheet" type="text/css" href="sqpaymentform-basic.css"&gt;
      &lt;script&gt;
       document.addEventListener("DOMContentLoaded", function(event) {
      if (SqPaymentForm.isSupportedBrowser()) {
        paymentForm.build();
        paymentForm.recalculateSize();
      }
    });
      &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
  
  &lt;div id="form-container"&gt;
    &lt;div id="sq-ccbox"&gt;
      &lt;!--
        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")
      --&gt;
      &lt;form id="nonce-form" novalidate action="payment-process.php" method="post"&gt;
        &lt;fieldset&gt;
          &lt;span class="label"&gt;Card Number&lt;/span&gt;
          &lt;div id="sq-card-number"&gt;&lt;/div&gt;
  
          &lt;div class="third"&gt;
            &lt;span class="label"&gt;Expiration&lt;/span&gt;
            &lt;div id="sq-expiration-date"&gt;&lt;/div&gt;
          &lt;/div&gt;
  
          &lt;div class="third"&gt;
            &lt;span class="label"&gt;CVV&lt;/span&gt;
            &lt;div id="sq-cvv"&gt;&lt;/div&gt;
          &lt;/div&gt;
  
          &lt;div class="third"&gt;
            &lt;span class="label"&gt;Postal&lt;/span&gt;
            &lt;div id="sq-postal-code"&gt;&lt;/div&gt;
          &lt;/div&gt;
        &lt;/fieldset&gt;
  
        &lt;button id="sq-creditcard" class="button-credit-card" onclick="requestCardNonce(event)"&gt;Pay $1.00&lt;/button&gt;
  
        &lt;div id="error"&gt;&lt;/div&gt;
  
        &lt;!--
          After a nonce is generated it will be assigned to this hidden input field.
        --&gt;
        &lt;input type="hidden" id="amount" name="amount" value="100"&gt;
        &lt;input type="hidden" id="card-nonce" name="nonce"&gt;
      &lt;/form&gt;
    &lt;/div&gt; &lt;!-- end #sq-ccbox --&gt;
  
  &lt;/div&gt; &lt;!-- end #form-container --&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p><strong>sqpaymentform.js</strong></p>
  
  <pre><code>// Set the application ID
  var applicationId = "APPLICATION-ID";
  
  // Set the location ID
  var locationId = "LOCATION-ID";
  
  
  function buildForm(form) {
    if (SqPaymentForm.isSupportedBrowser()) {
      form.build();
      form.recalculateSize();
    }
  }
  function buildForm1() {
      if (SqPaymentForm.isSupportedBrowser()) {
        var paymentDiv = document.getElementById("form-container");
        if (paymentDiv.style.display === "none") {
            paymentDiv.style.display = "block";
        }
        paymentform.build();
        paymentform.recalculateSize();
      } 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
    event.preventDefault();
  
    // Request a nonce from the SqPaymentForm object
    paymentForm.requestCardNonce();
  }
  
  // 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);
            alert(error.message);
          });
  
          return;
        }
        // Assign the nonce value to the hidden form field
        document.getElementById('card-nonce').value = nonce;
  
        // POST the nonce form to the payment processing page
        document.getElementById('nonce-form').submit();
  
      },
  
      /*
       * callback function: unsupportedBrowserDetected
       * Triggered when: the page loads and an unsupported browser is detected
       */
      unsupportedBrowserDetected: function () {
        /* PROVIDE FEEDBACK TO SITE VISITORS */
      },
  
      /*
       * callback function: inputEventReceived
       * Triggered when: visitors interact with SqPaymentForm iframe elements.
       */
      inputEventReceived: function (inputEvent) {
        switch (inputEvent.eventType) {
          case 'focusClassAdded':
            /* HANDLE AS DESIRED */
            break;
          case 'focusClassRemoved':
            /* HANDLE AS DESIRED */
            break;
          case 'errorClassAdded':
            document.getElementById("error").innerHTML = "Please fix card information errors before continuing.";
            break;
          case 'errorClassRemoved':
            /* HANDLE AS DESIRED */
            document.getElementById("error").style.display = "none";
            break;
          case 'cardBrandChanged':
            /* HANDLE AS DESIRED */
            break;
          case 'postalCodeChanged':
            /* HANDLE AS DESIRED */
            break;
        }
      },
  
      /*
       * callback function: paymentFormLoaded
       * Triggered when: SqPaymentForm is fully loaded
       */
      paymentFormLoaded: function () {
        /* HANDLE AS DESIRED */
        console.log("The form loaded!");
      }
    }
  });
  </code></pre>
  
  <p><strong>payment-process.php</strong></p>
  
  <pre><code>&lt;?php 
  require 'vendor/autoload.php';
  
  $access_token = 'ACCESS-TOKEN';
  # setup authorization
  \SquareConnect\Configuration::getDefaultConfiguration()-&gt;setAccessToken($access_token);
  # 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" =&gt; $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" =&gt; array (
          "amount" =&gt; (int) $_POST['amount'],
          "currency" =&gt; "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" =&gt; uniqid()
  );
  
  try {
      $result = $transactions_api-&gt;charge($location_id,  $request_body);
      // print_r($result);
  
      // echo '';
      if($result['transaction']['id']){
          echo 'Payment success!';
          echo "Transation ID: ".$result['transaction']['id']."";
      }
  } catch (\SquareConnect\ApiException $e) {
      echo "Exception when calling TransactionApi-&gt;charge:";
      var_dump($e-&gt;getResponseBody());
  }
  ?&gt;
  </code></pre>
  
  <p>Please note that i have download the <strong>"Square SDK"</strong> as mentioned and added <strong>location ID and Access token</strong> from Square account. </p>
  
  <p>Any help is greatly appreciated..</p>