Middleware SDK for .Net 4.5+

The Middleware SDK for .NET is a collection of classes that implement the rest api for the payment engine cloud solution. It allows developers to quickly create applications in .Net that take advantage of the payment engine middleware.

Middleware Class

Middleware Constructor

Constructor for the middleware class. To instantiate the middleware object, you will need an API Key and PIN which can be created in the merchant console. You also have the option of specifying the gateway host you would like to use.

public Middleware(String apiKey, String pin, String host="api.paymentengine.io")
Parameter Type Description
apiKey String The API Key (aka SourceKey) created in the merchant console.
pin String API PIN set in the merchant console.
host String Gateway host to use. Defaults to primary production gateway "api.paymentengine.io". For sandbox use "sandbox.usaepay.com"

Example

try
{
   Middleware client = new Middleware("_hxEwTCy4UPSTp7sL5V69fa2Uu5Gzrfu", "1234", "sandbox.usaepay.com");
} catch(MiddlewareException ex) {
   Console.WriteLine("Error instantiating middleware: " + ex.ToString());
}

Exceptions

Will throw a MiddlewareException.

Code Message Notes
Invalid API Key The key parameter was not set to a valid api key.
An API Pin is required The pin parameter must be set to the pin assigned to the api key. If no pin has been set for the api key, log into the merchant console and set one.
Invalid gateway hostname The host parameter must be set to a valid hostname for the gateway. It is the hostname only, do not include https://

RegisterDevice

Starts the registration process for a new terminal. The callback delegate will be called with a middleware device object that includes the "PairingCode" parameter. This code is entered by the user into the payment terminal to complete the pairing process. This method is only needed if the developer wishes to support registering new terminals. Alternately, terminals can be registered in the Device Manager section of the Merchant Console.

public void RegisterDevice(String TerminalName, Action<Device> callback, Action<MiddlewareException> onError, String RegistrationType="standalone")
Parameter Type Description
TerminalName String The name of the terminal chosen by the user/developer. This can be used to distinguish between multiple devices.
callback Action Delegate called when registration request is accepted and pairing code is available.
onError Action Delegate called if an error occurs.
RegistrationType String Type of device registration. Defaults to "standalone".

Example

client.RegisterDevice("Register 1",(device) => {
   Console.WriteLine("Pairing code: " + device.PairingCode);
   Console.WriteLine("Device Key: " + device.DeviceKey);
}, (emw)=> {
  Console.WriteLine("error: " + emw.Message);
});

Exceptions

The onError delegate will be called if an error occurs.

Code Message Notes

See also: Common Exceptions

LoadDeviceByKey

Loads a Device object for an existing DeviceKey. The DeviceKey is returned when registering the device with RegisterDevice. The DeviceKey is also available in the Device Manager screen under the Settings section of the merchant console.

public void LoadDeviceByKey(String DeviceKey, Action<Device> callback, Action<MiddlewareException> onError=null)
Parameter Type Description
DeviceKey String Key that uniquely identifies a device.
callback Action Delegate called when device has been loaded.
onError Action Delegate called if an error occurs.

Exceptions

Either throws a MiddlewareException or calls the onError delegate.

Code Message Notes
DeviceKey is required A valid DeviceKey must be passed in the first parameter
21121 Unknown device key ... The DeviceKey did not match a device on the server

See also: Common Exceptions

Example

client.LoadDeviceByKey("sa_0nr0qWGWrEQzALVjFkTeptSWj9NnE", (x) => {
   Device device = x;
   Console.WriteLine("Device load: " + device.Name);
}, (emw)=> {
  Console.WriteLine("error: " + emw.Message);
});

LoadDevices

Loads all Devices.

public void LoadDevices(Action<Device> callback, Action<MiddlewareException> onError=null)
Parameter Type Description
callback Action Delegate called when each device has been loaded.
onError Action Delegate called if an error occurs.

Exceptions

Calls the onError delegate.

See also: Common Exceptions

Example

client.LoadDevices((x) => {
   Device device = x;
   Console.WriteLine("Device load: " + device.Name);
}, (emw)=> {
  Console.WriteLine("error: " + emw.Message);
});

