UEMiddleware Class

UEMiddleware

UEMiddleware(String devicename, Activity parent, UEMiddlewareInterface callback, OnLog logger)

Constructor

Parameters

Type Parameter Description
String devicename Name of device, should be "MP200")
Activity parent The parent activity
UEMiddlewareInterface callback Object to handle middleware delegate methods, must implement the UEMiddlewareInterface
OnLog logger Object to handle logger delegate methods, must implement OnLog Interface

Exceptions

  • MiddlewareException will be thrown if any of the parameters are passed with a null value.

clearCachedFiles

void clearCachedFiles()

This method will clear all terminal configuration and software update information that is stored locally on the Android device. This method can only be run before the device is connected. On the next connect(), the terminal configuration will be rewritten to the terminal and software updates will be checked. This method is only necessary in situations where the developer wants to force the config and update checks. It is not normally required, because the middleware will apply changes on a regular schedule.

Delegate Methods

onError(UE_ERROR.DEVICE_CONNECTED)

The onError() delegate method will be called back if an attempt is made to clearCachedFiles while the device is already connected or in the process of connecting. To avoid this error, make sure to call clearCachedFiles after instantiation, but before connect().

connect

This method establishes a connection between a phone/table and the payment device. There are a few overloads for the connect method that allow developers to override the default gateway host (www.EBizCharge.com) and use a specified gateway host (like the sandbox) instead. Developers can also choose a specific bluetooth device rather than the first device found.

void connect(String connType, String sourceKey, String pin, String host)

Use the above to connect to the first device found and use the specified gateway host.

void connect(String connType, String sourceKey, String pin)

Use the above to connect to the first device found and use default gateway host "www.EBizCharge.com".

void connect(BluetoothDevice btDevice, String sourceKey, String pin, String host)

Use the above to connect to a specific bluetooth device "btDevice" with the specified host.

void connect(BluetoothDevice btDevice, String sourceKey, String pin)

Use the above to connect to a specific bluetooth device "btDevice" and default host to "www.EBizCharge.com".

Parameters

Type Parameter Description
String connType (Variant 1) Type of connection between phone/tablet and payment device (Ex: "BT" for Bluetooth, "USB" for USB )
BluetoothDevice btDevice (Variant 2) Bluetooth Device
String sourceKey Merchant's source key
String pin Merchant's PIN
String host (Optional) Host to connect to. This must be just a hostname, not a url. For example: "www.EBizCharge.com" or "sandbox.EBizCharge.com"

Exceptions

  • MiddlewareException will be thrown if any of the parameters are passed in with a null value.
  • MiddlewareException will be thrown if the hostname parameter is not a valid hostname.

Delegate Methods

The following delegates may be returned:

Retrieving Specific Bluetooth Device

A device list can be retrieved by calling the getAvailableDevices() method.

    ArrayList<BluetoothDevice> devices = ueMiddleware.getAvailableDevices();
    if(devices.size() == 0) throw new Exception("No devices found");
    ueMiddleware.connect(devices.get(0), sourceKey, pin, host);

disconnect

void disconnect()

Disconnects the device. Needs to be called whenever a transaction completes.

Delegate Methods

The following delegates may be returned:

doPerformTermUpdate

void doPerformTermUpdate()

Perform any outstanding terminal updates.

getAdvancedAPI

UEAdvancedAPI getAdvancedAPI()

The UEAdvancedAPI is a wrapper to a rest client for accessing the gateway rest api.

Returns

Type Description
UEAdvancedAPI Returns an instance of the api client

Example


try {
    UEAdvancedAPI api = ueMiddleware.getAdvancedAPI();
    JSONObject res = api.sendRESTRequest("https://www.EBizCharge.com/api/v2/info", "GET", sourceKey, pin, request[0]);
} catch(Exception e) {
    e.printStackTrace();
}

Example: Running on Main Thread

The api client is asynchronous and will throw a "NetworkOnMainThreadException" if you attempt to run it on the main UI thread. You will need to create an AsyncTask or something similar:

public class YourActivity extends AppCompatActivity {


        private class YourBtnListener implements Button.OnClickListener {
            @Override
            public void onClick(View v) {
                    JSONObject request = new JSONObject();
                    new RestTask().execute(request);
            }
        }

