Authorize.net Payment Integration Using Accept JS Token in ASP .NET MVC

Introduction

In this article, we will learn how to implement an Authorize.net payment gateway with your custom HTML and how to use accept token functionality

mainly accept token functionality used when you don’t want to store your card and bank account details in your backend code or database

Let’s begin.

Step: 1 First go to the authorized developer portal and make a sandbox account and get your client key and security key from the portal.

URL: Go to the authorized.net portal from here

Once you create your sandbox account log in to authorized.net and get your keys:

Step: 2 After login go to the Account > API Credentials & Keys

Here you find your API Login ID and Transaction Key Copy it and store it

Step: 3 Now click on “Manage Public Client Key”  To get your Public Client Key

Note: These three keys are very important for performing the transaction

Now we get our authorized credentials now time to make one MVC project.

Here I make one normal MVC project named ‘Authorized.net_Accept’ and install below NuGet package in our project.

Step: 4 Now we make one  controller named ‘Authorized’, One Class named ‘CardDetails’, One javascript file named ‘AuthorizedPayment’ and make one view named ‘cardForm’ like this :

Step 5: First of all we make our cardForm view

Copy the following code and paste it into your view.

<div class="col-50">
    <h3>Payment</h3>
    <label for="cname">Name on Card</label>
    <input type="text" class="form-control" id="cname" name="cardname" placeholder="John More Doe">
    <label for="ccnum">Credit card number</label>
    <input type="text" class="form-control" id="ccnum" name="cardnumber" placeholder="1111-2222-3333-4444">
    <label for="expyear">Exp Date</label>
    <input type="month" class="form-control" id="expDate" name="expyear" placeholder="2018">
    <label for="cvv">CVV</label>
    <input type="text" class="form-control" id="cvv" name="cvv" placeholder="352">
    <label for="Amount">Amount</label>
    <input type="text" class="form-control" id="Amount" name="Amount" placeholder="352">
    <div class="PayMentsButton">
        <div>
            <button class="btn btn-success" style="margin-top:10px" id="pay">Pay</button>
        </div>
    </div>
</div>

In the following code, there is one normal form for getting card details from UI here in this blog we are not giving any type of validation to form here is the normal form.

Here we are going to add an authorized accept js file to your code
Add the Following js file into your view :   <script type="text/javascript" src="https://jstest.authorize.net/v1/Accept.js" charset="utf-8"></script>

Step 6: Now open your Js file and add the following code to Generate accept Payment token and perform a payment transaction

$(document).ready(function () {

    async function SendPaymentDataToAuthorizeNet(CardDetails) {
        return new Promise((resolve, reject) => {
            debugger
            var authData = {};
            authData.clientKey = "Enter your Public Client Key here";
            authData.apiLoginID = "Enter Your API Login ID here";

            var cardData = {};
            cardData.cardNumber = CardDetails.ccnum;
            cardData.month = CardDetails.Expdate.split('-')[1];
            cardData.year = CardDetails.Expdate.split('-')[0].slice(2);
            //cardData.year = 2025;
            cardData.cardCode = CardDetails.cvv;

            var secureData = {};
            secureData.authData = authData;
            secureData.cardData = cardData;

            Accept.dispatchData(secureData, responseHandler);

            function responseHandler(response) {
                if (response.messages.resultCode === "Error") {
                    resolve({
                        success: false,
                        message: response.messages.message[0].code + ": " + response.messages.message[0].text
                    })
                } else {
                    resolve({
                        success: true,
                        data: response.opaqueData
                    });
                }
            }
        })
    }

    $("#pay").click(async function () {
        debugger
        var Name = $("#cname").val();
        var ccnum = $("#ccnum").val();
        var Expdate = $("#expDate").val();
        var cvv = $("#cvv").val();
        var Amount = $("#Amount").val();

        var Cardetails = {
            Name: Name,
            ccnum: ccnum,
            Expdate: Expdate,
            cvv: cvv
        }

        var Form = new FormData();

        var token = await SendPaymentDataToAuthorizeNet(Cardetails)

        Form.append("dataDescriptor", token.data.dataDescriptor)
        Form.append("dataValue", token.data.dataValue)
        Form.append("Amount", Amount)



        JSON.stringify(Form);

        $.ajax({
            url: "/authorize/ChargeCreditCard",
            data: Form,
            cache: false,
            contentType: false,
            processData: false,
            type: "POST",
            success: function (data) {
                debugger
                console.log(data);
            },
            error: function (error) {

                console.log(error);
            }

        })
    })
})

In this code, we make a click event to perform further code and also we make one JS function named ‘SendPaymentDataToAuthorizeNet’ for get Payment Token.

We pass your card details like Card Number, CVV(Security code), and expiry date in this function, and this function gives one token, and using this token we can perform our transaction in c# side code here we do not need any type of card or bank details on our backend side.

the above function gives a response like this :

{
    "opaqueData": {
        "dataDescriptor": "COMMON.ACCEPT.INAPP.PAYMENT",
        "dataValue": "Your Payment Token"
    },
    "messages": {
        "resultCode": "Ok",
        "message": [
            {
                "code": "I_WC_01",
                "text": "Successful."
            }
        ]
    }
}

Step: 7 Now make one class to get your token and other values from jquery, Open your CardDetails.cs file, and paste the below code into it.

public class CardDetails
{
    public string dataDescriptor { get; set; }
    public string dataValue { get; set; }
    public string Amount { get; set; }
    public string CustomerProfileid { get; set; }
    public string CustomerPaymentProfileid { get; set; }
}

public class CustomerDetailsResponse
{
    public string Transactionid { get; set; }
    public string messageCode { get; set; }
    public string message { get; set; }
    public bool issuccess { get; set; }
    public getCustomerProfileResponse Response { get; set; }
}

Step: 8 Now open your controller and make one method to perform your payment

        public ActionResult CardForm()
        {
            return View();
        }
        public CustomerDetailsResponse ChargeCreditCard(CardDetails CardToken)
        {
            CustomerDetailsResponse TransactionResponse = new CustomerDetailsResponse();

            ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNet.Environment.SANDBOX;
            ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType()
            {
                name = "Enter your API Login ID here",
                ItemElementName = ItemChoiceType.transactionKey,
                Item = "Enter your Transaction Key here",
            };
            var transactionRequest = new transactionRequestType
            {
                transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),    // charge the card
                amount = Convert.ToDecimal(CardToken.Amount),
                payment = new paymentType
                {
                    Item = new opaqueDataType
                    {
                        dataDescriptor = CardToken.dataDescriptor,
                        dataValue = CardToken.dataValue
                    }
                },
                customerIP = "",
                billTo = new customerAddressType
                {
                    firstName = "Test",
                    lastName = "Accept Token",
                },
                order = new orderType
                {
                    invoiceNumber = "123456",
                },
                customer = new customerDataType
                {
                    id = "111111",
                    email = "Test123@gmail.com",
                }
            };

            var request = new createTransactionRequest { transactionRequest = transactionRequest };
            var controller = new createTransactionController(request);
            controller.Execute();
            var response = controller.GetApiResponse();
            TransactionResponse.Response = response;

            // validate response
            if (response != null)
            {
                if (response.messages.resultCode == messageTypeEnum.Ok)
                {
                    if (response.transactionResponse.messages != null)
                    {
                        TransactionResponse.issuccess = true;
                        TransactionResponse.Response = response;
                    }
                    else
                    {
                        if (response.transactionResponse.errors != null)
                        {
                            TransactionResponse.issuccess = false;
                            TransactionResponse.messageCode = response.transactionResponse.errors[0].errorCode;
                            TransactionResponse.message = response.transactionResponse.errors[0].errorText;
                        }
                    }
                }
                else
                {
                    TransactionResponse.issuccess = false;
                }
            }
            else
            {
                TransactionResponse.issuccess = false;
            }

            return TransactionResponse;
        }

Note: Don’t forget to replace your login id and transaction id in your controller code.

Now Run your project your UI looks like this :

Now your all code is ready you can test your payment using this project add your test card data to the form and click on pay.

Perform like this :

Now you can see your transaction in the authorized portal.

In the above blog, we see how to use accept js(Token) in your MVC project to use payment integration. when you don’t want to send data to your backend you can simply make one token using the make accept token method pass it into your backend and perform your payment transaction.

One important thing is you can’t use this token two times you can use this token once only and this token is validated for only 15 minutes

using this you can perform any type of authorize.net payment functionality without using any type of security details, bank details, and card details in your code.

You can get more information about accept js from here

Thank You.

Submit a Comment

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

Subscribe

Select Categories