> For the complete documentation index, see [llms.txt](https://docs.verifone.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.verifone.com/psdk-latest/reference-material/code-labs/coding-guidelines.md).

# Coding Guidelines

{% columns %}
{% column width="41.66666666666667%" %} <i class="fa-clock">:clock:</i> 8 minutes reading time\ <i class="fa-calendar">:calendar:</i> Last updated: 23rd November, 2023
{% endcolumn %}

{% column width="16.666666666666668%" %}

{% endcolumn %}

{% column width="41.66666666666664%" %}
✅ Coding Guidelines

✅ Transaction Processes

✅ API Usage & Communication

✅ Best Practices
{% endcolumn %}
{% endcolumns %}

{% stepper %}
{% step %}

### Coding Guidlines

The SDK has a few core concepts before we get started.

#### Definitions

* **POS** - The Android application using the SDK. This may or may not be an actual Point-of-Sale application. This application is generally used by a cashier or employee of the merchant.
* **POI** - The point of interaction for the end customer, this is the device that collects card information and other similar input.
* **Payment Service** - A background service running on the Android system that receives the calls from the SDK and either handles it directly or adapts it to the protocol used by the POI.
* **Payment App** - The application running on the POI that handles the card information and other payment / transaction details, communicating this to the host to authorize the payment, or storing the data for later and issuing a temporary approval if offline authorization is enabled.
* **Host / Payment Host** - Receives the card data and other information from the Payment App, and actually enables the funds to be transferred. This can be a payment gateway, processor, etc.
* **Session** - The period between [TransactionManager.startSession2(…)](https://docs.verifone.com/psdk-api-latest/android-java/index/transactionmanager#startsession2-transaction) and [TransactionManager.endSession()](https://docs.verifone.com/psdk-api-latest/android-java/index/transactionmanager#endsession) where the POI is reserved for the POS, blocking anything else from performing operations with the POI, and keeping the screen in a ready state to display information from the POS.
* **Order** - A collection of basket items and payments that are related by the same Invoice, linking the original basket items, refunded/replaced items, and all of the associated payments such as sales, pre-auths, pre-auth completions, voids, refunds, etc. There is no explicit object in the SDK for an order, it is an abstract concept represented by a single Invoice ID.
* **Transaction** - A collection of basket items and payments that are related by the same Invoice for a specific purpose. Similar to an Order, except that it has a type which defines its purpose, such as `Transaction.PAYMENT_TYPE` or `Transaction.REFUND_TYPE`. There can be one or more transactions for an order. There is always one transaction object associated with a Session.

#### PaymentDeviceState

PSDK maintains the last known connection state between POS and terminal state in [PaymentDeviceState](https://docs.verifone.com/psdk-api-latest/android-java/index/paymentdevicestate). This can be queried using the API [PaymentSdk.getDeviceInformation()](https://docs.verifone.com/psdk-api-latest/android-java/index/paymentsdkinterface#getdeviceinformation). The following table indicates possible device states and the follow-up actions that POS can take.

| Index | PaymentDeviceState        | Possible Actions from POS                                                                                                                                                                                                                                                                                                 |
| ----- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1     | NOT\_CONNECTED            | POS should call [PaymentSdk.initialize(…)](https://docs.verifone.com/psdk-api-latest/android-java/index/paymentsdkbase#initialize)                                                                                                                                                                                        |
| 2     | CONNECTING                | POS needs to wait for the callback to see the result of Initialize request.                                                                                                                                                                                                                                               |
| 3     | CONNECTED                 | POS can request regular operation API like [loginWithCredentials](https://docs.verifone.com/psdk-api-latest/android-java/index/transactionmanager#loginwithcredentials-logincredentials), [startsession2](https://docs.verifone.com/psdk-api-latest/android-java/index/transactionmanager#startsession2-transaction) etc. |
| 4     | DISCONNECTING             | PSDK is in the process of teardown, POS needs to wait for the callback to see the result of TearDown request.                                                                                                                                                                                                             |
| 5     | CONNECTION\_LOST          | Connection lost and cannot be recovered. [PaymentSDK.TearDown(…)](https://docs.verifone.com/psdk-api-latest/android-java/index/paymentsdkbase#teardown) call required                                                                                                                                                     |
| 6     | MAINTENANCE\_IN\_PROGRESS | To use the terminal, POS needs to wait till it receives the END\_MAINTENANCE notification event.                                                                                                                                                                                                                          |

#### PSDK State Transitions

The table below itemizes the available actions and subsequent transition states for each action.

#### Index

| Index         | Actions                  | Need Login | Need Session | TransactionManager Transient State | TransactionManager Final State (Success/Failure) |
| ------------- | ------------------------ | ---------- | ------------ | ---------------------------------- | ------------------------------------------------ |
| 1             | Initialize               | No         | No           | NA                                 | NOT\_LOGGED\_IN/UNKNOWN                          |
| 2             | Login                    | No         | No           | LOGGING\_IN                        | LOGGED\_IN/NOT\_LOGGED\_IN                       |
| 3             | StartSession             | Yes        | No           | SESSION\_OPENING                   | SESSION\_OPEN/LOGGED\_IN                         |
| 4             | HandleLineItem           | Yes        | Yes          | AWAITING\_TERMINAL                 | No state change                                  |
| 5             | FinalizeBasket           | Yes        | Yes          | AWAITING\_TERMINAL                 | No state change                                  |
| 6             | PresentReceiptOptions    | Yes        | Yes          | AWAITING\_TERMINAL                 | No state change                                  |
| 7             | RequestCardData          | Yes        | Yes          | AWAITING\_TERMINAL                 | No state change                                  |
| 8             | PerformStoredValueAction | Yes        | Yes          | AWAITING\_TERMINAL                 | No state change                                  |
| 9             | PerformPayment           | Yes        | Yes          | PAYMENT\_PROCESSING                | No state change                                  |
| 10            | HandleResponse           | Yes        | Yes          | PAYMENT\_PROCESSING                | No state change                                  |
| 11            | EndSession               | Yes        | Yes          | NA                                 | LOGGED\_IN                                       |
| 12            | Reconcile                | Yes        | No           | AWAITING\_TERMINAL                 | No state change                                  |
| 13            | QueryTransactions        | Yes        | No           | AWAITING\_TERMINAL                 | No state change                                  |
| 14            | ReprintReceipt           | Yes        | No           | NA                                 | No state change                                  |
| 15            | Logout                   | Yes        | No           | NA                                 | NOT\_LOGGED\_IN                                  |
| 16            | PresentContent           | No         | No           | NA                                 | No state change                                  |
| 17            | RequestInput             | No         | No           | AWAITING\_TERMINAL                 | No state change                                  |
| 18            | DeviceManagementCommand  | No         | No           | AWAITING\_TERMINAL                 | No state change                                  |
| 19            | GetState                 | No         | No           | NA                                 | Synchronous, no state change                     |
| 20            | QueryCapability          | No         | No           | NA                                 | No state change                                  |
| 21            | Abort                    | No         | No           | NA                                 | No state change                                  |
| 22            | Print                    | No         | No           | NA                                 | No state change                                  |
| 23            | Encryption               | No         | No           | AWAITING\_TERMINAL                 | No state change                                  |
| 24            | DeviceVitals             | No         | No           | NA                                 | No state change                                  |
| 25            | Pin                      | No         | No           | NA                                 | No state change                                  |
| 26            | Teardown                 | No         | No           | NA                                 | UNKNOWN                                          |
| {% endstep %} |                          |            |              |                                    |                                                  |

{% step %}

### Transaction Processes

#### Logging In

Logging in ([TransactionManager.loginWithCreadentials(…)](https://docs.verifone.com/psdk-api-latest/android-java/index/transactionmanager#loginwithcredentials-logincredentials)) informs the POI that a cashier is present, and enables the POI to download/configure itself based on the cashier ID.

#### Starting a Session

Starting a session ([TransactionManager.startSession2(…)](https://docs.verifone.com/psdk-api-latest/android-java/index/transactionmanager#startsession2-transaction)) reserves the POI for use by the Point of Sale (POS), enabling an order to be built and payments to be processed. There should only be one "order" per session, where an order is an optional collection of basket items and a set of payments/refunds/voids, all associated with a single Invoice ID. It is acceptable to manage a single order across multiple sessions, but it's not recommended to handle multiple orders within a single session.

#### Payment Processing

Starting a payment or performing some other payment-related action will move it to the payment processing state.

![psdk\_payment\_process](https://verifone.cloud/sites/default/files/migrate-markdown/tutorials/files/coding_guidelines.png)
{% endstep %}

{% step %}

### API Usage and Communication

#### Actions Without a Session

There are some actions that can be performed without an active session but after login, primarily actions on the ReportManager. Other actions, related to setting parameters such as [`PaymentSdk.getDeviceInformation()`](https://docs.verifone.com/psdk-api-latest/android-java/index/paymentsdkbase#getdeviceinformation), can be performed even before login.

#### Asynchronous Calls

All calls are asynchronous (except a few). Nearly all of the calls are asynchronous, returning an immediate value to indicate if the call could be successfully transmitted, and later returning the actual result to the listener. The immediate value returned only indicates if it was possible to send the call across the bound interface and that the bound interface is in a state to accept the call and queue it to be sent to the Point of Interaction (POI). If this immediate result returns an error status, the listener will not receive any event for the call.

The asynchronous calls are placed into a queue, so if one were to call [loginWithCredentials()](https://docs.verifone.com/psdk-api-latest/android-java/index/transactionmanager#loginwithcredentials-logincredentials), [startSession2()](https://docs.verifone.com/psdk-api-latest/android-java/index/transactionmanager#startsession2-transaction), [startPayment()](https://docs.verifone.com/psdk-api-latest/android-java/index/transactionmanager#startpayment-payment), the payment would be properly handled if the preceding calls succeeded without error, otherwise they are going to fail due to a state issue (see [PSDK State Transitions](#state-matters)).

The exceptions to this rule do not require communication with the POI, allowing the result to be returned immediately. These are listed below.

* [TransactionManager.getState()](https://docs.verifone.com/psdk-api-latest/android-java/index/transactionmanager#getstate)
* [TransactionManager.isCapable(…)](https://docs.verifone.com/psdk-api-latest/android-java/index/transactionmanager#iscapable-string)
* [TransactionManager.getBasketManager()](https://docs.verifone.com/psdk-api-latest/android-java/index/transactionmanager#getbasketmanager)
* [TransactionManager.getReportManager()](https://docs.verifone.com/psdk-api-latest/android-java/index/transactionmanager#getreportmanager)
* [BasketManager.getBasket()](https://docs.verifone.com/psdk-api-latest/android-java/index/basketmanager#getbasket)
* [BasketManager.getCurrentAmountTotals()](https://docs.verifone.com/psdk-api-latest/android-java/index/basketmanager#getcurrentamounttotals)
* [ReportManager.isCapable(…)](https://docs.verifone.com/psdk-api-latest/android-java/index/reportmanager#iscapable-string)

#### Separate Processes means Separate Objects

The services are separate processes, which means that the memory is separate. Each API call to a process marshals and unmarshalls the objects across the process boundary, meaning that each application has a copy of the objects being used. This can be confusing and lead to mistakes while programming, such as setting a field on an object within the Point of Sale (POS) and expecting it to be set within the Payment Service, or modifying an object locally without using the latest version of that object from the service, and causing a merge issue. The services can perform most of the basic merges necessary to run easily, but it's important to remember that if an object is changed locally and the update needs to be reflected in the service, this object must be sent to the service using one of the API calls defined. It is also important to keep local copies updated with or replaced by the latest objects received by the listener.
{% endstep %}

{% step %}

### Best Practices

#### User Inactivity

It is important that a session not be kept open without any interaction, as it blocks the POI from performing important internal updates and prevents any other application from being able to use the device. We recommend ending the session if the cashier is inactive somewhere between 10 and 30 seconds. It can be good to immediately start a session once a previous session is ended, this can help a cashier dealing with a long line and needing to key in orders rapidly, but if the cashier is not doing anything, please end the session.

#### Threads of Execution

It is generally best to interact with the PSDK from some context which is different than the UI. While most calls into the PSDK will not block for long, there are a couple that might delay UI execution, such as initialization.

It is also important that when events are received, the actual processing of the event happens in a separate context from the one which received the event. We only send events from one thread, so any long processing of one event will delay subsequent events from being received. This is generally not desirable behavior.

Finally, when running on Android or Java, it is best for all calls into the PSDK be performed from a single thread/context. On these platforms, calls into the PSDK attach to the JVM, which can be an expensive operation, but contexts which have already attached do not need to perform that operation on subsequent calls.
{% endstep %}
{% endstepper %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.verifone.com/psdk-latest/reference-material/code-labs/coding-guidelines.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