        private class RestTask extends AsyncTask<JSONObject, Integer, JSONObject> {
            protected JSONObject doInBackground(JSONObject... request) {

                // get api instance
                UEAdvancedAPI api = ueMiddleware.getAdvancedAPI();

                JSONObject res;
                try {
                    // perform rest request
                    res = api.sendRESTRequest("https://www.EBizCharge.com/api/v2/info", "GET", sourceKey, pin, request[0]);

                } catch(Exception e) {
                    res = new JSONObject();
                    try {
                        res.put("error", e.getLocalizedMessage());
                    }catch(Exception e2) {

                    }
                }
                return res;
            }


            protected void onPostExecute(JSONObject result) {
                // do something with the result
                Log.d(TAG, "Result: " + result.toString());
            }

        }
}

getAvailableDevices

ArrayList<BluetoothDevice> getAvailableDevices()

When using the MP200, call this to get the list of available paired bluetooth MP200 devices. This list is filtered and only displays devices containing name "MP200". Devices can be identified by the last 4 of the serial number (located on the back of the MP200).

Returns:

Type Description
ArrayList\<BluetoothDevice> List of available devices

If no devices are found, an empty array list will be returned.

Example

    ArrayList<BluetoothDevice> devices = ueMiddleware.getAvailableDevices();
    if(devices.size() == 0) throw new Exception("No devices found");
    ueMiddleware.connect(devices.get(0), sourceKey, pin, host);

getDeviceInfo

void getDeviceInfo()

Retrieves information about the connected device. You must connect() to the device first. Once all details have been retrieved from the device, the onDeviceInfoReceived() delegate will be called.

Delegate Methods

The following delegates may be returned:

getGatewayInfo

void getGatewayInfo()

Retrieves information on the gateway environment. Calls the onGatewayInfoReceived() delegate when the data is available.

getMerchantCapabilities

void getMerchantCapabilities()

Get the processing capabilities of the merchant. Calls the onMerchantCapabilitiesReceived() delegate with the merchant capabilities.

getReceipt

void getReceipt(String template, String refNum, String sourceKey, String pin, String returnType)

Retrieve a receipt for transaction referenced by refNum field. Receipt template is selected using the template" parameter. The rendered receipt is returned as a String to the onReceiptReceived() delegate.

Parameters

Type Param Description
String template Name of template to pull. Use "PointOfSale" for an EMV compliant receipt template. Merchants can also create custom receipt templates in the merchant console.
String refNum Transaction reference number
String returnType Format of receipt template referenced. Possible values are: "html" or "text"

Exceptions

  • MiddlewareException will be thrown if any of the parameters are passed in with a null value.

Delegates

  • onReceiptReceived() will be called once the receipt is successfully retrieved from the gateway.
  • onError() will be called if an error occurs, such as error connecting to the gateway. Other errors include:
  • onError(RECEIPT_NOT_FOUND) will be called if the template did not match any of the named receipt templates available on the merchants account.
  • onError(TRANSACTION_NOT_FOUND) will be called if the refNum did not match a transaction.
  • onError(RECEIPT_FORMAT_NOT_FOUND) will be called if the receipt is either not available in the requested returnType or an invalid returnType was passed.

Example

public void onTransactionComplete(UEMTransactionResult transResults) {
    Log.d(TAG, "onTransactionComplete()");

    if (!transResults.hasError()) {

        ueMiddleware.getReceipt("PointOfSale",RefNum,"html");

    }
}

public void onReceiptReceived(String receipt) {
    Log.d(TAG, "onReceiptReceived()");
    Log.d(TAG, "Receipt: " + receipt);
}

hardReset

void hardReset()

Aborts any running operations and causes the terminal to reboot. Please note: This method is not supported with the Castles MP200.

isConnected

boolean isConnected()

Returns true if phone/tablet is connected to payment device, and returns false otherwise.

returnPartialAuthDecision

void returnPartialAuthDecision(boolean doAuth)

When asked for partial auth through the onPromptForPartialAuth(String String), use this command to continue the transaction.

Parameters

Type Parameter Description
boolean doAuth Set to true to proceed with the auth amount, and false to decline and discontinue the transaction.

setConnectionType

void setConnectionType(int connType)

Sets connection type for MP200.

Parameters

Type Parameter Description
int connType 0 = BT (bluetooth), 1 = USB

setSourceAndPin

void setSourceAndPin(String sourceKey, String pin)

Sets the gateway source key, and pin. Must be set before the transaction can be sent.

Parameters

Type Parameter Description
String sourceKey Merchant's source key
String pin Merchant's pin

setTerminalConfig

public void setTerminalConfig(TerminalConfig config):
public void setTerminalConfig(TerminalConfig config, boolean force):

The command sets the terminal configuration. This must be called prior to connect()

Please Note: The middleware will compare the requested terminal configuration against the merchant capabilities. It is possible that some features such as EMV, contactless and Tip Adjust are not available due to the merchant's platform config. If no terminal config is set, the middleware will use the last applied config (stored on terminal). If no config exists on the terminal the middleware will default to the max capabilities of the merchant.

There are two base configs:

ALLCVM

This terminal config enables all EVM cardholder verification methods including signature, PIN and NOCVM (for low ticket transactions). Tip amounts must be added prior to authorization and the amount can not be adjusted after authorization. This config can be retrieved with TerminalConfig.getAllCVMConfig() and contains the defaults:

  • enable_emv = true;
  • enable_debit_msr = true;
  • enable_tip_adjust = false;
  • enable_contactless = true;

Tip Adjust

Allows a tip amount to be added after authorization. This is achieved by disabling all CVMs other than signature. This config can be retrieved with TerminalConfig.getTipAdjustConfig() and contains the defaults:

  • enable_emv = true;
  • enable_debit_msr = false;
  • enable_tip_adjust = true;
  • enable_contactless = true;

Parameters

Type Parameter Description
TerminalConfig config The terminal config object describing desired features.
boolean force (optional) Forces an update to the terminal config. The middleware keeps track of the currently active terminal config and only writes a new one to the terminal if a change is detected. By setting force to "true", it will ignore the stored config and write the new config to the terminal. This can also be achieved by using the clearCachedFiles() method.

Exceptions

  • MiddlewareException will be thrown if any of the parameters are passed in with a null value.

Examples

// Use AllCVM base config  (Credit/Debit selection enabled)
TerminalConfig tc = TerminalConfig.getAllCVMConfig();
ueMiddleware.setTerminalConfig(tc);
ueMiddleware.connect(mConnType, sourceKey, pin, host);
// Use AllCVM base config and then disable Credit/Debit selection
TerminalConfig tc = TerminalConfig.getAllCVMConfig();
tc.setEnable_debit_msr(false);
ueMiddleware.setTerminalConfig(tc);
ueMiddleware.connect(mConnType, sourceKey, pin, host);
// Use TipAdjust base config
TerminalConfig tc = TerminalConfig.getTipAdjustConfig();
ueMiddleware.setTerminalConfig(tc);
ueMiddleware.connect(mConnType, sourceKey, pin, host);

Delegate Methods

onError(UE_ERROR.DEVICE_CONNECTED)

The onError() delegate method will be called back if an attempt is made to setTerminalConfig while the device is already connected or in the process of connecting. Make sure to call setTerminalConfig after instantiation but before connect().

setTipAdjust

void setTipAdjust(boolean tipAdjust)

Enables tip adjust.

Parameters

Type Paremeter Description
boolean tipAdjust Set to true to enable tip adjust in transaction, false otherwise

startTransaction

void startTransaction(HashMap<String, String> transInfo,
                                             boolean manualKey,
                                             boolean promptTip)

Starts a transaction request. The terminal will prompt the customer to swipe, tap or dip their card depending on the merchant's capabilities. If prompTip parameter is set to true then they customer will be asked for a tip amount. The customer is then prompted to confirm the amount. The transaction is sent to the gateway for processing. When the gateway response is received or an error occurs, the onTransactionComplete event will be triggered. If the customer hits the cancel button on the terminal, the onTransactionCancelled event will be triggered. Developers will need to implement these two methods on their delegate to properly handle the transaction flow.

Parameters

Type Parameter Description
HashMap transInfo HashMap that holds information about the transaction. See below.
boolean manualKey Set to true to trigger a manually-keyed transaction
boolean prompTip Set to true to prompt the customer for a tip

Exceptions

  • MiddlewareException will be thrown if any of the parameters are passed in with a null value.

Supported Commands

cc:sale
This command is the default processing command. The 'cc:sale' command runs a standard credit/debit card sale. It will charge the customers credit/debit card for the amount specified. This command requires that the amount field be populated. Once called, the terminal will collect the payment method from the customer and then send the transaction for processing. If the charge is successful, the transaction will be placed in the merchant's currently open batch for settlement. As long as the merchant has their batch set to autoclose, no further action is required to capture these funds.

cc:authonly
This command runs a credit/debit card authorization. This command requires that the amount field be populated. Once called, the terminal will collect the payment method from the customer and then send the transaction for processing. If approved, the funds will be held in the customers account. The funds will remain oh hold until either the transaction is captured and settled, or until the authorization code expires. The length of time before an authorization expires varies from bank to bank, but generally it is recommended that authorizations be captured within 24-48 hours. Merchants should consult their merchant service provider for information specific to their account. If a merchant does not capture the transaction, no funds will be received by the merchant.

capture
This command moves 'cc:authonly' transactions into the batch for settlement. The original Transaction ID (refnum) must be passed in refNum field. Additionally, the amount of originally authorized may be adjusted by passing the amount field. The tolerances for the settle amount vary depending on the type of merchant account and the merchant service provider. The transaction will be placed in the merchant's currently open batch for settlement. As long as the merchant has their batch set to autoclose, no further action is required to capture these funds.

adjust This command allows you to make changes to an existing (unsettled) sale. The authorization amount can be increased (incremental authorization), decreased (partial reversal), or not changed. Additional data elements such as tax amount and PO number can also be added. The original Transaction ID (refnum) must be passed in refNum field. The tolerances for the settle amount vary depending on the type of Merchant Account and the merchant service provider. The adjust and capture commands function identically except that the adjust command does not place the transaction in the batch (see example below).

cc:credit
This command performs an open credit (refund) to a card. It requires the amount field be populated. The terminal will then prompt the customer for the payment method, and then send the transaction to the gateway for processing.

void:release
This command cancels a pending (sale, authonly, or credit) transaction. For credit card transactions, this command removes the transaction from the current batch. There is a limited amount of time that a void may be run. For credit cards, a transaction can no longer be voided once the batch has been closed. The void requires that the original Transaction ID number be passed in the refNum field. The terminal is not used, and the transaction is sent directly to the gateway.

transInfo Fields

The majority of these are optional, the only required field is "Amount".

Key Description
command Processing command, typically "cc:sale" or "cc:authonly". See above for more information.
amount Total amount to authorize (including tax, shipping, etc). If prompTip parameter is set to "true", this amount will be added to the tip for the total authorization amount.
tax Tax amount
nontaxable Transaction is non taxable
tip If the prompTip parameter is not set, the tip may be passed in this field. The third option is to use the Tip Adjust terminal config which allows for the tip to be added post authorization.
shipping Shipping amount
duty Duty charge (Required only for level 3)
discount The amount of any discounts that were applied.
description Transaction description
comments Internal transaction notes (not included on customer receipt). Optional.
custid Merchant assigned customer id.
invoice Invoice number, only the first 11 characters are used.
orderid Order identifier. This field can be used to reference the order to which this transaction corresponds. This field can contain up to 64 characters and should be used instead of invoice when orderid is longer that 10 digits.
ponum Purchase Order number. Only required for corporate purchasing cards.
clerk Indicates the clerk/person processing transaction, for reporting purposes. (optional)
tranterm Indicates the terminal used to process transaction, for reporting purposes. (optional)
resttable Indicates the restaurant table, for reporting purposes. (optional)
enablePartialAuth Set to "true" to enable partial authorization.
refNum Gateway assigned transaction id number. Necessary for commands that modify an existing transaction, such as "adjust" or "void:release".
timeout Max number of seconds to wait for a response from the gateway. This does not limit how long the customer has to swipe their card.
target deprecated set the gateway url. This is now done in the connect().

Address Fields:

Billing Key Shipping Key Description
billfname shipfname First Name
billlname shiplname Last Name
billcompany shipcompany Company Name
billstreet shipstreet Street Address
billstreet2 shipsreet2 Additional street information (if needed)
billcity shipcity City
billstate shipstate State
billzip shipzip Zip/Postal code
billcountry shipcountry Country
billphone shipphone Phone Number
email
fax
website

Line Item Details:

Replace * with the line number 1-99999.

Field Max Length Description
line*productrefnum 12 (optional) Gateway assigned product RefNum, used for inventory control.
line*sku 32 Product id, code or SKU
line*name 255 Item name or short description
line*description 64k Long description
line*cost 00000000.00 Cost of item per unit of measure (before tax or discount)
line*qty 00000000.0000 Quantity
line*taxable 1 Y = Taxable, N = Non-taxable
line*taxrate 00.000 Tax rate for line (only required for level 3 processing).
line*taxamount 00000000.00 Amount of tax charge for line (if left blank will be calculated from taxrate)
line*um 12 Unit of measure. If left blank or an invalid code is sent, EA (Each) will be used.
line*commoditycode 12 Commodity code (only required for level 3 processing). See http://www.unspsc.org/ for valid list of codes.
line*discountrate 000.000 Discount percentage for line (only required for level 3 processing).
line*discountamount 00000000.00 Discount amount for line (if left blank will be calculated from discountrate).

Delegate Methods

The following delegates may be returned:

  • onTransactionComplete() method will be called for all errors, declines or approvals. It is called after all transaction operations have been completed.
  • onPromptForPartialAuth() method will be called when a transaction is approved for less that the full amount requested. The developer must tell the middleware how they want to complete the transaction by calling the returnPartialAuthDecision() method.
  • onSeePhoneNFC() method will be called during a contactless transaction if the customer needs to take an additional step on their phone (such as enter a password). The transaction will continue once the user takes this action, the developer does not need to do anything, and it is not required that this delegate do anything.
  • onStatusChanged() is called when the transaction moves to the next step in the processing flow.
  • onError() - is called when startTransaction is passed invalid parameters.
  • onError(INVALID_COMMAND) is called when "command" in "transInfo" was not one of the supported commands.
  • onError(REFNUM_REQUIRED) is called when "void:release" and "capture" commands are called and the "refnum" parameter was not included.

Example: Extracting the RefNum from onTransactionCompleted

The RefNum is needed if you are going to adjust or void the transaction.

public void onTransactionComplete(UEMTransactionResult transResults) {
    Log.d(TAG, "onTransactionComplete()");

    String RefNum = "NA";
    if(transResults.getGatewayTransactionResults().containsKey("UMrefNum")) RefNum = transResults.getGatewayTransactionResults().get("UMrefNum");
}

Example: Adjusting a Transaction

The following example can be used to add a tip to a transaction. Please note: This will only work on an EMV transaction if the Terminal Config has been set to tipadjust. RefNum is the value received during the authorization.

HashMap<String,String> captureInfo = new HashMap<String,String>();
captureInfo.put("command", "adjust");
captureInfo.put("refNum", RefNum);
captureInfo.put("tip", "1.00");

BigDecimal totalAmount = new BigDecimal(transInfo.get("amount"));
totalAmount.add(new BigDecimal("1.00"));

captureInfo.put("amount", totalAmount.toString());
Log.d(TAG, " captureInfo: " + captureInfo.toString());


try {
    ueMiddleware.startTransaction(captureInfo,  false, false);
} catch (MiddlewareException e) {
    e.printStackTrace();
}

Example: Voiding a Transaction

The following example demonstrates voiding a transaction and releasing the funds back to the cardholder. RefNum is the value received during the authorization.

HashMap<String,String> voidInfo = new HashMap<String,String>();
voidInfo.put("command", "void:release");
voidInfo.put("refNum", RefNum);
Log.d(TAG, " voidInfo: " + voidInfo.toString());

try {
    ueMiddleware.startTransaction(voidInfo,  false, false);
} catch (MiddlewareException e) {
    e.printStackTrace();
}

updateDevice

void updateDevice()