LoadPaymentRequestByKey

Load an existing payment request by RequestKey.

public void LoadPaymentRequestByKey(String RequestKey, Action<PaymentRequest> callback, Action<MiddlewareException> onError)
Parameter Type Description
RequestKey String Key that uniquely identifies an existing payment request.
callback Action Delegate called when payment request has been loaded.
onError Action Delegate called if an error occurs.

Exceptions

Throws a MiddlewareException

Code Message Notes
RequestKey is required A valid RequestKey must be passed in the first parameter
99999 Request not found The RequestKey did not match a payment request on the server

Device Class

Parameter Type Description
DeviceKey String Key that uniquely identifies a device.
Name String Developer/merchant assigned device name
Status String Current device status
PairingCode String If device has not been paired yet, this parameter contains the pairing code needed to be entered on terminal to complete registration.
PairingExpiration DateTime Date/Time that the pairing code will expire. The device will automatically be deleted if not paired by this time.
Config TerminalConfig Terminal configuration. Controls the payment processing features, such as contactless payments, EMV and PIN debit.
Settings DeviceSettings Settings not related to payment processing, such as whether to allow sharing the device between multiple merchants.
Details DeviceDetails Contains details about the registered terminal, such as the model and serial number.

StartTransaction

Sends a payment request to the terminal. Returns a PaymentRequest object that can be used to access the current status of the payment or cancel the transaction.

public PaymentRequest StartTransaction(Transaction Request, Action<String,TransactionResult> onTransactionComplete, Action<String> onStatusUpdate, Action<MiddlewareException> onError)
Parameter Type Description
Request TransactionRequest Transaction details such as amount.
onTransactionComplete Action Method that is called once the device has refreshed. Passes a String containing the current device status
onStatusUpdate Action Method that is called once the device has refreshed. Passes a String containing the current device status
onError Action Method that is called if an exception occurs. Note: this is only called for communication and library issues. If the transaction is declined, the customer cancels the transaction or any other processing related error occurs, onTransactionComplete will be called.

Example

TransactionRequest tran = new TransactionRequest()
{
    Command = "cc:sale",
    Amount = "10.00"
};
request = device.StartTransaction(tran,
    (status, result) =>
    {
      Console.WriteLine("Status: " + status);
        if(result != null)
        {
            Console.WriteLine("Transaction " + result.Result);
            if (result.ResultCode.Equals("A")) Console.WriteLine("  AuthCode: " + result.AuthCode);
            else Console.WriteLine("  Error: " + result.Error);
        }
    },
    (status) =>
    {
        Console.WriteLine("Status: " + status);
    },
    (emw) =>
    {
        Console.WriteLine("Error: " + emw.Message);
    },
  );

ToJSON

Serializes a Device object to a JSON encoded string.

Example

String json = device.ToJSON();

Refresh

Refreshes device information and status.

public void Refresh(Action<PaymentRequest> callback, Action<MiddlewareException> onError)
Parameter Type Description
callback Action Method that is called once the device has refreshed.
onError Action Method that is called if an exception occurs.

Example

device.Refresh((x) =>
{
    Console.WriteLine("Device status: " + device.Status);
}, (ex)=>{
    Console.WriteLine("Error: " + ex.Message);
});

ResetPairing

Unlinks the devicekey from the terminal and generates a new pairing code. The terminal will go back to the pairing screen and the device key can be then be paired to either the same terminal or a new one. This method allows for switching hardware terminals without needing to switch to a new devicekey.

public void ResetPairing(Action<PairingCode> callback, Action<MiddlewareException> onError)
Parameter Type Description
callback Action Method that is called once the device is reset, passes the new pairing code
onError Action Method that is called if an exception occurs.

Example

device.ResetPairing((x) =>
{
    Console.WriteLine("Pairing reset, new pairing code: " + x);
}, (ex)=>{
    Console.WriteLine("Error: " + ex.Message);
});

DeviceDetails Class

Parameter Type Description
Make String Device manufacturer
Model String Model name of terminal
Revision String Firmware version
Serial String Serial number

DeviceSettings Class

