authorizenet / sample-code-csharp Goto Github PK
View Code? Open in Web Editor NEWThis repository contains working code samples which demonstrate C# integration with the Authorize.Net API
License: MIT License
This repository contains working code samples which demonstrate C# integration with the Authorize.Net API
License: MIT License
Hi there,
In it's current state, the project does not build in VS2015, the error looks to be related to multiple AuthorizeNet
packages being specified in packages.config:
Error occurred while restoring NuGet packages: An error occurred while reading file 'd:\misc\sample-code-csharp\packages.config': There are duplicate packages: AuthorizeNet
1>------ Rebuild All started: Project: SampleCode, Configuration: Debug Any CPU ------
1>C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(1819,5): warning MSB3245: Could not resolve this reference. Could not locate the assembly "AuthorizeNet". Check to make sure the assembly exists on disk. If this reference is required by your code, you may get compilation errors.
1>d:\misc\sample-code-csharp\ApplePayTransactions\CreateAnApplePayTransaction.cs(5,7,5,19): error CS0246: The type or namespace name 'AuthorizeNet' could not be found (are you missing a using directive or an assembly reference?)
1>d:\misc\sample-code-csharp\ApplePayTransactions\CreateAnApplePayTransaction.cs(6,7,6,19): error CS0246: The type or namespace name 'AuthorizeNet' could not be found (are you missing a using directive or an assembly reference?)
1>d:\misc\sample-code-csharp\ApplePayTransactions\CreateAnApplePayTransaction.cs(7,7,7,19): error CS0246: The type or namespace name 'AuthorizeNet' could not be found (are you missing a using directive or an assembly reference?)
1>d:\misc\sample-code-csharp\CustomerProfiles\CreateCustomerPaymentProfile.cs(3,7,3,19): error CS0246: The type or namespace name 'AuthorizeNet' could not be found (are you missing a using directive or an assembly reference?)
1>d:\misc\sample-code-csharp\CustomerProfiles\CreateCustomerPaymentProfile.cs(4,7,4,19): error CS0246: The type or namespace name 'AuthorizeNet' could not be found (are you missing a using directive or an assembly reference?)
1>d:\misc\sample-code-csharp\CustomerProfiles\CreateCustomerPaymentProfile.cs(5,7,5,19): error CS0246: The type or namespace name 'AuthorizeNet' could not be found (are you missing a using directive or an assembly reference?)
1>d:\misc\sample-code-csharp\CustomerProfiles\CreateCustomerProfile.cs(3,7,3,19): error CS0246: The type or namespace name 'AuthorizeNet' could not be found (are you missing a using directive or an assembly reference?)
1>d:\misc\sample-code-csharp\CustomerProfiles\CreateCustomerProfile.cs(4,7,4,19): error CS0246: The type or namespace name 'AuthorizeNet' could not be found (are you missing a using directive or an assembly reference?)
1>d:\misc\sample-code-csharp\CustomerProfiles\CreateCustomerProfile.cs(5,7,5,19): error CS0246: The type or namespace name 'AuthorizeNet' could not be found (are you missing a using directive or an assembly reference?)
...
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
I suspect the newer version of NuGet that VS2015 ships with does not handle duplicate references, but previous versions did.
I'm happy to submit a PR removing the additional reference.
Thanks!
Request:
{
"createTransactionRequest": {
"merchantAuthentication": {
"name": "NameNameName",
"transactionKey": "KeyKeyKey"
},
"refId": "123",
"transactionRequest": {
"transactionType": "authCaptureTransaction",
"amount": "7.77",
"payment": {
"creditCard": {
"cardNumber": "4111111111111111",
"expirationDate": "2022-03",
"cardCode": "123"
}
},
"billTo": {
"zip": "85308"
},
"order": {
"invoiceNumber": "1231",
"description": "Some desc"
}
}
}
}
Response
{
"messages": {
"resultCode": "Error",
"message": [
{
"code": "E00003",
"text": "The element 'transactionRequest' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd' has invalid child element 'order' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd'. List of possible elements expected: 'shipTo, customerIP, cardholderAuthentication, retail, employeeId, transactionSettings, userFields, surcharge, merchantDescriptor, subMerchant, tip, processingOptions, subsequentAuthInformation, otherTax, shipFrom, authorizationIndicatorType' in namespace 'AnetApi/xml/v1/schema/AnetApiSchema.xsd'."
}
]
}
}
Steps to reproduce:
<form action="https://test.authorize.net/payment/payment" method="post">
<input type="text" name="token" value="token value here" />
<hr />
<button type="submit">Pay</button>
</form>
Credit Card #: 4111111111111111
Credit Card Exp: 11/21
Credit Card Code: 907
Upon clicking pay you get an error "Unexpected error. Please try again."
I have tried several different ways to generate the token as well as several different types of credit card numbers (all test numbers) and amounts, etc. I cannot get a working sample to go through.
I even tried to do this in a production environment and had the same result. Can someone please let me know what exactly this error is?
You can duplicate the error using the sample codes api login or with any generated one from the sandbox.
I have a hosting providor that only allows a medium trust level. I could only get a transaction to process at a full trust level. How can I get authorize.net to work at medium trust level?
Thx
It is nessasary to have gGetHostedProfilePageResponse to make tokenized credit card payments. As per the http://www.authorize.net/content/dam/authorize/documents/CIM_XML_guide.pdf document, chapter 4. But there is no implementation in the sample code. Solution from the community member can be found in http://community.developer.authorize.net/t5/Integration-and-Testing/How-to-call-GetHostedProfilePage/td-p/14208. I used it and it works. Please implement this missing method.
Hi,
We have upgraded our project to .Net Core 3.1 and are now getting the below error when trying to set any of the ApiOperationBase values:
System.TypeInitializationException
HResult=0x80131534
Message=The type initializer for 'AuthorizeNet.Api.Controllers.Bases.ApiOperationBase`2' threw an exception.
Source=AuthorizeNET
StackTrace:
at AuthorizeNet.Api.Controllers.Bases.ApiOperationBase`2.set_RunEnvironment(Environment value)
at efs.portal.api.services.PaymentGateway.AuthNetGateway..ctor(IConfiguration config, IMapper mapper, ILoggerFactory loggerFactory) in D:\WORK\EFS\Code\efs-portal-api\Projects\efs-services\PaymentGateway\AuthNetGateway.cs:line 40
Inner Exception 1:
MissingMethodException: Method not found: 'Microsoft.Extensions.Logging.ILoggerFactory Microsoft.Extensions.Logging.DebugLoggerFactoryExtensions.AddDebug(Microsoft.Extensions.Logging.ILoggerFactory, Microsoft.Extensions.Logging.LogLevel)'.
is this a compatibility issue with 3.1 or something different?
Thanks,
Gennadi
I get the following exception when I call the Execute method. I am obviously missing some files or packages for the correct TLS configuration. Any help would be greatly appreciated.
"The request was aborted: Could not create SSL/TLS secure channel."
I ran the latest C# version of the sample code "ChargeCreditCard", but cannot seem to get past the error, "The underlying connection was closed: "
var controller = new createTransactionController(request);
controller.Execute();
I verified my sandbox ApiLoginID and ApiTransactionKey work on the Authorize.net website: https://developer.authorize.net/api/reference/
It seems others are having this issue, but we haven't found a solution:
https://community.developer.authorize.net/t5/Integration-and-Testing/Sandbox-issues-The-underlying-connection-was-closed-An/td-p/57584
I have implemented this test method and getting the error below. Any help would be great.
The same code works fine in my other application though.
public static object Ping()
{
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType()
{
name = "5KP3u95bQpv",
ItemElementName = ItemChoiceType.transactionKey,
Item = "346HZ32z3fP4hTG2"
};
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNet.Environment.SANDBOX;
authenticateTestRequest request = new authenticateTestRequest();
var controller = new authenticateTestController(request);
controller.Execute();
var response = controller.GetApiResponse();
return response;
}
While running the GetBatchStatistics I am getting the following exception:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
Hello,
I'm trying to redirect to a hosted payment page using .net with c#. I have the basic app that is getting a token using getHostedPaymentPageResponse
, and I'm putting the token received to a form and submitting the form to "https://test.authorize.net/payment/payment" with POST method. But I keep getting "Missing or invalid token" error. Following is my code:
<form runat="server" action="" id="formAuthorizeNetTestPage" name="formAuthorizeNetTestPage" method="POST">
<input type="hidden" name="token" value="" runat="server" id="redirectToken"/>
<p>Customer ID: </p>
<asp:TextBox runat="server" ID="customerID"></asp:TextBox>
<p>Amount: </p>
<asp:TextBox runat="server" ID="amount_input"></asp:TextBox>
<asp:Button ID="Button1" OnClick="Button1_Click" runat="server" text="Pay"/>
</form>
And here is the code behind:
public void Button1_Click(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("Hello, Button1 Clicked");
decimal amount = decimal.Parse(amount_input.Text);
string customerId = customerID.Text;
var ApiResponse = Run(LoginId, TransactionKey, amount, customerId, redirectToken, formAuthorizeNetTestPage, body_container);
//System.Diagnostics.Debug.WriteLine();
}
public static ANetApiResponse Run(String ApiLoginID, String ApiTransactionKey, decimal amount, string customerProfileId, System.Web.UI.HtmlControls.HtmlInputHidden token_input, System.Web.UI.HtmlControls.HtmlForm formAuthorizeNetTestPage, System.Web.UI.HtmlControls.HtmlGenericControl body_container)
{
System.Diagnostics.Debug.WriteLine("GetAnAcceptPaymentPage Sample");
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNet.Environment.SANDBOX;
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType()
{
name = ApiLoginID,
ItemElementName = ItemChoiceType.transactionKey,
Item = ApiTransactionKey,
};
settingType[] settings = new settingType[]{
new settingType()
// More settings can be added here as and when required
};
settings[0] = new settingType();
settings[0].settingName = settingNameEnum.hostedProfileReturnUrl.ToString();
settings[0].settingValue = "https://example.com/";
var request = new getHostedProfilePageRequest();
request.customerProfileId = customerProfileId;
request.hostedProfileSettings = settings;
var controller = new getHostedProfilePageController(request);
controller.Execute();
// get the response from the service (errors contained if any)
var response = controller.GetApiResponse();
// validate response
if (response != null && response.messages.resultCode == messageTypeEnum.Ok)
{
System.Diagnostics.Debug.WriteLine("Message code : " + response.messages.message[0].code);
System.Diagnostics.Debug.WriteLine("Message text : " + response.messages.message[0].text);
System.Diagnostics.Debug.WriteLine("Token : " + response.token);
}
else if (response != null)
{
System.Diagnostics.Debug.WriteLine("Error: " + response.messages.message[0].code + " " + response.messages.message[0].text);
System.Diagnostics.Debug.WriteLine("Failed to get hosted payment page");
}
System.Diagnostics.Debug.WriteLine(response.token);
token_input.Value = response.token;
formAuthorizeNetTestPage.Action = "https://test.authorize.net/payment/payment";
//HttpContext.Current.Response.Redirect("https://test.authorize.net/payment/payment");
body_container.Attributes.Add("onload", "document.getElementById('formAuthorizeNetTestPage').submit();");
return response;
}
I'm unable to build the SampleCode project after following the instructions in the README.md. I've attached a log of errors and warnings I get when I try and build the project.
sample-code-error-list.xlsx
ChargeCreditCard.cs or sample code doesn't generate declines? How do you verify address or zip?
SOAP representation of Authorize.Net has CreateCustomerProfileTransaction method and I would like to move to REST API and cannot find this method. Can someone guide me with the equivalent method that is missing in REST
Hi there,
While integrating Authorize.Net into a client project, we came across some unexpected issues when testing against a live account, using real payment information.
From your own sample code for ChargeCreditCard.Run
:
// get the response from the service (errors contained if any)
var response = controller.GetApiResponse();
if (response.messages.resultCode == messageTypeEnum.Ok)
{
if (response.transactionResponse != null)
{
Console.WriteLine("Success, Auth Code : " + response.transactionResponse.authCode);
}
}
else
{
Console.WriteLine("Error: " + response.messages.message[0].code + " " + response.messages.message[0].text);
if (response.transactionResponse != null)
{
Console.WriteLine("Transaction Error : " + response.transactionResponse.errors[0].errorCode + " " + response.transactionResponse.errors[0].errorText);
}
}
...
This seems to suggest that response.messages.resultCode
can be used to determine success of the overall transaction. During our testing however, this was found not to be the case. When using a live account, and intentionally entering incorrect information we regularly saw a resultCode of Ok
, despite the transaction itself being declined and errors being returned.
I was only able to find limited documentation surrounding the sample code, which all seemed to suggest that messages.resultCode
could be relied upon to confirm a successful transaction. However, It's definitely possible that I've missed something!
As a temporary workaround, we've resorted to also checking response.transactionResponse.responseCode
as well as the errors collection returned by the transaction response:
if (response.messages.resultCode == messageTypeEnum.Ok && response.transactionResponse != null &&
response.transactionResponse.responseCode == "1" &&
(response.transactionResponse.errors == null || !response.transactionResponse.errors.Any()))
{
// successful transaction
}
This works as we would like, but feels wrong. For the majority of cases, it's only important for us to check that the transaction was successful, and requiring this number of checks to confirm does seem a little excessive!
Just for others' benefit, it's also worth mentioning that this was only discovered when moving over to a 'live' account; using sandbox/test accounts did not surface the issue, as transactions were always returned as successful during testing.
I am trying to compile the sample code and I get an error in GetAccountUpdaterJobSummary.cs because the getAUJobSummaryController type is not found on line 35.
I have the same implementation as referred and also pass on CustomerDataType and Order Type. If i use Credit Card then i get accepted in live site, but the "DebitBankAccount" returns NULL response (The response object is NULL).
Customer Info has emailID and UserID which is an INT passed as string
Order Info has invoice number which is "12345-67890" and Description"
I tried in the sandbox URL and have the same problem.
If i run it from my dev server i dont have this issue and works like a charm.
Also, the command sample application (sample-code-csharp-master) from Authorize.net downloaded from githhub runs well in the same PROD server where web fails.
My Server is Windows 2012 R2
Any help?
Here is the Debit Bank Code:
#region Direct Debit - Bank Payment
//accType = null;
var bankAccount = new bankAccountType
{
accountNumber = TextBoxAccountNumber.Text,
routingNumber = TextBoxRTN.Text,
echeckType = echeckTypeEnum.WEB, // change based on how you take the payment (web, telephone, etc)
nameOnAccount = TextBoxBankName.Text,
accountType = GetSelectedAccountType()
};
//standard api call to retrieve response
var paymentType = new paymentType { Item = bankAccount };
customerDataType customerInfo;
orderType orderInfo;
GetCustomerAndOrderInfo(out customerInfo, out orderInfo);
transactionRequest = new transactionRequestType
{
transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), // refund type
payment = paymentType,
amount = ccPaymentDetails.Amount,
customer = customerInfo,
order = orderInfo
};
#endregion
}
request = new createTransactionRequest { transactionRequest = transactionRequest };
// instantiate the contoller 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();
if (response != null && response.messages.resultCode == messageTypeEnum.Ok)
{
if (response.transactionResponse != null)
{...
}
}
else if (response != null)
{
string message = "Transaction Error : " + response.messages.message[0].code + " " + response.messages.message[0].text;
// Do something Here
}
else { Log.Info("Authorize.net Response Message is null", true); }
It always goes to else when i use DebitBank
Note: Same code for CC works like a charm.
when I run "CreateAnAcceptPaymentTransaction"
I got this error
System.Net.WebException: 'The request was aborted: Could not create SSL/TLS secure channel.'
Now that they shut off TLS 1.1 on the Sandbox the code does not work anymore for ChargeCreditCard. The line. Even if the Server registries entries are set to shut off TLS 1.0 and TLS 1.2
controller.Execute();
You get a return exception:
The underlying connection was closed: An unexpected error occurred on a send.
I have created account PayPal sandbox mode(Not add bank account information). Then I set grant permission from account Authorize.Net and the error message always appear "There has been an error while processing your request. Please try again."
So How I resolve this issue ?
The example code is misleading because the ANetApiResponse class does not have the attribute 'token', which is what gets populated by the call to GetApiResponse. It should actually return the derived class, getHostedPaymentPageResponse.
Hello, I am trying to build the "DotNet_Core" solution but getting a lot of errors, such as:
-->SampleCode.cs-->using AuthorizeNet.Utilities;
-->SampleCode.cs --> ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment.HttpUseProxy
-->SampleCode.cs --> AuthorizeNet.Environment.getBooleanProperty(Constants.HttpsUseProxy)
Do you have a better solution for the "DotNet_Core" project or any documentation tutorial?
Thank you very much!
Best,
Sample code doesn't deal with the cvv? How is that typically dealt with or submitted? Thanks
userFields are available in the transactionRequestType but are not returned by Transaction calls.
I am using ID TECH Augusta smart card reader device to swipe and capture encrypted data and submitting it to Authorize.net using code sample on git hub link https://github.com/AuthorizeNet/sample-code-csharp/blob/master/PaymentTransactions/ChargeEncryptedTrackData.cs
Can you knowledge me what is the correct data length that is allowed and also let me know the format if any that I should get it configured my device with.
What is allowed data length?
Running CaptureOnly.cs gives the following error "Error: E00027 (The transaction was unsuccessful).
Transaction Error: 12 (An authorization code is required but not present)."
I have to add a line like authCode = "ROHNFQ" to transactionRequest to make this work properly (where ROHNFQ is a valid authCode). Adding this line to the code however makes CaptureOnly.cs equivalent to CaptureFundsAuthorizedThroughAnotherChannel.cs.
Email is not posted when using customerAddressType. The credit card is charged successfully. However, when I login to authorize.net account and pull up the transaction, the billing email is blank - apparently it is not posted.
Here is an example from my code:
var billingAddress = new customerAddressType
{
firstName = _tran.first_name,
lastName = _tran.last_name,
address = _tran.address,
city = _tran.city,
state = _tran.state,
zip = _tran.zip,
country = _tran.country,
email = _tran.email_address,
phoneNumber = _tran.phone_num, //phone number won't be posted to Authorize.net
};
I am trying to include lineItems using this model. Any suggestions would be great. Code snip below:
//standard api call to retrieve response
var paymentType = new paymentType { Item = creditCard };
var orderDetails = new orderType { invoiceNumber = "Inv 01234", description = "Test" };
var items = new lineItemType { itemId = "TESTER", description = "Dec", name="Name", quantity = 1, taxable = false, taxableSpecified = false, unitPrice = 0.10m };
var transactionRequest = new transactionRequestType
{
transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), // charge the card
//amount = 133.45m,
amount = Amount,
payment = paymentType,
order = orderDetails,
lineItems = items
};
Need authorize.net to send an email through code. How is that done?
Are there plans to support .Net Core?
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNet.Environment.SANDBOX;
This line from the sample code gives the error:
ANetApiRequest is an ambiguous reference between 'AuthorizeNet.ApiCore.ANetApiRequest' and 'AuthorizeNet.Api.Contracts.V1.ANetApiRequest'
If I try to fully qualify the reference, it says 'ApiCore' namespace not found and 'Api' reference not found, respectively.
var controller = new createCustomerProfileController(request);
controller.Execute();
// get the response from the service (errors contained if any)
createCustomerProfileResponse response = controller.GetApiResponse();
When trying to use above getting the error below:
S_### erver Error in '/' Application.
Could not load file or assembly 'AuthorizeNet, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. A strongly-named assembly is required. (Exception from HRESULT: 0x80131044)
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.FileLoadException: Could not load file or assembly 'AuthorizeNet, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. A strongly-named assembly is required. (Exception from HRESULT: 0x80131044)_
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.