Payment Integrations

How To Create Payment Using Square In ASP.NET MVC

In this article, we will learn how to Create a Payment using Square in ASP.NET Web application.

Let’s begin.

Please read this article first of all here.

 

Create payment

Charges a payment source, for example, a card represented by the customer’s card on file or a card nonce. In addition to the payment source, the request must also include the amount to accept for the payment.

C# Code Example

Open the Index.cshtml and add the below code in it.

            <link href="~/fonts/sq-payment-form.css" rel="stylesheet" />                       
       <div id="sq-ccbox">

                          <form id="nonce-form" novalidate>

                              <div class="sq-field">
                                  <label class="sq-label">Card Number</label>
                                  <div id="sq-card-number" class="txtclass"></div>
                               
                              </div>

                              <div class="sq-field-wrapper">
                                  <div class="sq-field sq-field--in-wrapper">
                                      <label class="sq-label">CVV</label>
                                      <div id="sq-cvv" class="txtclass"></div>
                                     
                                  </div>
                                  <div class="sq-field sq-field--in-wrapper">
                                      <label class="sq-label">Expiration</label>
                                      <div id="sq-expiration-date" class="txtclass"></div>
                                     
                                  </div>
                                  <div class="sq-field sq-field--in-wrapper">
                                      <label class="sq-label">Postal</label>
                                      <div id="sq-postal-code" class="txtclass"></div>
                                     
                                  </div>
                              </div>
                              
                              <div id="error"></div>
                              <input type="hidden" id="card-nonce" name="nonce">
                          </form>
                      </div>
  <div>
   <a class="btn indigo waves-effect waves-light right sq-button" id="sq-creditcard" name="action" 
                                                        >

Open the  sq-payment-form.js and add the below code in it.

var applicationid, locationId;
applicationid = "Your Application Id";
locationId = "Your Location Id";
function onGetCardNonce(event) {
       paymentForm.requestCardNonce();
}

