How to do payment transactions using Authorize.Net?

Payment Processing Using Authorize.Net

Building a payment gateway is crucial for any online business, especially those with eCommerce operations. Without a robust payment, gateway businesses stand to lose credibility, reputation, and customers.

So, as developers, we need to recommend and provide the best possible payment systems for the clients. In this tutorial, we will go through the process to add and enable payment transactions with Authorize.Net.

What is Authorize.Net?

Authorize.Net is a payment gateway that provides different options like SDK, API, etc., for doing payment transactions. It offers robust functions for processing payments for businesses and also supports XML and JSON variants. Today we are going to explore API payment gateway.

There are lots of API provided by Authorize.Net. Check this link for more information on the same.

The amazing feature of Authorize.Net is the staging sandbox. It is provided especially for developers to do any kind of R&D regarding payment transactions. A developer can perform unlimited payment transactions on the staging sandbox.

For that, you need to do one-time registration on their portal. After successful registration, they will provide you with three keys required to do further payment transactions. Make sure to store the keys securely.

These keys are;

  • API Login ID
  • Transaction Key
  • Key

We will explore two major options like paying through a credit card or Bank Account.

1. Charge Credit Card API

Request :
	"payment": {
                "creditCard": {
                    "cardNumber": "5424000000000015",
                    "expirationDate": "2025-12",
                    "cardCode": "999"
                }
            },

There are lots of parameters available, but we can include relevant parameters as per our requirements. Here, I am showing the required parameters specifically to pay through Credit Card.

Response :

{
    "transactionResponse": {
        "responseCode": "1",
        "authCode": "HW617E",
        "avsResultCode": "Y",
        "cvvResultCode": "",
        "cavvResultCode": "",
        "transId": "2157047189",
        "refTransID": "",
        "transHash": "E7CEB0A9F1BECA32A02493E1B31D5955",
        "testRequest": "0",
        "accountNumber": "XXXX1111",
        "accountType": "Visa",
        "messages": [
            {
                "code": "1",
                "description": "This transaction has been approved."
            }
        ],
        "transHashSha2": "D0C4FFF5648511A5862B917CFD9BB78ABF8A6E1D90C119CBBC4C0B454F4FF40DED15B204E042F36ECA5FB15D02588E4E4A7B85B94E7279599CE6020462CB7DEE",
        "SupplementalDataQualificationIndicator": 0,
	"networkTransId": "123456789NNNH"
    },
    "messages": {
        "resultCode": "Ok",
        "message": [
            {
                "code": "I00001",
                "text": "Successful."
            }
        ]
    }
}

If payment is successful, you will receive an “OK” status code and the above message as a response.

2. Debit Bank Account

Here we require bank details like account number, name, account type

"payment": {
                "bankAccount": {
                    "accountType": "checking",
                    "routingNumber": "121042882",
                    "accountNumber": "123456789",
                    "nameOnAccount": "John Doe"
                }
        	},

Response:

{
    "transactionResponse": {
        "responseCode": "1",
        "authCode": "",
        "avsResultCode": "P",
        "cvvResultCode": "",
        "cavvResultCode": "",
        "transId": "2149186917",
        "refTransID": "",
        "transHash": "803D51FDF65043182BF264B8BAA8B2DF",
        "accountNumber": "XXXXX6789",
        "accountType": "eCheck",
        "messages": [
            {
                "code": "1",
                "description": "This transaction has been approved."
            }
        ]
    },
    "refId": "123456",
    "messages": {
        "resultCode": "Ok",
        "message": [
            {
                "code": "I00001",
                "text": "Successful."
            }
        ]
    }
}

If payment is successful, you will receive an “OK” status code and the above message as a response.

You need to save the transId (transaction ID) for future reference. This is required if the client wants a refund of that amount. At that moment, we need the system to pass that reference transaction ID with the relevant API, which is provided by Authorize.Net.

3. Credit Bank Account

This is required when we want to transfer the specified amount to someone’s bank account.

Request