This object controls the settings of the payment engine device not related to payment acceptance. Payment acceptance settings are configured via the TerminalConfig.

Parameter Type Description
Timeout int Sets transaction timeout in seconds.
EnableStandalone bool Allows transactions to be initiated by terminal.
ShareDevice bool Allows terminal to be used by any API key including those belonging to other merchants.

TerminalConfig Class

This object describes the requested terminal config. When processing a transaction, the merchants capabilities are also evaluated. Features that are requested and available to the merchant will be enabled on the terminal. For example: If EnableEMV is set to true, but the merchant is configured for a credit card processor that does not support EMV, then the card slot will not be enabled.

Parameter Type Description
EnableEMV bool Enable the smart card slot for EMV processing
EnableDebitMSR bool Enable swiped PIN debit transactions
EnableContactless bool Enable the contactless reader for NFC transactions
TipAdjustAfterAuth bool Allow addition of tip after initial authorization. Disables PIN CVM and No CVM.

PaymentRequest Class

Parameter Type Description
RequestKey String Unique key that identifies the payment request
Status String The current status of the payment request
Result TransactionResult Contains the payment details after a transaction has been completed, such as authorization code.
Timeout int The maximum amount of time allowed for the customer to complete the payment on the terminal. When the timeout is reached, the payment will be canceled.

Refresh

CancelTransaction

Cancels a payment request that is in progress.

public void CancelTransaction(Action<String>callback, Action<MiddlewareException> onError)
Parameter Type Description
callback Action Delegate is called once the payment request has been canceled.
onError Action Delegate is called if an exception occurs.

Example

request.CancelTransaction((x) =>
{
    Console.WriteLine("Request cancelled: " + x);
}, (ex)=>
{
    Console.WriteLine("Exception cancelling tran: " + ex.Message);
});

TransactionRequest Class

This object is passed to the StartTransaction method. The only required parameters are the "Command" and "Amount" fields. The DeviceKey is set automatically by the StartTransaction method and will be ignored if set manually.

Parameter Type Description
DeviceKey String Unique identifier for the terminal that the transaction will be sent to.
Command String Payment command to run. Supported commands are: cc:sale, cc:authonly and cc:refund
Amount String Amount to process payment for. This should be the final amount (unless choosing to allow terminal to prompt for tip and cashback).
AmountDetail AmountDetail Detailed breakdown of the above total Amount.
PoNum String Purchase order number, only required for corporate cards.
Invoice String Invoice number, only first 10 digits are sent to platform
OrderID String Order identifier, alpha numeric
Description String Transaction description (visible to customer on receipt)
Comments String Internal transaction comments (visible only to merchant)
RestaurantTable String Table number
Clerk String Clerk/Cashier name
BillingAddress Address Billing address information
ShippingAddress Address Shipping address information
CustomerEmail String Customer email address
CustomerID String Customer ID
ClientIP String IP address of customer, useful if request is initiated from a server.
GeoLocation String Latitude and longitude to record for transaction. Example: "40.7142700,-74.0059700"
LineItems LineItem[] Array of line item details
ManualKey Boolean Set to true to have the terminal prompt for manual card number entry instead of swipe/dip
PromptTip Boolean Set to true to have the terminal prompt the customer for a tip amount.
PromptCashBack Boolean Set to true to have the terminal prompt the customer for cash back.
PromptSignature Boolean Set to false to prevent the terminal from capturing the customer signature. If the terminal supports signature capture, it will be on by default.
CustomFlow String Optional string that controls the sequence of screens presented to the customer during payment. Leave blank to use the default flow. Example: "amount,payment,result"
SaveCard Boolean Set to true to save the payment data to the customer record
Timeout Integer Set the transaction timeout
BlockOffline Boolean Set to true to have the request refused if the device is currently offline

TransactionResult Class

This object is returned when the payment has been completed.

Parameter Type Description
TransactionKey String Unique identifier for transaction. Can be used to perform actions such as refund and void on a transaction.
RefNum String Numeric sequential transaction reference number. Can be used with older gateway APIs.
AuthAmount String Authroized amount returned from processor.
AuthCode String AuthCode returned from processor.
ProcRefNum String Processor generated transaction reference number (if available).
Result String Result of transaction: Approved, Declined, Error or Partial Approval.
ResultCode String Result code of transaction: A, D, E or P
IsDuplicate String "Y" indicates that a duplicate transaction was detected, the transaction was folded, and the details from the original transaction was returned.
Error String Error message if transaction was a decline or error
ErrorCode String Gateway error code
ProcRefNum String Backend processor reference number (if available)
AVS AvsResult Result of address verification (if manually keyed)
CVC CvcResult Result of card code verification (if manually keyed)
CreditCard CreditCard Information about the credit card used
Token String Reuasable token to charge payment data in a new request

Address Class

Parameter Type Description
FirstName String
LastName String
Company String
Street String
Street2 String
City String
State String
PostalCode String
Country String
Phone String
Fax String

AmountDetail Class

The amount class provides a break down of the total charge amount (the Amount field in the TransactionRequest class);

Parameter Type Description
Tax String Total tax amount
NonTaxable String Set to "Y" to indicate that the transaction is non-taxable.
Cash String For debit, amount of cashback
Tip String Tip amount, only set if choosing not to prompt for tip on terminal
Discount String Amount of order level discount
Shipping String Shipping charges
Duty String Duty charges (for level 3 processing)
EnablePartialAuth bool Include this parameter to authorize partial funds when the full amount is not available. For example, if the total is $10 and the customer only has $5 in their account, $5 will be authorized. If not included in request, partial authorization defaults to disabled.

AvsResult Class

Result of the Address Verification System. This only applies to manually keyed transactions. Swiped, dipped and contactless transactions will not typically receive a result.

Parameter Type Description
Result String String describing the address verification result.
ResultCode String Short code representing result.

CvcResult Class

Result of the card verification code match. This only applies to manually keyed transactions.

Parameter Type Description
Result String String describing the card verification code result.
ResultCode String Short code representing result.

CreditCard Class

Information about the credit card that was used to run the transaction .

Parameter Type Description
Type String Brand of card: Visa, Mastercard, Amex, Discover
Number String The masked card number
CardHolder String The card holder name (if available)
EntryMode String How the payment method was entered: keyed, swiped, dipped, or tapped
CategoryCode String The card category code (if available)
AvsStreet String The avs street number if manually keyed
AvsPostalCode String The avs postal code if manually keyed
Verification String The method of customer verification (if available): signature, pin
Signature String The base64 encoded PNG of the signature image (if available)

MiddlewareException Class

Parameter Type Description
Message String Error message
ErrorCode String If the error is a server side error, this parameter will be set to the gateway ErrorCode.

Common Exceptions

The following exceptions are common to most methods in the library.

ErrorCode Message Notes
21002 API authentication failed The api key or pin is incorrect. Also verify that the gateway host is the same as the one used to create the key. A sandbox key will not work in production.

Change Log

v1.0.9 - 2018-04-17

  • Fixed Error Handling for Dropped Connections
  • Added explicit default setting for TLS 1.2 support

v1.0.8 - 2017-08-25

  • Default url changed from www.usaepay.com to api.paymentengine.io
  • Added Timeout to the TransactionRequest class
  • Added BlockOffline to the TransactionRequest class
  • Added SaveCard to the TransactionRequest class
  • Added Token to the TransactionResult class

v1.0.7 - 2017-08-15

  • Added additional whitelisted domains

v1.0.6 - 2017-05-16

  • Added Verification to the CreditCard class
  • Added Signature to the CreditCard class

v1.0.5 - 2017-02-21

  • Added AuthAmount to the TransactionResult class
  • Added LoadDevices method to the Middleware class

v1.0.4 - 2017-02-15

  • Added CustomFlow to the TransactionRequest class

v1.0.3 - 2017-02-03

  • Added ResetPairing method on the Device class to allow switching terminals without needing a new device key

v1.0.2 - 2017-01-17

  • Added onError delegate to all methods with background processing to fix exception handling
  • Added CreditCard class to TransactionResult
  • Added LoadPaymentRequestByKey to the Middleware class

v1.0.1 - 2017-01-11

  • Changed to target to .Net 4.5