Authorized.net Integrate Payment Gateway within Asp.net MVC – Accept Hosted

Accept Hosted:

Accept Hosted is a mobile-optimized payment form hosted by Authorize.Net. It enables you to use the Authorize.Net API to submit payment transactions while maintaining SAQ-A level PCI compliance. You can redirect customers to the Accept Hosted payment form or embed the payment form directly in your own page.

Overview:

How to Integrate Payment Gateway in Asp.net

There are three step of process: How to integrate payment gateway in asp.net c#

  1. Requesting the form token.
  2. Embed the payment form or redirect the customer to the payment form by sending an HTML POST containing the form token.
  3. Your customer completes and submits the payment form. The API sends the transaction to Authorize.Net for processing. The customer is returned to your site, which displays a result page based on the URL followed or the response details sent.

Now we will see the whole process with the example including the code:

Requesting the Form token:

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

Note that Form token is Valid for 15 minutes only.

This API call contains two primary element :

  1. Transaction Request: it contains transaction information.
  2. HostedPaymentSettings: It contains the settings that control the Payment form for the transaction.
TRANSACTION REQUEST DETAIL

The transactionRequest element contains transaction details and values that can be used to populate the form fields. It uses the same child elements as the transactionRequest element in createTransactionRequest. Only the transactionType and amount elements are required.

Example:    var transactionRequest = new transactionRequestType

  1. {
  2. transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),
  3. amount = objPayment.amount,
  4. };
HOSTED FORM PARAMETER SETTINGS

This is use to control the payment form. There is one element HostedPaymentSettings within the getHostedPaymentPageRequest API call. Below table contains the all the parameters settings. The values for all parameters sent within hostedPaymentSettings are sent as JSON objects, regardless of whether you sent the getHostedPaymentPageRequest API call in JSON or XML format.