"refId": "123456",
        "transactionRequest": {
            "transactionType": "refundTransaction",
            "amount": "5",
            "payment": {
                "bankAccount": {
                    "accountType": "checking",
                    "routingNumber": "121042882",
                    "accountNumber": "123456789",
                    "nameOnAccount": "John Doe"
                }
            },
            "refTransId": "2148889729"

Response

{
    "transactionResponse": {
        "responseCode": "3",
        "authCode": "",
        "avsResultCode": "P",
        "cvvResultCode": "",
        "cavvResultCode": "",
        "transId": "0",
        "refTransID": "2149181544",
        "transHash": "D6C9036F443BADE785D57DA2B44CD190",
        "accountNumber": "XXXX5678",
        "accountType": "eCheck",
        "errors": [
            {
                "errorCode": "16",
                "errorText": "The transaction cannot be found."
            }
        ]
    },
    "refId": "123456",
    "messages": {
        "resultCode": "Error",
        "message": [
            {
                "code": "E00027",
                "text": "The transaction was unsuccessful."
            }
        ]
    }
}

You will find your transaction status in the result code tag.

4. Refund

This transaction type is used to initiate a refund transaction for the customer when requested. The refund transaction will initiate after the customer has successfully settled the account through the payment gateway.

Note that credit card information and bank account information are mutually exclusive, so you should not submit both.

Request:

{
    "createTransactionRequest": {
        "merchantAuthentication": {
            "name": "5KP3u95bQpv",
            "transactionKey": "346HZ32z3fP4hTG2"
        },
        "refId": "123456",
        "transactionRequest": {
            "transactionType": "refundTransaction",
            "amount": "5.00",
            "payment": {
                "creditCard": {
                    "cardNumber": "0015",
                    "expirationDate": "XXXX"
                }
            },
            "refTransId": "1234567890"
        }
    }
}

Response:

{
    "transactionResponse": {
        "responseCode": "1",
        "authCode": "",
        "avsResultCode": "P",
        "cvvResultCode": "",
        "cavvResultCode": "",
        "transId": "1234569999",
        "refTransID": "1234567890",
        "transHash": "D04B060066BA442AFF73A31B97A4693F",
        "accountNumber": "XXXX0015",
        "accountType": "Mastercard",
        "messages": [
            {
                "code": "1",
                "description": "This transaction has been approved."
            }
        ]
    },
    "refId": "123456",
    "messages": {
        "resultCode": "Ok",
        "message": [
            {
                "code": "I00001",
                "text": "Successful."
            }
        ]
    }
}

These are the basic payment methods we usually need to implement in the application where payment integration is needed.

We have tried to add all the basic payment gateways and transactions businesses require in the present-day environment. You will find the Request and Response information listed above for four different types of payment transactions.

For more details, you can visit the Authorized.Net link. Now, we are going to explore API in terms of how to consume these Authorized.NetAPIs in our project.

You will find the code snippet below, and it will give you an idea of different steps that you need to perform to complete payment transactions through Authorized.Net

Some samples:

PaymentTranscationResponsetranscationResponse = new PaymentTranscationResponse();
              	
        	#region Set Enviornment
        	if (transcationRequest.RunEnvironment.ToString().ToUpper() == "SANDBOX")
        	{
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNet.Environment.SANDBOX;
        	}
        	else if (transcationRequest.RunEnvironment.ToString().ToUpper() == "PRODUCTION")
        	{
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNet.Environment.PRODUCTION;
        	}
        	else
        	{
            	return null;
        	}
        	#endregion
         	#region Set Authorize merchant information
        	// define the merchant information (authentication / transaction id)
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType()
        	{
            	name = transcationRequest.APILoginKey,
ItemElementName = ItemChoiceType.transactionKey,
            	Item = transcationRequest.ApiTransactionKey,
        	};
        	#endregion
         	#region Set Credit card details
        	var creditCard = new creditCardType
        	{
cardNumber = transcationRequest.CreditCardNumber,
expirationDate = transcationRequest.ExpirationDate,
cardCode = transcationRequest.CardCode
     	   };
        	#endregion
         	#region Set BillingAddress
        	var billingAddress = new customerAddressType
        	{
firstName = "Debtor",
lastName = "Debtor",
            	address = "Debtor",
            	city = "debtor",
                zip = "98004"
        	};
        	#endregion
         	#region Set payment information
        	//standard api call to retrieve response
        	var paymentType = new paymentType{ Item = creditCard };
         	// Add line Items
        	var lineItems = new lineItemType[1];
lineItems[0] = new lineItemType { itemId = "1", name = "Course", quantity = 1, unitPrice = new Decimal(25.00) };
         	var transactionRequest = new transactionRequestType
        	{
transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),	// charge the card
             	amount = transcationRequest.Amount,
            	payment = paymentType,
billTo = billingAddress,
lineItems = lineItems
        	};
         	#endregion
         	#region Send request to Authorize payment API
 transcationResponse.PaymentTransId = DateTime.Now.ToString("yyyyMMddhhmmss");
         	var request = new createTransactionRequest{ transactionRequest = transactionRequest };
         	// instantiate the controller that will call the service
        	var controller = new createTransactionController(request);
controller.Execute();
         	// get the response from the service (errors contained if any)
        	var response = controller.GetApiResponse();
        	#endregion
         	#region Set Response
        	// validate response
        	if (response != null)
        	{
            	if (response.messages.resultCode == messageTypeEnum.Ok)
            	{
                	if (response.transactionResponse.messages != null)
                	{
transcationResponse.ResultCode = "OK";
                        //Console.WriteLine("Successfully created transaction with Transaction ID: " + response.transactionResponse.transId);
transcationResponse.TransId = response.transactionResponse.transId;
                        //Console.WriteLine("Response Code: " + response.transactionResponse.responseCode);
transcationResponse.ResponseCode = response.transactionResponse.responseCode;
                        //Console.WriteLine("Message Code: " + response.transactionResponse.messages[0].code);
transcationResponse.TransMessageCode = response.transactionResponse.messages[0].code;
                        //Console.WriteLine("Description: " + response.transactionResponse.messages[0].description);
transcationResponse.TransMessageText = response.transactionResponse.messages[0].description;
                    	//Console.WriteLine("Success, Auth Code : " + response.transactionResponse.authCode);
transcationResponse.AuthCode = response.transactionResponse.authCode;
                	}
                	else
                	{
                    	//Console.WriteLine("Failed Transaction.");
transcationResponse.ResultCode = "Error";
                    	if (response.transactionResponse.errors != null)
                    	{
                            //Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode);
transcationResponse.ErrorCode = response.transactionResponse.errors[0].errorCode;
                            //Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText);
transcationResponse.ErrorText = response.transactionResponse.errors[0].errorText;
                    	}
                	}
            	}
            	else
            	{
                    //Console.WriteLine("Failed Transaction.");
transcationResponse.ResultCode = "Error";
                	if (response.transactionResponse != null &&response.transactionResponse.errors != null)
                	{
                        //Console.WriteLine("Error Code: " + response.transactionResponse.errors[0].errorCode);
transcationResponse.ErrorCode = response.transactionResponse.errors[0].errorCode;
                        //Console.WriteLine("Error message: " + response.transactionResponse.errors[0].errorText);
transcationResponse.ErrorText = response.transactionResponse.errors[0].errorText;
                	}
                	else
                	{
                        //Console.WriteLine("Error Code: " + response.messages.message[0].code);
transcationResponse.MessageCode = response.messages.message[0].code;
	                    //Console.WriteLine("Error message: " + response.messages.message[0].text);
transcationResponse.MessageDescription = response.messages.message[0].text;
                	}
            	}
        	}
        	else
        	{
            	//Console.WriteLine("Null Response.");
transcationResponse.ResultCode = "Error";
        	}
        	#endregion
         	return transcationResponse;

Conclusion

Any business that has just started operations or has been in the industry for some time needs to start accepting online payments. Having the right payment solutions improves the ability of the customer to pay, which means it is good for business.

Choosing the right payment method and its API is imperative as it helps ensure seamlessness in the transaction’s speed and accuracy. Authorize .Net supports several other payment systems, including PayPal or Apple Pay.

You can use the API-based system to build a robust payment gateway. For building such a system, you can contact our expert developers, who will bring years of experience to the table and a deep understanding of the operations. We can become your development partners for all the current and future requirements.