var paymentForm = new SqPaymentForm({

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

    // Customize the CSS for SqPaymentForm iframe elements
    inputStyles: [{
        backgroundColor: 'transparent',
        color: '#333333',
        fontFamily: '"Helvetica Neue", "Helvetica", sans-serif',
        fontSize: '16px',
        fontWeight: '400',
        placeholderColor: '#8594A7',
        placeholderFontWeight: '400',
        padding: '16px',
        _webkitFontSmoothing: 'antialiased',
        _mozOsxFontSmoothing: 'grayscale'
    }],

    // Initialize Google Pay button ID
    googlePay: {
        elementId: 'sq-google-pay'
    },

    // Initialize Apple Pay placeholder ID
    applePay: {
        elementId: 'sq-apple-pay'
    },

    // Initialize Masterpass placeholder ID
    masterpass: {
        elementId: 'sq-masterpass'
    },

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

    // SqPaymentForm callback functions
    callbacks: {

        /*
         * callback function: methodsSupported
         * Triggered when: the page is loaded.
         */        methodsSupported: function (methods) {
            if (!methods.masterpass && !methods.applePay && !methods.googlePay) {
                var walletBox = document.getElementById('sq-walletbox');
                walletBox.style.display = 'none';
            } else {
                var walletBox = document.getElementById('sq-walletbox');
                walletBox.style.display = 'block';
            }

            // Only show the button if Google Pay is enabled
            if (methods.googlePay === true) {
                var googlePayBtn = document.getElementById('sq-google-pay');
                googlePayBtn.style.display = 'inline-block';
            }

            // Only show the button if Apple Pay for Web is enabled
            if (methods.applePay === true) {
                var applePayBtn = document.getElementById('sq-apple-pay');
                applePayBtn.style.display = 'inline-block';
            }

            // Only show the button if Masterpass is enabled
            if (methods.masterpass === true) {
                var masterpassBtn = document.getElementById('sq-masterpass');
                masterpassBtn.style.display = 'inline-block';
            }
        },

        /*
         * callback function: createPaymentRequest
         * Triggered when: a digital wallet payment button is clicked.
         */        createPaymentRequest: function () {

            //var paymentRequestJson = {
            //    requestShippingAddress: false,
            //    requestBillingInfo: true,
            //    shippingContact: {
            //        familyName: "CUSTOMER LAST NAME",
            //        givenName: "CUSTOMER FIRST NAME",
            //        email: "mycustomer@example.com",
            //        country: "USA",
            //        region: "CA",
            //        city: "San Francisco",
            //        addressLines: [
            //            "1455 Market St #600"
            //        ],
            //        postalCode: "94103",
            //        phone: "14255551212"
            //    },
            //    currencyCode: "USD",
            //    countryCode: "US",
            //    total: {
            //        label: "MERCHANT NAME",
            //        amount: "1.00",
            //        pending: false
            //    },
            //    lineItems: [
            //        {
            //            label: "Subtotal",
            //            amount: "1.00",
            //            pending: false
            //        }
            //    ]
            //};

            return paymentRequestJson;
        },

        /*
         * callback function: validateShippingContact
         * Triggered when: a shipping address is selected/changed in a digital
         *                 wallet UI that supports address selection.
         */        validateShippingContact: function (contact) {

            var validationErrorObj;
            /* ADD CODE TO SET validationErrorObj IF ERRORS ARE FOUND */            return validationErrorObj;
        },

        /*
         * callback function: cardNonceResponseReceived
         * Triggered when: SqPaymentForm completes a card nonce request
         */        cardNonceResponseReceived: function (errors, nonce, cardData, billingContact, shippingContact) {


            if (errors) {
                var error_html = "";
                for (var i = 0; i < errors.length; i++) {
                    error_html += "<li> " + errors[i].message + " </li>";
                }
                document.getElementById("error").innerHTML = error_html;
                document.getElementById('sq-creditcard').disabled = false;

                return;
            } else {
                document.getElementById("error").innerHTML = "";
            }

            // Assign the nonce value to the hidden form field
            document.getElementById('card-nonce').value = nonce;
            //alert(nonce);
         
         
            $.ajax({
                type: "POST",
                url: "/Home/SavefrmReceivePaymentCreditCardAsync",
                data: {  "nonce": nonce },
                success: function (result) {
                                       if (result.IsSuccess) {

                        M.toast({ html: "Successfully Charged CC", classes: 'rounded toast-success' });
                      
                    }
                    else {
                        
                        M.toast({ html: result.Message, classes: 'rounded toast-danger' });
                    }
                },
                error: function (err) {
                   
                    M.toast({ html: "Something Went Wrong.", classes: 'rounded toast-danger' });
                }

            });
            // 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':
                    /* HANDLE AS DESIRED */                    break;
                case 'errorClassRemoved':
                    /* HANDLE AS DESIRED */                    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 */        }
    }
});

Open the HomeController.cshtml and add the below code in it.

private SquareClient client;
public ActionResult Index()
{

      
       return View();
}
public async System.Threading.Tasks.Task<JsonResult> SavefrmReceivePaymentCreditCardAsync(string nonce)
   {
       try
       {
           client = new SquareClient.Builder()
                  .Environment(Square.Environment.Sandbox)
                  .AccessToken("Your Access Token")
                  .Build();

           
           var amountMoney = new Money.Builder()
                 .Amount(200L)
                 .Currency("USD")
                 .Build();
           string idempotencyKey = NewIdempotencyKey();
           var appFeeMoney = new Money.Builder()
             .Amount(10L)
             .Currency("USD")
             .Build();

           var body = new CreatePaymentRequest.Builder(
               sourceId: nonce,
               idempotencyKey: idempotencyKey,
               amountMoney: amountMoney)
             .AppFeeMoney(appFeeMoney)
             .Autocomplete(true)
             .Build();
           return Json(new { IsSuccess = true }, JsonRequestBehavior.AllowGet);
       }
       catch (Exception)
       {

           return Json(new { IsSuccess = false }, JsonRequestBehavior.AllowGet);
       }
     

   }
   private static string NewIdempotencyKey()
   {
       return Guid.NewGuid().ToString();
   }

if you have any questions or issues about this article, please let me know.

 

Sagar Rana

Sagar Rana is a Web Developer in Vision Infotech. He has strong skills and knowledge of ASP.NET C#, ASP.NET MVC, .Net Core, Jquery, JavaScript, WEB API, React.js, ADO.Net, Entity Framework, SQL and different integration like Xero, Stripe, Zoho CRM, Square, PayTM, PayKUN, RazorPay, Quickbook Desktop etc.

View Comments

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago