Square Payment Integration In ASP.NET MVC

Introduction

In this article, we will learn how to implement a Square payment gateway in ASP.NET Web application.

Let’s begin.

Go to https://developer.squareup.com/us/en

Click on “Get Started” to make registration. After successful registration, the below page appears.

click on create your first application and will be open a modal popup.

enter your Application Name and click on the Save button, so the below page appears.

Successfully application created.

Click on your application, below the page appears. after you will get client Id and Client Secret.

Click on OAuth Tab and get Client Id (Application ID) and Client Secret (Application Secret) and set Redirect URL.

Click on the Locations tab and get Location Id.

Set Client Id, Client Secret, and Location Id in WEB.config.

Note:

You will Get Authorization Code in Production Mode, not in sandbox Mode.

Install the package “Square” in your project.

C# Code Example

call URL and get authentication code.

window.location.href = "https://squareup.com/oauth2/authorize?client_id=" + "Enter Your Cliet Id "+ "&scope=" + "CUSTOMERS_WRITE+CUSTOMERS_READ+MERCHANT_PROFILE_READ+PAYMENTS_WRITE_ADDITIONAL_RECIPIENTS+PAYMENTS_WRITE+PAYMENTS_READ";

 

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

   private SquareClient client;

   public ActionResult Index()
   {
            
            return View();
   }

   public async Task<ActionResult> GetAuthenticationCodeAsync(string code, string response_type)
   {


      var body = new ObtainTokenRequest.Builder(
           clientId: ConfigurationManager.AppSettings["ClientId"],
          clientSecret: ConfigurationManager.AppSettings["ClientSecret"],
         grantType: "authorization_code")
                  .Code(code)
                  .Build();


      client = new SquareClient.Builder()
             .Environment(Square.Environment.Production)
             .Build();

      try
      {

          var responceaccessToken = await client.OAuthApi.ObtainTokenAsync(body: body);


      }
      catch (Exception ex)
      {
          Console.WriteLine("Failed to make the request");
          Console.WriteLine($"Exception: {ex.Message}");
      }






      return RedirectToAction("Index", "Home");

  }

 

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

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories