Payment Gateway Integration in ASP net Source Code [Free 2024]

How to integrate payment gateway in c# source code

Put simply, your customers transfer funds to you through an online payment gateway called a payment gateway.

Suppose you also search for Payment Gateway Integration in asp net c# source code. In that case, you are landing on the perfect website because we share a Stripe payment gateway integration for free in ASP C# source code. We will also share information about online payment gateways.

Before starting the integration process, learn about online payment gateways.

What Is a Payment Gateway?

A payment gateway is a technology that facilitates the transfer of payment information between a customer (sender) and a merchant (receiver), usually during an online transaction called a payment gateway.

What Is a Payment Gateway integration - Papaya Coders

Now, here are a few significant functions and components of the payment gateways:

  • Secure Connection: In this mode, a powerful, secure connection between the merchant’s website and the payment processor, such as credit card details, is encrypted and protected from unauthorized access.
  • Authorization: Authorization verifies the customer’s payment information and ensures sufficient funds are available for the transaction. This process involves communication with the customer’s issuing bank.
  • Approval or Rejection: Based on this, the bank decides whether the transaction is approved or rejected when issuing the bank response. If the bank agrees, the customer will be automatically notified (your transaction has been completed).
  • Settlement: After authorization, the payment gateway assists in the settlement process, which involves transferring funds from the customer’s bank to the merchant’s bank account (which may take a few days).
  • Reporting and management: These tools help manage transactions, view reports, handle refunds, detect chargebacks, maintain records, and analyze transaction data.

Payment Gateway Integration in ASP net

I expect you to know object-oriented programming concepts in C# and .NET Core concepts, especially MVC patterns, and get all the information from here.

You must install.NET Core 2.2 and Visual Studio if you want to do this project. You can also use any other IDE of your choice instead of Visual Studio. Also, a bonus for you is that you can find the link to the GitHub repository at the end of this article.

How to integrate payment gateway in c - Papaya Coders
Payment Gateway Integration in ASP net

Three-step of the process: How to integrate payment gateway in c# Source code; here’s an essential guide to help you get started:

  1. A form token is being requested.
  2. Embed a payment form or redirect the customer to payment.
  3. Your customer completes and submits the payment form.

Let us now see the complete process with examples, including integrate payment gateway in c# code:

Requesting the Form token:

The AcceptHosted process starts with a getHostedPaymentPageRequest API call. The response that occurs contains a form token that you can use to display the hosted payment form in a subsequent request.

The most important thing is that the form token is valid only for 15 minutes, after which the token expires.

This API call has two primary elements:

  • Transaction Request: This contains transaction information.
  • HostedPaymentSettings: This includes the settings that control the payment form for the transaction.

Transaction req Details

This transactionRequest element contains transaction details as well as values that can be used to populate form fields.

It uses child elements similar to the transactionRequest element in createTransactionRequest, which are required only for the transaction type and amount elements.

Example: var transactionRequest = new transactionRequestType

transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),
amount = objPayment.amount,


It is used to control payment forms. The table below contains all parameter settings.

ParametersSettings NameDescription
{“showEmail”: false, “requiredEmail”: false, “addPaymentProfile”: true}hostedPaymentCustomerOptionsUse showEmail to display the email field on the form and requiredEmail to make it mandatory. Both default to false. Use addPaymentProfile to allow customers to add a new payment method to their profile.
{“show”: true, “merchantName”: “XYZ”}hostedPaymentOrderOptionsUse show to display merchantName on the receipt page.

{“url”: “”}
hostedPaymentIFrameCommunicatorUrlSet url for JavaScript communication in iframe or lightbox applications.
{“show”: true, “required”: false}hostedPaymentBillingAddressOptionsUse show to display the billing address. Use required to make it mandatory.
{“show”: false, “required”: false}hostedPaymentShippingAddressOptionsUse show to display the shipping address. Use required to make it mandatory. Both default to false.
{“captcha”: false}hostedPaymentSecurityOptionsUse to enable or disable CAPTCHA security on the form.
{“apiKey”:”Your Visa SRC API key”,”displayName”:”DISPNAME”,”message”:”MESSAGE”}hostedPaymentVisaCheckoutOptionsAdds Visa SRC as a payment option.
{“cardCodeRequired”: false, “showCreditCard”: true, “showBankAccount”: true, “customerProfileId”: false}hostedPaymentPaymentOptionsUse to specify payment options on the hosted form. Defaults: card shown, CodeRequired false, customerProfileId false, showCreditCard & showBankAccount true.
{“bgColor”: “black”}hostedPaymentStyleOptionsSet accent color for form elements.
{“text”: “Pay”}hostedPaymentButtonOptionsUse to set the text on the payment button.
{“showReceipt”: true, “url”: “”, “urlText”: “Continue”, “cancelUrl”: “”, “cancelUrlText”: “Cancel”}hostedPaymentReturnOptionsControl receipt page, return URLs, and buttons for payment form and receipt.

Implementing Authorized.NET Accept Hosted Payment Transaction within ASP.NET MVC.


public class PaymentModel
public string token { get; set; }
public string actionURl { get; set; }
public decimal amount { get; set; }

MVC View – DoPayment.CSHTML

@model PaymentModel
ViewBag.Title = “payment”;
Layout = null;
@*<div id=”iframe_holder” class=”center-block” style=”width:90%;max-width: 1000px”>
<iframe id=”add_payment” class=”embed-responsive-item panel” name=”add_payment” height=”200%” width=”100%” frameborder=”0″ scrolling=”no” hidden=”true”></iframe>
<form name=”formpaynow” id=”formpaynow” method=”post” action=@Model.actionURl >
<input type=”hidden” value=”@Model.token” id=”token” name=”token” />
<script src=”~/Scripts/jquery-1.10.2.js”></script>
<script type=”text/javascript”>
$(document).ready(function () {
var form = $(“form”);
//$(window).scrollTop($(‘#add_payment’).offset().top – 50);

MVC Controller File

public ActionResult DoPayment()
PaymentModel objPayment = new PaymentModel();
objPayment.amount = Convert.ToDecimal(50);
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNet.Environment.SANDBOX;
objPayment.actionURl = ConfigurationManager.AppSettings[“PaymentURL”]; ////””;
// define the merchant information (authentication / transaction id)
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType()
name = ConfigurationManager.AppSettings[“APILoginId”],//”4J7Z4ymG”,
ItemElementName = ItemChoiceType.transactionKey,
Item = ConfigurationManager.AppSettings[“TransactionKey”] //// “8sM38B8v2Wwcs354”,
settingType[] settings = new settingType[10];
settings[0] = new settingType();
settings[0].settingName = settingNameEnum.hostedPaymentBillingAddressOptions.ToString();
settings[0].settingValue = “{\”show\”: true , \”required\”: true }”;
settings[1] = new settingType();
settings[1].settingName = settingNameEnum.hostedPaymentButtonOptions.ToString();
settings[1].settingValue = “{\”text\”: \”Pay\”}”;
settings[2] = new settingType();
settings[2].settingName = settingNameEnum.hostedPaymentCustomerOptions.ToString();
settings[2].settingValue = “{\”showEmail\”: true ,\”requiredEmail\”: true }”;
settings[3] = new settingType();
settings[3].settingName = settingNameEnum.hostedPaymentOrderOptions.ToString();
settings[3].settingValue = “{\”show\”: true }”;
settings[4] = new settingType();
settings[4].settingName = settingNameEnum.hostedPaymentPaymentOptions.ToString();
settings[4].settingValue = “{\”cardCodeRequired\”: false }”;
settings[5] = new settingType();
settings[5].settingName = settingNameEnum.hostedPaymentReturnOptions.ToString();
settings[5].settingValue = “{\”showReceipt\”: true ,\”url\”:\”” + Request.Url.AbsoluteUri.Replace(“DoPayment”, “RedirectFromPayment”) + “\”,\”urlText\”:\”Continue\”,\”cancelUrl\”:\”” + Request.Url.AbsoluteUri.Replace(“DoPayment”, “CancelFromPaypal”) + “\”,\”cancelUrlText\”:\”Cancel\”}”;
settings[6] = new settingType();
settings[6].settingName = settingNameEnum.hostedPaymentSecurityOptions.ToString();
settings[6].settingValue = “{\”captcha\”: false }”;
settings[7] = new settingType();
settings[7].settingName = settingNameEnum.hostedPaymentShippingAddressOptions.ToString();
settings[7].settingValue = “{\”show\”: false ,\”required\”: false }”;
settings[8] = new settingType();
settings[8].settingName = settingNameEnum.hostedPaymentStyleOptions.ToString();
settings[8].settingValue = “{\”bgColor\”: \”red\”}”;
var orderType = new orderType
description = “Product Registrtion”,
var transactionRequest = new transactionRequestType
transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),    // charge the card
amount = objPayment.amount,
order = orderType,
var request = new getHostedPaymentPageRequest();
request.transactionRequest = transactionRequest;
request.hostedPaymentSettings = settings;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
// instantiate the contoller that will call the service
var controller = new getHostedPaymentPageController(request);
// get the response from the service (errors contained if any)
var response = controller.GetApiResponse();
if (response != null && response.messages.resultCode == messageTypeEnum.Ok)
objPayment.token = response.token;
return View(“DoPayment “, objPayment);
} catch (Exception ex)
return Json( new { success = false , message = ex.Message });
public ActionResult RedirectFromPayment ()
// This method calls when payment get success for sure. Write the code after payment successfull
public ActionResult CancelFromPaypal ()
{     // This method calls when payment get cancel or not success. Write the code of cancelation or warning


What is the best payment gateway for small businesses?

Stripe and PayPal are excellent payment gateways for small businesses.

Can I use multiple payment gateways in one project?

Yes, you can integrate multiple payment gateways.

What are the costs associated with payment gateway integration?

Costs include transaction fees, setup fees, and possibly monthly fees.

Also checkout Phone pay Getway integration method:


Overall, this article covers a payment gateway for testing purposes using ASP.NET Core, but with the right tools and knowledge, it becomes manageable. Stay updated with the latest trends and continuously improve your integration to meet evolving standards.

You can start your journey with Papaya Coders Pvt Ltd towards help to create a website, apps and software. You can grow your company by contacting us online or at +916392806939 today!

Tags :

Latest Post

Your Cart

No Item Found