Settings Name Parameters Description
hostedPaymentReturnOptions {“showReceipt”: true, “url”: “https://mysite.com/receipt”, “urlText”: “Continue”, “cancelUrl”: “https://mysite.com/cancel”, “cancelUrlText”: “Cancel”} Use these options to control the receipt page, return URLs, and buttons for both the payment form and the receipt page.
hostedPaymentButtonOptions {“text”: “Pay”} Use to set the text on the payment button.
hostedPaymentStyleOptions {“bgColor”: “red”} Use to set the accent color of the form, including button and field line colors.
hostedPaymentPaymentOptions {“cardCodeRequired”: false, “showCreditCard”: true, “showBankAccount”: true, “customerProfileId”: false} Use to control which payment options to display on the hosted payment form. By Default card CodeRequired and customerProfileId are false, and showCreditCard and showBankAccount are true.
hostedPaymentVisaCheckoutOptions {“apiKey”:”Your Visa SRC API key”,”displayName”:”DISPNAME”,”message”:”MESSAGE”} Adds Visa SRC as a payment option.
hostedPaymentSecurityOptions {“captcha”: false} Use to enable or disable CAPTCHA security on the form. Defaults to false.
hostedPaymentShippingAddressOptions {“show”: false, “required”: false} Use show to enable or disable the shipping address on the form. Use required to require the shipping address. Both show and required default to false.
hostedPaymentBillingAddressOptions {“show”: true, “required”: false} Use show to enable or disable the billing address on the form. Defaults to true. Use required to require the billing address. Defaults to false.
hostedPaymentCustomerOptions {“showEmail”: false, “requiredEmail”: false, “addPaymentProfile”: true} Use showEmail to enable or disable the email address on the form. Use requiredEmail to require the email address. Both showEmail and requiredEmail default to false.Use addPaymentProfile to enable the customer to add a new form of payment to their customer profile.
hostedPaymentOrderOptions {“show”: true, “merchantName”: “XYZ”} Use show to enable or disable the display of merchantName on the hosted receipt page. Defaults to true. Use merchantName to define how the merchant name appears on the receipt.
hostedPaymentIFrameCommunicatorUrl {“url”: “https://mysite.com/IFrameCommunicator.html”} Use url to set the URL of a page that can communicate with the merchant’s site using JavaScript. Required for iframe or lightbox applications.

What is ASP.NET Web API and How it works?

Below is the Code example to implement Authorized.net Accept Hosted Payment Transaction within asp.net mvc

PaymentModel.CS:
  1. public class PaymentModel
  2. {
  3. public string token { get; set; }
  4. public string actionURl { get; set; }
  5. public decimal amount { get; set; }
  6. }
MVC Controller File
  1. public ActionResult DoPayment()
  2. {
  3. try
  4. {
  5. PaymentModel objPayment = new PaymentModel();
  6. objPayment.amount = Convert.ToDecimal(50);
  7. ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNet.Environment.SANDBOX;
  8. objPayment.actionURl = ConfigurationManager.AppSettings[“PaymentURL”]; ////”https://test.authorize.net/payment/payment”;
  9. // define the merchant information (authentication / transaction id)
  10. ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType()
  11. {
  12. name = ConfigurationManager.AppSettings[“APILoginId”],//”4J7Z4ymG”,
  13. ItemElementName = ItemChoiceType.transactionKey,
  14. Item = ConfigurationManager.AppSettings[“TransactionKey”] //// “8sM38B8v2Wwcs354”,
  15. };
  16. settingType[] settings = new settingType[10];
  17. settings[0] = new settingType();
  18. settings[0].settingName = settingNameEnum.hostedPaymentBillingAddressOptions.ToString();
  19. settings[0].settingValue = “{\”show\”: true , \”required\”: true }”;
  20. settings[1] = new settingType();
  21. settings[1].settingName = settingNameEnum.hostedPaymentButtonOptions.ToString();
  22. settings[1].settingValue = “{\”text\”: \”Pay\”}”;
  23. settings[2] = new settingType();
  24. settings[2].settingName = settingNameEnum.hostedPaymentCustomerOptions.ToString();
  25. settings[2].settingValue = “{\”showEmail\”: true ,\”requiredEmail\”: true }”;
  26. settings[3] = new settingType();
  27. settings[3].settingName = settingNameEnum.hostedPaymentOrderOptions.ToString();
  28. settings[3].settingValue = “{\”show\”: true }”;
  29. settings[4] = new settingType();
  30. settings[4].settingName = settingNameEnum.hostedPaymentPaymentOptions.ToString();
  31. settings[4].settingValue = “{\”cardCodeRequired\”: false }”;
  32. settings[5] = new settingType();
  33. settings[5].settingName = settingNameEnum.hostedPaymentReturnOptions.ToString();
  34. settings[5].settingValue = “{\”showReceipt\”: true ,\”url\”:\”” + Request.Url.AbsoluteUri.Replace(“DoPayment”, “RedirectFromPayment”) + “\”,\”urlText\”:\”Continue\”,\”cancelUrl\”:\”” + Request.Url.AbsoluteUri.Replace(“DoPayment”, “CancelFromPaypal”) + “\”,\”cancelUrlText\”:\”Cancel\”}”;
  35. settings[6] = new settingType();
  36. settings[6].settingName = settingNameEnum.hostedPaymentSecurityOptions.ToString();
  37. settings[6].settingValue = “{\”captcha\”: false }”;
  38. settings[7] = new settingType();
  39. settings[7].settingName = settingNameEnum.hostedPaymentShippingAddressOptions.ToString();
  40. settings[7].settingValue = “{\”show\”: false ,\”required\”: false }”;
  41. settings[8] = new settingType();
  42. settings[8].settingName = settingNameEnum.hostedPaymentStyleOptions.ToString();
  43. settings[8].settingValue = “{\”bgColor\”: \”red\”}”;
  44. var orderType = new orderType
  45. {
  46. description = “Product Registrtion”,
  47. };
  48. var transactionRequest = new transactionRequestType
  49. {
  50. transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),    // charge the card
  51. amount = objPayment.amount,
  52. order = orderType,
  53. };
  54. var request = new getHostedPaymentPageRequest();
  55. request.transactionRequest = transactionRequest;
  56. request.hostedPaymentSettings = settings;
  57. ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
  58. // instantiate the contoller that will call the service
  59. var controller = new getHostedPaymentPageController(request);
  60. controller.Execute();
  61. // get the response from the service (errors contained if any)
  62. var response = controller.GetApiResponse();
  63. ////validate
  64. if (response != null && response.messages.resultCode == messageTypeEnum.Ok)
  65. {
  66. objPayment.token = response.token;
  67. }
  68. return View(“DoPayment “, objPayment);
  69. } catch (Exception ex)
  70. {
  71. Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
  72. return Json( new { success = false , message = ex.Message });
  73. }
  74. }
  75. public ActionResult RedirectFromPayment ()
  76. {
  77. // This method calls when payment get success for sure. Write the code after payment successfull
  78. }
  79. public ActionResult CancelFromPaypal ()
  80. {     // This method calls when payment get cancel or not success. Write the code of cancelation or warning
  81. }
MVC View – DoPayment.CSHTML
  1. @model PaymentModel
  2. @{
  3. ViewBag.Title = “payment”;
  4. Layout = null;
  5. }
  6. <body>
  7. @*<div id=”iframe_holder” class=”center-block” style=”width:90%;max-width: 1000px”>
  8. <iframe id=”add_payment” class=”embed-responsive-item panel” name=”add_payment” height=”200%” width=”100%” frameborder=”0″ scrolling=”no” hidden=”true”></iframe>
  9. </div>*@
  10. <form name=”formpaynow” id=”formpaynow” method=”post” action=@Model.actionURl >
  11. <input type=”hidden” value=”@Model.token” id=”token” name=”token” />
  12. </form>
  13. </body>
  14. <script src=”~/Scripts/jquery-1.10.2.js”></script>
  15. <script type=”text/javascript”>
  16. $(document).ready(function () {
  17. //$(“#add_payment”).show();
  18. var form = $(“form”);
  19. form.submit();
  20. //$(window).scrollTop($(‘#add_payment’).offset().top – 50);
  21. });
  22. </script>

Author – Kajal Chandarana

Get a Quote