# Auto-Debit

Welcome to the Ottu `Auto Debit API` documentation. Our API provides businesses and developers with the ability to incorporate Ottu's auto-debit functionality into their existing systems, allowing for seamless and automated payment processing.

**But what is auto debit?** Auto debit is a financial arrangement wherein a customer authorizes a company to deduct money from their account, whether on a recurring basis, an unscheduled basis, or potentially in the future, the deduction could occur on an event-based, installment, or other specified terms. The frequency and amount of these deductions are determined in advance and can vary depending on the type of agreement, be it a subscription, a loan repayment, or any other kind of periodic payment.&#x20;

Imagine you are a merchant providing a monthly subscription service to your customers. Each month, you need to charge your customers, but the process becomes tedious when you have to remind them to make the payment or when they have to manually make the payment each time. This is where the auto debit functionality shines. With Ottu's `Auto Debit API`, you can schedule these charges automatically, ensuring seamless business operations and improving customer experience, all while saving valuable time and effort.&#x20;

In the following sections, we will guide you through the steps of [Setup](#setup), [Authentication](#authentication), and how to use the various endpoints available. This will give you the tools and knowledge needed to fully leverage the capabilities of the Ottu `Auto Debit API`.&#x20;

## [Setup](#setup)

Before you can integrate with Ottu's `Auto Debit API`, there are several prerequisites that need to be fulfilled. These prerequisites are essential to ensure that the API functions correctly and securely.&#x20;

1. **Payment Gateway:** \
   A Payment Gateway with auto debit enabled is required for the API to work. The Payment Gateway is a tool that authorizes and processes transactions between you and your customers. For a detailed understanding of what a Payment Gateway is and how it functions, please refer to our [Payment Gateway](https://docs.ottu.com/user-guide/payment-gateway) User Guide.
2. **Checkout API:** \
   Before you call the `Auto Debit API`, the [Checkout API](https://docs.ottu.com/developer/checkout-api) must be used to create a payment transaction. This is where important details such as the [amount](https://docs.ottu.com/checkout-api#amount-string-required), customer data, and more are added. Once the payment has been created via the `Checkout API`, a [session\_id](https://docs.ottu.com/checkout-api#session_id-string-mandatory) will be generated. This `session_id` is a key parameter for the `Auto Debit API`.
3. **Tokenization and User Cards API:** \
   Understanding and utilizing the [Tokenization](https://docs.ottu.com/developer/tokenization) and [User Cards](https://docs.ottu.com/developer/user-cards) API is an essential step in the process. In order to handle transactions securely and keep sensitive data such as card information safe, Ottu uses a process called tokenization. When a user saves a card, the sensitive card data is replaced with a unique token generated by the PG. \
   In the context of the `Auto Debit API`, you will need to [retrieve](https://docs.ottu.com/user-cards#fetch-cards) these tokens (i.e., the saved card details of the customer) by calling the `User Cards API`. The tokens received from this API call are used to identify which card will be used for the auto debit process, ensuring a secure transaction without exposing sensitive customer information. Thus, getting familiar with the [User Cards API](https://docs.ottu.com/developer/user-cards) and the concept of [tokenization](https://docs.ottu.com/developer/tokenization) is crucial to the successful implementation of the `Auto Debit API`.
4. **Payment Webhook Response:** \
   Lastly, you need to be familiar with the [Payment Webhook response](https://docs.ottu.com/developer/webhooks/payment-notification). This response is returned by the `Auto Debit API`, providing important information about the transaction status.
5. **Optional:** Checkout SDK\
   [Checkout SDK](https://docs.ottu.com/developer/checkout-sdk) As an optional but highly recommended step, you can utilize our `Checkout SDK`. This software development kit does the heavy lifting for you by handling tasks such as rendering all the payment methods, showing saved cards, and giving payers the option to save their card for future transactions.
6. **Optional:** `Payment Methods API`\
   The [Payment Methods API](https://docs.ottu.com/developer/payment-methods) serves as a preliminary step to gather dynamic parameters, primarily the [pg\_code](https://docs.ottu.com/checkout-api#pg_codes-array-required), required for the subsequent [Checkout API](https://docs.ottu.com/developer/checkout-api) call. Think of it as a preparatory API call that equips you with the necessary “ammunition” for the main transactional API.

\
**Why is it optional?**\
If you’re already aware of the specific `pg_code` you intend to use consistently, you can bypass this step by storing that `pg_code` directly in your system. However, invoking the `Payment Methods API` ensures that you’re always updated with the latest available payment gateways or any changes in the configuration. This dynamic approach ensures a more resilient and adaptable integration with Ottu.

Once you've fulfilled these prerequisites, you're ready to integrate the `Auto Debit API`. The following sections of this document will guide you through the authentication process and the usage of various API endpoints.

### [Boost Your Integration](#boost-your-integration)

To optimize the integration of your Auto-Debit API, our official packages are designed to simplify the process significantly. These packages efficiently manage the complexities of API integration, enabling you to concentrate on the essential aspects of your project.

Here are the currently available packages:

* **Python SDK**: Enhances access to auto-debit functionalities through a Pythonic interface, effectively abstracting the intricacies of API calls to boost developer efficiency. [Learn more](https://github.com/ottuco/ottu-py?tab=readme-ov-file#auto-debit-autoflow)
* **Django SDK**: Integrates auto-debit features smoothly into Django-based applications, providing Django-specific enhancements that streamline auto-debit transactions. [Continue exploring](https://github.com/ottuco/ottu-py?tab=readme-ov-file#auto-debit-autoflow-1)

To fully leverage these packages, a thorough understanding of the foundational concepts and structures detailed in the documentation is essential for effective and sustainable integration.

## [Authentication](#authentication)

**Supported Methods**

* [Private API Key](https://docs.ottu.com/authentication#private-key-api-key)
* [Basic Authentication](https://docs.ottu.com/authentication#basic-authentication)

For detailed information on authentication procedures, please refer to the [Authentication documentation](#authentication).

## [How It Works](#how-it-works)

Ottu’s `Auto Debit API` process is intricately designed to navigate the nuances of both cardholder and merchant initiated transactions. This process revolves around two primary phases:  [First Payment](#first-payment) and [Subsequent Payments](#subsequent-payments).

* #### [Cardholder Initiated Transactions (CIT)](#cardholder-initiated-transactions-cit)

  These are transactions initiated and authenticated by the cardholder. A typical example is the [First Payment](#first-payment) where the cardholder is present, providing payment details and authorizing the transaction, commonly seen in e-commerce purchases or at physical point-of-sale.
* #### [Merchant Initiated Transactions (MIT)](#merchant-initiated-transactions-mit)

  These transactions come into play during [Subsequent Payments](#subsequent-payments). Triggered by the merchant based on a prior [agreement](#what-is-an-agreement) with the cardholder, they are frequently observed in scenarios like monthly subscriptions or certain installment payments.

For a smooth transaction process, it’s important to understand the role of an [agreement](#what-is-an-agreement) before initiating the first payment. The Agreement defines the terms for subsequent `MITs`, clarifying when and how the merchant can carry out these transactions.

#### [**What is an Agreement?**](#what-is-an-agreement)

An agreement represents a commercial contract you establish with your payer, allowing you to store and utilize their payment details for [Subsequent Transactions](#subsequent-payments). This mutual understanding between you (the merchant) and the payer permits processing their payment details under specific conditions.&#x20;

**Examples include:**

* **Recurring Payments:** Regular payments, like a mobile phone subscription, where the payer authorizes billing at intervals (e.g., monthly). The amount can be fixed or variable.
* **Installment Payments:** An arrangement to split a single purchase into multiple payments at defined intervals, like six monthly installments.
* **Unscheduled Payments:** Where the payer authorizes automatic deductions for a payment when required, such as auto top-ups when an account balance is low.
* **Other:** Agreements that don’t fit the recurring, installment, or unscheduled categories, like split tender payments.

{% hint style="info" %}
Please be aware that the **availability** of specific agreement types is subject to the regulations of individual countries’ central banks. Before setting up a particular agreement, it’s essential to check its applicability in your jurisdiction. If you’re unsure or need clarity regarding the types of agreements available in your country, don’t hesitate to contact our support team at <mark style="color:blue;">**<support@ottu.com>**</mark>. We’re here to help!
{% endhint %}

#### **Importance for Merchants:**

Before utilizing Ottu's auto-debit feature, it is crucial to confirm the existence of the necessary agreement. For more information about the `agreement` parameters, please refer to the details in the [agreement object](https://docs.ottu.com/checkout-api#agreement-object-details).

Below table outlines mandatory and optional parameters for two agreement types: `recurring` and `unscheduled`, streamlining the agreement creation process.

<table data-full-width="false"><thead><tr><th align="center">type</th><th>                               Mandatory</th></tr></thead><tbody><tr><td align="center"><code>recurring</code></td><td><ul><li><code>id</code></li><li><code>frequency</code></li><li><code>amount_variability</code></li><li><code>expiry_date</code></li><li><code>cycle_interval_days</code></li><li><code>total_cycles</code></li></ul></td></tr><tr><td align="center"><code>unscheduled</code></td><td><ul><li><code>id</code></li><li><code>frequency</code></li></ul></td></tr></tbody></table>

{% hint style="info" %}
If you have requirements for an `auto-debit` type other than **`recurring`/`unscheduled`** or have specific customizations in mind, please don’t hesitate to contact us at <mark style="color:blue;">**<support@ottu.com>**</mark>. We’re here to support and assist you in tailoring a solution that best fits your business needs
{% endhint %}

For the [First Payment](#first-payment), the agreement lays the foundation by defining the terms under which the initial transaction takes place. During this step, the customer selects the specific card they wish to associate with the auto-debit payment. This chosen card will be the only one charged for all [Subsequent Payments](#subsequent-payments) based on the agreement's terms.&#x20;

**It's important to note that:**

* Only **one** card can be linked with an [agreement](#what-is-an-agreement) at any given time, and only that card can be charged for [Subsequent Payments](#subsequent-payments).
* If there's a need to change the card associated with the agreement, it can only be done through another [Cardholder Initiated Transaction](#cardholder-initiated-transactions-cit) (CIT). This means the customer must either enter a new card or select from their saved cards the card they desire for future payments.
* Even if a customer has multiple saved cards in their account, only the card specifically selected for the auto-debit payment can be charged. Other cards in the customer's account cannot be used for this agreement.

For a comprehensive list of agreement parameters and further details, refer to the [Checkout API documentation](https://docs.ottu.com/webhooks/payment-notification#agreement-object-conditional).

#### :digit\_one:[ **First Payment**](#first-payment)

For the initial payment, which is a [Cardholder Initiated Transaction](#cardholder-initiated-transactions-cit) (CIT), the payer must be online to initiate and perform the transaction. With the `auto_debit` for payment\_type parameter, the payer’s card will be automatically saved for [Subsequent Transactions](#subsequent-payments). Here’s the flow:

1. #### [Call `Payment Methods API`](#call-payment-methods-api)

   Start by fetching the [pg\_codes](https://docs.ottu.com/checkout-api#pg_codes-array-required) (payment gateways) which are enabled for [Tokenization](https://docs.ottu.com/developer/tokenization). This can be done by calling the `Payment Methods API`.
2. #### [Call `Checkout API`](#call-checkout-api)

   After obtaining the `pg_codes`, call the [Checkout API](https://docs.ottu.com/developer/checkout-api) to create a payment transaction.&#x20;

* **For `auto_debit` transactions, it’s essential to:**
  * Include the `payment_type` parameter set to `auto_debit`.
  * Ensure both the [agreement](#what-is-an-agreement) (with its related subfields) and [customer\_id](https://docs.ottu.com/checkout-api#customer_id-string-optional) parameters are supplied, as they are **mandatory**. For more information about agreement, please check [here](#importance-for-merchants).

3. #### [Present Payment Options to Payer](#present-payment-options-to-payer)

   Now, present the payment options to the payer. You can either use the [payment\_methods](https://docs.ottu.com/checkout-api#payment_methods-array-object-mandatory) response from the [Checkout API](https://docs.ottu.com/developer/checkout-api) or use the [Checkout SDK](https://docs.ottu.com/developer/checkout-sdk). The SDK does the heavy lifting by rendering all payment options and capturing the payment.
4. #### [Customer Makes Payment and Saves Card](#customer-makes-payment-and-saves-card)

   The customer then proceeds to pay and save their card.
5. #### [Webhook Payemnt Notification](#webhook-payemnt-notification)

   After the payment is processed, Ottu will notify your [webhook\_url](https://docs.ottu.com/checkout-api#webhook_url-string-optional) (which was provided during the `Checkout API` call).&#x20;

#### [**Here’s what you need to know**](#heres-what-you-need-to-know)

* **Token Retrieval:** The notification to your `webhook_url` will contain the saved card details in the token field. It’s crucial to always save this token, even for [Subsequent Payments](#subsequent-payments). This is because the payer might choose a different card for future `auto-debit` payments. For a detailed schema of the notification, refer to the [Payment Webhook documentation](https://docs.ottu.com/developer/webhooks/payment-notification).
* **Multiple Tokens:** The merchant  should pass the Agreement `ID` as a parameter to distinguish between a customer's tokens, especially when the customer possesses multiple tokens.
* **Handling Lost Tokens:** In case you don’t save the token or lose it, you can retrieve it using the [User Cards API](https://docs.ottu.com/user-cards#fetch-cards). Further details on this process are provided below.
* **Card and Agreement Association:** When a payment is made via `auto-debit`, the `agreement.id` value will be linked with the saved card. Ottu manages this association automatically. This means that if a payer decides to use a different card for subsequent payments, Ottu will handle the transition by disassociating the `agreement.id` from the previous card and linking it to the new one. It’s important to note that an `agreement.id` can only be associated with one card at a time. This automated management ensures that you always have the correct card details associated with the agreement, simplifying the process for subsequent payments.

<figure><img src="https://2847651520-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FiUKrMb9zLt5ZzGPUYDsK%2Fuploads%2FOnFfHcztjn3EmPKSml9T%2FAuto-Debit%20Docs%20-%20First%20Payment%20(1).png?alt=media&#x26;token=6a233273-b8df-41b9-8e3b-7de71175ae4e" alt="" width="264"><figcaption></figcaption></figure>

#### :digit\_two: [**Subsequent Payments**](#subsequent-payments)

After the [initial payment](#first-payment), subsequent payments can be automated using the `Auto Debit API`.

1. #### [Call `Checkout API` with Consistent Parameters](#call-checkout-api-with-consistent-parameters)

   &#x20;When initiating subsequent payments, call the [Checkout API](https://docs.ottu.com/developer/checkout-api) using the [pg\_code](https://docs.ottu.com/checkout-api#pg_codes-array-required) associated with the saved card. It’s crucial to maintain consistency by using the exact same [agreement](#what-is-an-agreement) and [customer\_id](https://docs.ottu.com/checkout-api#customer_id-string-optional) as in the [First Payment](#first-payment). Ottu will handle the task of sending the required parameters to the bank, ensuring a seamless transaction process.\
   \
   **For Parameter Updates:** Avoid sending updated parameters for subsequent payments, as they will have no effect. The method to update the agreement will be discussed in a later section.<br>
2. #### [Call `Auto Debit API`](#call-auto-debit-api)

   Now, call the `Auto Debit API` using the [session\_id](https://docs.ottu.com/checkout-api#session_id-string-mandatory) from the [Checkout API](https://docs.ottu.com/developer/checkout-api) and the card/token you wish to use to charge the customer.

The automated debit process is now initiated, and the payment will be processed automatically without the need for the payer to be online.

<figure><img src="https://2847651520-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FiUKrMb9zLt5ZzGPUYDsK%2Fuploads%2FtmKLrZwQxiNhubxug5aS%2FAuto-Debit%20Docs%20-%20Subsequent%20Payments%20(2).png?alt=media&#x26;token=4ca53aca-7ce4-48dd-958c-402844e310a6" alt="" width="264"><figcaption></figcaption></figure>

This diagram visually represents the steps needed to set up subsequent payments. After calling the [Checkout API](https://docs.ottu.com/developer/checkout-api), you then call the `Auto Debit API` using the [session\_id](https://docs.ottu.com/checkout-api#session_id-string-mandatory) and card/token. The payment is then processed automatically, eliminating the need for the payer to manually authorize each transaction.

For a more detailed technical understanding and the implementation specifics of these operations, please refer to the OpenAPI schema in the API Schema Reference section below.

## Auto debit endpoint for auto debit payment flow

> This endpoint will take a session id and check for it's related payment if it's possible to be auto charged  or not. \<br/> if possible it will charge the payment and return the operation response. \<br/> 📝 \*\*NOTE\*\* Optional fields may not be represented in response body.\
> &#x20;      &#x20;

```json
{"openapi":"3.1.1","info":{"title":"Ottu API","version":"1.0.0"},"servers":[{"url":"https://sandbox.ottu.net"}],"security":[{"SSO_BasicAuth":[]},{"basicAuth":[]},{"SSO_JWT_Auth":[]}],"components":{"securitySchemes":{"SSO_BasicAuth":{"type":"http","scheme":"basic"},"basicAuth":{"type":"http","scheme":"basic"},"SSO_JWT_Auth":{"type":"http","scheme":"bearer","bearerFormat":"JWT"}},"schemas":{"AutoDebit":{"type":"object","description":"Auto debit serializer should take session_id and consumer payment token\nthen validate if session id is valid\nif session id is valid then validate if payment gateway supports auto debit\nif payment gateway supports auto debit then validate if payment gateway has implemented auto debit\nif payment gateway has implemented auto debit then charge the token and return charge response from client\nauto_debit method which should be implemented in client","properties":{"session_id":{"type":"string","description":"A unique identifier for each payment transaction, used to maintain the session state during the payment process.","maxLength":128},"token":{"type":"string","description":"Use this field to provide the unique identifier of a saved customer card for processing a payment in the API request."}},"required":["session_id","token"]},"SchemaWebhook":{"type":"object","properties":{"pg_params":{"allOf":[{"$ref":"#/components/schemas/PGParams"}],"readOnly":true,"description":"The `pg_params` field contains the details received \nfrom the payment gateway callback these details are \nprovided to us by the gateway after a user has completed \na payment transaction additionally, `pg_params` \ncan include information obtained from an inquiry \nrequest made to the payment gateway status check API. \n"},"agreement":{"allOf":[{"$ref":"#/components/schemas/Agreement"}],"readOnly":true,"description":"An established contractual arrangement with the payer, which authorizes you to securely store and subsequently utilize their payment information for specific purposes. This could encompass arrangements like recurring payments for services such as mobile subscriptions, installment-based payments for purchases, arrangements for ad-hoc charges like account top-ups, or for standard industry practices like penalty charges for missed appointments. \n\nNote: If your intention is solely to store payment details for transactions initiated by the payer in the future, then this parameter group should not be used."},"amount":{"type":"string","readOnly":true,"description":"Denotes the total sum of the payment transaction, which encompasses the cost of the procured items or services, excluding any supplementary fees or charges."},"amount_details":{"allOf":[{"$ref":"#/components/schemas/AmountDetails"}],"readOnly":true,"description":"A comprehensive set of amount details includes: Currency Code, Amount, Total, Fee."},"capture_delivery_address":{"type":"boolean","description":"By enabling this, you will ask for user's address. If enabled, capture delivery coordinates should also be active."},"capture_delivery_location":{"type":"boolean","title":"Capture delivery coordinates","description":"By enabling this, you will ask for user's delivery location on a map. "},"card_acceptance_criteria":{"allOf":[{"$ref":"#/components/schemas/CardAcceptanceCriteria"}],"readOnly":true,"description":"This field allows you to define specific rules and conditions that a card must meet to be eligible for payment. These stipulations apply regardless of whether a customer chooses to pay using a saved card or opts to add a new card for the transaction. By leveraging the `card_acceptance_criteria`, you gain the power to fine-tune your payment processing strategy, tailoring acceptance rules to align with your business needs, security standards, and risk management policies.\n\n**Example**: If you run an exclusive service that caters predominantly to premium customers, you might set criteria that only allow transactions from high-tier credit cards like VISA Platinum. This ensures that payments align with the exclusivity and branding of your services. Remember to configure these criteria thoughtfully. Striking the right balance between security, risk mitigation, and user experience is paramount.\n\n**Note**: The `card_acceptance_criteria` field is applicable only for direct payments and not for hosted session payments."},"currency_code":{"type":"string","description":"The specified currency represents the denomination of the transaction.Nevertheless, it doesn't necessarily mandate payment in this exact currency.Due to potential currency conversions or exchanges, the final charge may be in a different currency.","maxLength":3,"minLength":3},"customer_address_city":{"type":"string","description":"The city of the customer's billing address. This field may be used to send the billing address to the payment gateway.","maxLength":40},"customer_address_country":{"type":"string","description":"The country of the customer's billing address, formatted as a two-letter ISO country code (e.g., 'US' for United States, 'CA' for Canada). This field may be used to send the billing address to the payment gateway.","maxLength":2,"minLength":2},"customer_address_line1":{"type":"string","title":"Customer address line 1","description":"The first line of the customer's billing street address. This field may be used to send the billing address to the payment gateway."},"customer_address_line2":{"type":"string","title":"Customer address line 2","description":"The second line of the customer's billing street address, if available. This field may be used to provide additional address information, such as an apartment or suite number."},"customer_birthdate":{"type":["string","null"],"format":"date","description":"The customer's date of birth in ISO format (YYYY-MM-DD)."},"customer_address_postal_code":{"type":"string","description":"The postal code of the customer's billing address. This field may be used to send the billing address to the payment gateway.","maxLength":12},"customer_address_state":{"type":"string","description":"The state or region of the customer's billing address. This field may be used to send the billing address to the payment gateway.","maxLength":40},"customer_email":{"type":"string","description":"The email address of the customer that is used to send payment notifications and receipts, and can be used for fraud prevention. This field is mandatory and is always sent to the payment gateway. It may also be included in the invoice, receipt, email, and displayed on the payment page.","maxLength":128},"customer_first_name":{"type":"string","description":"The first name of the recipient of the payment. This field is used for various communications such as the invoice, receipt, email, SMS, or displayed on the payment page. It may also be sent to the payment gateway if necessary.","maxLength":64},"customer_id":{"type":"string","description":"The customer ID is a unique identifier for the customer within the merchant's system. It is also used as a merchant identifier for the customer and plays a critical role in tokenization. All the customer's cards will be associated with this ID.","maxLength":64},"customer_last_name":{"type":"string","description":"The last name of the recipient of the payment. This field is used for various communications such as the invoice, receipt, email, SMS, or displayed on the payment page. It may also be sent to the payment gateway if necessary.","maxLength":64},"customer_phone":{"type":"string","description":"Customer phone number associated with the payment. This might be sent to the payment gateway and depending on the gateway, it may trigger a click to pay process on the payment page. The phone number will also be included in the invoice, receipt, email, and displayed on the payment page.","maxLength":32},"extra":{"description":"The extra information for the payment details, which the merchant has sent it in key value form."},"fee":{"type":"string","description":"The fee denotes the sum the customer pays in their chosen payment currency. This may vary from the transaction's designated currency. The fee is computed once to maintain precision and uniformity throughout the payment procedure.","readOnly":true},"gateway_account":{"type":"string","readOnly":true,"description":"This code corresponds to the payment gateway and plays an essential role in facilitating payment transactions."},"gateway_name":{"type":"string","readOnly":true,"description":"The name of the payment gateway service being utilized."},"gateway_response":{"type":"object","additionalProperties":{},"description":"This field stores the processed response received from the payment gateway and forwarded to Ottu.","readOnly":true},"initiator":{"allOf":[{"$ref":"#/components/schemas/InitiatorUser"}],"description":"The user who initiated the creation of this payment transaction, if available. This field is optional and may be used to track who created the payment transaction. Note that if the payment transaction was using API Key auth initiator_id can be set to any value that corresponds to an existing ACTIVE user in the system"},"is_sandbox":{"type":"boolean","title":"Is Sandbox?","description":"Indicates whether the operation was performed in a test environment or not."},"message":{"type":"string","readOnly":true,"description":"This represents the message, either transmitted by the Payment Gateway (PG) or established by Ottu, that provides a detailed illustration of the payment's current status."},"order_no":{"type":["string","null"],"description":"The unique identifier assigned to this payment transaction. It is used for tracking purposes and is set by the merchant or the system.","maxLength":128},"paid_amount":{"oneOf":[{"type":"number","format":"double"},{"type":"string"}],"description":"The paid amount encompasses fees or captured amounts from authorized transactions. This total is derived from the specified 'amount' field, converting foreign currencies to the default as necessary. This might result in minor variations due to fluctuations in exchange rates.","readOnly":true},"payment_type":{"enum":["one_off","auto_debit","save_card"],"type":"string","description":"Type of payment. Choose `one_off` for payments that occur only once without future commitments. Choose `auto_debit` for payments that are automatically deducted, such as recurring subscriptions, installments, or unscheduled auto-debits. \n\nChoose `save_card` if you want to perform a card tokenization operation.\n\nNOTE: If `auto_debit` is selected: \n1. `agreement` and `customer_id` parameters will also be mandatory. \n2. Only PG codes supporting tokenization can be selected. \nAs a side effect, the card used for the payment will be associated with the supplied `agreement.id`. This card will be locked, preventing the customer from deleting it from the system until an alternate card is chosen for auto-debit payments.\n\nNOTE: If `save_card` is selected: \n1. The amount must be zero for the save card operation. \n2. The selected MID(pg_code) must support tokenization to enable the save card operation. \n3. Please note that the save card operation is considered successful without any funds being charged.\n4. Once a card is created, Ottu will send a webhook containing the card details to the merchant's webhook URL.\n5. When the transaction type is `save_card`, all previously saved cards returned in the sdk_preload_payload should be hidden since the user is saving a new card and does not need to select from existing ones.\n\n* `one_off` - One Off\n* `auto_debit` - Auto Debit\n* `save_card` - Save Card"},"reference_number":{"type":"string","readOnly":true},"refunded_amount":{"type":"number","format":"double","description":"The total refunded amount for the payment transaction."},"remaining_amount":{"type":"number","format":"double","description":"The residual amount due. Together with the editable amount, it indicates the outstanding balance of a transaction awaiting settlement.","readOnly":true},"result":{"enum":["pending","success","failed","canceled","error","cod"],"type":"string","description":"Indicates the outcome of the operation. `success` denotes a successful operation.","readOnly":true},"session_id":{"type":"string","description":"A unique identifier for each payment transaction, used to maintain the session state during the payment process.","maxLength":128},"settled_amount":{"type":"number","format":"double","description":"The amount that has been paid or authorized in its original currency, excluding any fees.","readOnly":true},"signature":{"type":"string","readOnly":true,"description":"Signature Field: A cryptographic hash used to guarantee data integrity and authenticity during client-server exchanges. This hash ensures that the API payload has not been tampered with, and can only be verified by authorized parties."},"state":{"type":"string","readOnly":true},"token":{"allOf":[{"$ref":"#/components/schemas/Card"}],"description":"Please note that if card is created via checkout save_card payment type\n\nIt means card is created via successful operation without any funds charged.\n\nFor more details check Checkout API `payment_type` field documentation details"},"transaction_log_id":{"type":["integer","null"],"maximum":2147483647,"minimum":0,"description":"Identifies the transaction log associated with the payment transaction. A transaction log is created for each record that is dispatched during a bulk dispatch process."},"timestamp_utc":{"type":"string","format":"date-time","readOnly":true,"description":"This field represents the timestamp at which ottu processed the transaction.While this often corresponds to the payment time,it's important to note that it might not always be the case.Payments can be acknowledged at a later time,so this timestamp might not align precisely with the actual payment time."},"transactions":{"type":"array","items":{"$ref":"#/components/schemas/ChildPayment"},"description":"A list of dictionaries is generated, each containing a concise summary of each child payment transaction that has been created."},"voided_amount":{"type":"number","format":"double","description":"The total voided amount for the payment transaction."}},"required":["agreement","amount","amount_details","card_acceptance_criteria","currency_code","customer_address_country","fee","gateway_account","gateway_name","gateway_response","message","paid_amount","pg_params","reference_number","remaining_amount","result","settled_amount","signature","state","timestamp_utc"]},"PGParams":{"type":"object","description":"Serializer for PaymentTransaction with dynamically generated fields.","properties":{"auth_code":{},"card_type":{},"card_holder":{},"cardholder_email":{},"card_expiry_month":{},"card_expiry_year":{},"full_card_expiry":{},"card_number":{},"card_issuer":{},"ref":{},"result":{},"track_id":{},"post_date":{},"transaction_id":{},"payment_id":{},"pg_message":{},"receipt_no":{},"transaction_no":{},"decision":{},"card_expiry":{},"card_details":{},"dcc_payer_amount":{},"dcc_payer_currency":{},"dcc_payer_exchange_rate":{},"rrn":{}}},"Agreement":{"type":"object","description":"Serializer to hold the recurring data information.\nThis is required for being able to create recurring payments and the PGs\nrequire this information.","properties":{"id":{"type":"string","description":"A unique identifier for the agreement established with the payer. This ID links to the specific terms and conditions the payer has authorized for processing their stored card details. Use cases include: \n1. Recurring Payments: Periodic debits, e.g., gym memberships. \n2. Installment Payments: Multiple charges for a single purchase over time. \n3. Unscheduled: Future payments as required, e.g., account top-ups. \n4. Industry Practice: Standard business practices related to an original payment, e.g., hotel charges after checkout.","maxLength":128},"amount_variability":{"enum":["fixed","variable"],"type":"string","description":"Indicates if all payments within the agreement use the same amount or if the amount differs between the payments.\n\n* `fixed` - Fixed\n* `variable` - Variable"},"start_date":{"type":"string","format":"date","description":"Date on which the agreement with the payer to process payments starts."},"expiry_date":{"type":"string","format":"date","description":"Date on which your agreement with the payer to process payments expires."},"max_amount_per_cycle":{"type":"string","format":"decimal","description":"The maximum amount for a single payment in the series as agreed with the payer."},"cycle_interval_days":{"type":"integer","maximum":366,"minimum":1,"description":"The minimum number of days between payments agreed with the payer."},"total_cycles":{"type":"integer","maximum":999,"minimum":1,"description":"The number of merchant-initiated payments within the recurring payment agreement."},"frequency":{"enum":["irregular","daily","weekly","semi_monthly","monthly","quarterly","semi_annually","yearly","other"],"type":"string","description":"The frequency of the payments within the series as agreed with the payer.\n\n* `irregular` - Irregular\n* `daily` - Daily\n* `weekly` - Weekly\n* `semi_monthly` - Semi Monthly\n* `monthly` - Monthly\n* `quarterly` - Quarterly\n* `semi_annually` - Semi Annually\n* `yearly` - Yearly\n* `other` - Other"},"type":{"enum":["event_based","installment","recurring","unscheduled","other"],"type":"string","default":"recurring","description":"The type of commercial agreement that the payer has with the merchant.\n\n *Note*: For `unscheduled` agreements, the allowed values should be configured as follows: \n\n `id` - Accepts any value. \n\n `frequency`. \n\n `type`.\n\n This configuration ensures that only specific values are permitted for each field when the `type` is `Unscheduled`.\n\n *Note*: For `recurring` agreements, the following fields are mandatory as follows: \n\n `amount_variability` \n\n `cycle_interval_days` \n\n `expiry_date` \n\n ` `requency` \n\n `id` \n\n  `total_cycles` \n\n This configuration ensures that the required values are mandatory for each field when the `type` is `Recurring`.\n\n* `event_based` - Event Based\n* `installment` - Installment\n* `recurring` - Recurring\n* `unscheduled` - Unscheduled\n* `other` - Other"},"seller":{"allOf":[{"$ref":"#/components/schemas/AgreementSeller"}],"description":"Details about the retailer, if the agreement is for installment payments."},"extra_params":{"allOf":[{"$ref":"#/components/schemas/AgreementExtraParams"}],"description":"Additional parameters related to the agreement."}}},"AgreementSeller":{"type":"object","properties":{"name":{"type":"string","description":"The retailer's trading name.","maxLength":128},"short_name":{"type":"string","description":"Abbreviation of the retailer's trading name, suitable for payer's statement display.","maxLength":64},"category_code":{"type":"string","description":"A 4-digit code classifying the retailer's business by the type of goods or services it offers.","maxLength":64}}},"AgreementExtraParams":{"type":"object","properties":{"payment_processing_day":{"type":"integer","maximum":31,"minimum":1,"description":"Day of the month on which the payment must be processed. Not required for unscheduled payment agreements."}}},"AmountDetails":{"type":"object","properties":{"currency_code":{"type":"string","readOnly":true},"amount":{"type":"string","description":"Represents the total amount of the payment transaction, which includes the cost of the purchased items or services but excludes any additional fees or charges","maxLength":120},"total":{"type":"string","readOnly":true,"description":"Denotes the comprehensive total of the payment transaction, incorporating both the principal amount and any associated fees."},"fee":{"type":"string","readOnly":true,"description":"The `Fee` indicates the sum disbursed by the customer in their chosen currency for the payment. Note, this currency could vary from the currency used for the transaction."},"exchange_rate":{"type":"string","description":"The conversion rate used for currency conversion during payment. This value reflects the rate locally calculated."}},"required":["currency_code","fee","total"]},"CardAcceptanceCriteria":{"type":"object","properties":{"min_expiry_time":{"type":"integer","maximum":365,"minimum":1,"description":"Specifies the minimum required validity period, in days, for a card to be eligible for payment. If set to 30 days, for example, cards set to expire within the next month would be declined. This ensures short-lived cards nearing their expiration date are filtered out, reducing chances of payment failures. When implementing, balance your operational needs with customer convenience. Setting it too stringent might increase payment declines, while a lenient approach could risk future payment failures.\n\nAdditionally, it defaults to 30 days when the `payment_type` is `auto_debit`. If any other payment type is selected, no default value is set."}}},"InitiatorUser":{"type":"object","properties":{"id":{"type":"integer","readOnly":true},"first_name":{"type":"string","maxLength":32},"last_name":{"type":"string","maxLength":32},"username":{"type":"string","description":"Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.","pattern":"^[\\w.@+-]+$","maxLength":150},"email":{"type":"string","format":"email","title":"Email address","maxLength":254},"phone":{"type":"string","title":"Phone number","maxLength":128}},"required":["email","id","username"]},"Card":{"type":"object","description":"Represents token details, only if the user pays with a tokenized card, Ottu will include the token details in the response.","properties":{"brand":{"type":["string","null"],"description":"The card brand (e.g., Visa, Mastercard) associated with the card. Display this information for customer reference.","maxLength":32},"customer_id":{"type":"string","description":"The unique identifier for the customer who owns the card","maxLength":36},"cvv_required":{"type":"boolean","description":"Specifies if the card requires the submission of a CVV for transactions. A card without CVV requirement can be used for auto-debit or recurring payments."},"expiry_month":{"type":"string","description":"The card's expiration month. Provide this information for transaction processing and validation.","maxLength":2},"expiry_year":{"type":"string","description":"The card's expiration year. Provide this information for transaction processing and validation.","maxLength":2},"is_expired":{"type":"boolean","description":"A boolean field indicating whether the card has expired. Use this information to determine if the card is valid for transactions and to notify the customer if necessary."},"is_preferred":{"type":"boolean","readOnly":true,"description":" Indicates if the card is the customer's preferred payment option. Order cards with this attribute set to true at the top of the list for easy access."},"name_on_card":{"type":["string","null"],"description":"The cardholder's name as it appears on the card. Display this information for customer verification.","maxLength":64},"number":{"type":["string","null"],"description":"The masked card number to be displayed, ensuring customer privacy and security while providing essential information.","maxLength":19},"pg_code":{"type":"string","description":"The `pg_code` associated with the card's creation."},"pg_name":{"enum":["knet","cybersource","csuc","checkoutcom","migs","dapi","deema","burgan","paypal","mpgs","kpay","enet","omannet","benefit","benefit_pay","blank","cbk","fss","myfatoorah","ngenius","ifg","ccavenues","payu_india","cod","amazon_pay","ottu_pg","bookeey","upg","bambora","hyperpay","qpay","smart_pay","sohar","nbo","tabby","tamara","hesabe","rajhi","stc_pay","stcbahrain","urpay","beyon_money","upayments","tap","fawry","fiserv","payon","paymob","moyasar"],"type":"string","description":"The payment `gateway` associated with the user's card.\n\n* `knet` - Knet\n* `cybersource` - CyberSource\n* `csuc` - Cybersource Unified Checkout\n* `checkoutcom` - checkout.com\n* `migs` - MiGS\n* `dapi` - Dapi\n* `deema` - Deema\n* `burgan` - Burgan\n* `paypal` - PayPal\n* `mpgs` - MPGS\n* `kpay` - KPay\n* `enet` - Enet\n* `omannet` - OmanNet\n* `benefit` - Benefit\n* `benefit_pay` - BenefitPay\n* `blank` - Blank\n* `cbk` - CBK\n* `fss` - FSS\n* `myfatoorah` - MyFatoorah\n* `ngenius` - N-Genius\n* `ifg` - IATA Financial Gateway\n* `ccavenues` - Ccavenues\n* `payu_india` - PayU India\n* `cod` - Cash\n* `amazon_pay` - Amazon Pay\n* `ottu_pg` - Ottu PG\n* `bookeey` - Bookeey\n* `upg` - UPG\n* `bambora` - Bambora\n* `hyperpay` - HyperPay\n* `qpay` - Qpay\n* `smart_pay` - SmartPay\n* `sohar` - SoharInternational\n* `nbo` - NBO\n* `tabby` - Tabby\n* `tamara` - Tamara\n* `hesabe` - Hesabe\n* `rajhi` - Alrajhi Bank\n* `stc_pay` - STC Pay\n* `stcbahrain` - STC Bahrain\n* `urpay` - URPay\n* `beyon_money` - BeyonMoney\n* `upayments` - UPayments\n* `tap` - Tap Payments\n* `fawry` - Fawry\n* `fiserv` - Fiserv\n* `payon` - PayOn\n* `paymob` - PayMob\n* `moyasar` - Moyasar"},"token":{"type":"string","description":"The unique token associated with the card, required for tokenized card payments. Use this value to securely process transactions.","maxLength":50},"agreements":{"description":"List of agreements associated with this card."}},"required":["agreements","brand","customer_id","cvv_required","expiry_month","expiry_year","is_expired","is_preferred","name_on_card","number","pg_code","pg_name","token"]},"ChildPayment":{"type":"object","properties":{"amount":{"type":"string","readOnly":true},"currency_code":{"type":"string","description":"The specified currency represents the denomination of the transaction.Nevertheless, it doesn't necessarily mandate payment in this exact currency.Due to potential currency conversions or exchanges, the final charge may be in a different currency.","maxLength":3,"minLength":3},"order_no":{"type":["string","null"],"description":"The unique identifier assigned to this payment transaction. It is used for tracking purposes and is set by the merchant or the system.","maxLength":128},"session_id":{"type":"string","description":"A unique identifier for each payment transaction, used to maintain the session state during the payment process.","maxLength":128},"state":{"enum":["paid","refunded","refund_queued","refund_rejected","voided"],"type":"string","description":"The current state of the payment transaction, it helps to understand the progress of the payment.\n\n* `paid` - paid\n* `refunded` - refunded\n* `refund_queued` - refund_queued\n* `refund_rejected` - refund_rejected\n* `voided` - voided"}},"required":["amount","currency_code"]},"AutoDebitErrors":{"oneOf":[{"$ref":"#/components/schemas/FieldErrors"},{"$ref":"#/components/schemas/AutoDebitFailure"}]},"FieldErrors":{"type":"object","properties":{"field_name":{"type":"array","items":{"type":"string","default":"This field is required."}}}},"AutoDebitFailure":{"type":"object","properties":{"detail":{"type":"string","description":"Provides a message associated with the operation, suitable for displaying to the end user."},"result":{"enum":["failed"],"type":"string","description":"* `failed` - Failed"}},"required":["detail","result"]},"GenericErrorMessage":{"type":"object","properties":{"detail":{"type":"string"}},"required":["detail"]}}},"paths":{"/b/pbl/v2/auto-debit/":{"post":{"operationId":"auto_debit","description":"This endpoint will take a session id and check for it's related payment if it's possible to be auto charged  or not. <br/> if possible it will charge the payment and return the operation response. <br/> 📝 **NOTE** Optional fields may not be represented in response body.\n        ","summary":"Auto debit endpoint for auto debit payment flow","parameters":[{"in":"header","name":"Authorization","schema":{"type":"string","default":"Api-Key vSUmxsXx.V81oYvOWFMcIywaOu57Utx6VSCmG11lo"},"description":"Private API key to be provided in the format `Api-Key <key>`.","required":true}],"tags":["Auto Debit"],"requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AutoDebit"}},"application/x-www-form-urlencoded":{"schema":{"$ref":"#/components/schemas/AutoDebit"}},"multipart/form-data":{"schema":{"$ref":"#/components/schemas/AutoDebit"}}},"required":true},"responses":{"200":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SchemaWebhook"}}},"description":""},"400":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AutoDebitErrors"}}},"description":""},"401":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/GenericErrorMessage"}}},"description":""}}}}}}
```

## [Guide: Step By Step](#guide-step-by-step)

Navigating the world of digital payments can be intricate. Whether you’re processing an initial payment or managing subsequent transactions, each step is crucial to ensure a seamless experience for both merchants and payers. This guide provides a detailed walkthrough, from the moment a customer decides to save their card details to the intricacies of handling recurring charges.

### [First Payment Process](#first-payment-process)

#### 1. [Retrieving `pg_codes` (Option](#id-1.-retrieving-pg_codes-optional)

Before initiating the first payment, you have the option to call the [Payment Methods API](https://docs.ottu.com/developer/payment-methods) to retrieve the necessary [pg\_codes](https://docs.ottu.com/checkout-api#pg_codes-array-required). This can be done using the following payload:<br>

```json
{
    "plugin": "e_commerce",
    "currencies": ["KWD", "SAR"],
    "operation": "purchase",
    "customer_id": "test",
    "tokenizable": true
}
```

**Why Consider This Step?**\
While this step is optional, it offers several advantages:

* **Flexibility:** If you’re uncertain about the `pg_code` or anticipate it might change in the future, this step ensures you always have the most up-to-date code.
* **End-to-End Integration:** By retrieving the `pg_codes`dynamically, you ensure a seamless integration with Ottu. This means that any changes in the configuration, such as a code alteration or the addition of a new payment gateway, will be automatically reflected in your system.
* **Hardcoding Alternative:** If you’re confident that the `pg_code` will remain consistent and won’t change, you can opt to hardcode it directly into your system. This approach might simplify the process but could require updates if there are changes on Ottu end.

#### 2. [Initiating the Payment via `Checkout API`](#id-2.-initiating-the-payment-via-checkout-api)

To proceed with the payment, you’ll need to call the [Checkout API](https://docs.ottu.com/developer/checkout-api). Here’s an example of the payload you might use:

```json
{
   "type":"e_commerce",
   "amount":"200.00",
   "payment_type":"auto_debit",
   "currency_code":"KWD",
   "pg_codes":["credit-card"],
   "customer_id":"cust_123",
   "return_url":"https://yourwebsite.com/return",
   "webhook_url":"https://yourwebsite.com/webhook",
   "card_acceptance_criteria":{
      "min_expiry_time":30
   },
   "agreement":{
      "id":"A123456789",
      "amount_variability":"fixed",
      "start_date":"13/12/2023",
      "expiry_date":"01/10/2024",
      "cycle_interval_days":1,
      "total_cycles":1,
      "frequency":"daily",
      "type":"recurring",
      "seller":{
         "name":"Test-auto-debit",
         "short_name":"Test",
         "category_code":"1234"
      }
   }
}
```

#### Response:

```json
{
   "agreement":{
      "id":"A123456789",
      "amount_variability":"fixed",
      "start_date":"13/12/2023",
      "expiry_date":"01/10/2024",
      "cycle_interval_days":1,
      "total_cycles":1,
      "frequency":"daily",
      "type":"recurring",
      "seller":{
         "name":"Test-auto-debit",
         "short_name":"Test",
         "category_code":"1234"
      }
   },
   "amount":"200.000",
   "card_acceptance_criteria":{
      "min_expiry_time":30
   },
   "checkout_url":"https://sandbox.ottu.net/b/checkout/redirect/start/?session_id=4a462681df6aab64e27cedc9bbf733cd6442578b",
   "currency_code":"KWD",
   "customer_id":"cust_123",
   "due_datetime":"13/12/2023 12:55:36",
   "expiration_time":"1 00:00:00",
   "language":"en",
   "operation":"purchase",
   "payment_methods":[
      {
         "code":"credit-card",
         "name":"Credit Card",
         "pg":"Ottu PG",
         "type":"sandbox",
         "amount":"200.000",
         "currency_code":"KWD",
         "fee":"0.000",
         "fee_description":"",
         "icon":"https://sandbox.ottu.net/media/gateway/settings/logos/MASTER-.jpeg",
         "flow":"redirect",
         "redirect_url":"https://pg.ottu.dev/checkout/c2FuZGJveC5vdHR1Lm5ldA==/Z0FBQUFBQ"
      }
   ],
   "payment_type":"auto_debit",
   "pg_codes":[
      "credit-card"
   ],
   "session_id":"4a462681df6aab64e27cedc9bbf733cd6442578b",
   "state":"created",
   "type":"e_commerce",
   "webhook_url":"https://yourwebsite.com/webhook"
}
```

After sending this request, you’ll be provided with a [session\_id](https://docs.ottu.com/checkout-api#session_id-string-mandatory). Additionally, you’ll receive at least two ([redirect\_url](https://docs.ottu.com/checkout-api#redirect_url-string-optional))s. These URLs are essential as they guide the customer through the subsequent stages of the payment process.

* **Using the Checkout SDK:** If you’ve integrated the [Checkout SDK](https://docs.ottu.com/developer/checkout-sdk), utilize the received [session\_id](https://docs.ottu.com/checkout-api#session_id-string-mandatory) to initiate the SDK on your page. This will automate the process, presenting any saved cards to the payer, if available.
* **Without the Checkout SDK:** If you haven’t integrated the SDK, you have the option to redirect the customer to either:
  * #### checkout\_url:

    This URL leads the payer to an Ottu page where any saved cards are displayed, and they also have the option to save a new card. for more information about `redirect_url`, check [here](https://docs.ottu.com/checkout-api#checkout_url-string-mandatory).
  * #### payment\_methods.redirect\_url:

    This URL takes the payer directly to the payment page where they can input their card details. More information about `payment_methods` objects could be found [here](https://docs.ottu.com/checkout-api#payment_methods-object-details).

If the payer has previously saved cards associated with the `pg_code` used to create the payment, it’s advisable to redirect them to the `checkout_url`. Otherwise, use the `payment_methods.redirect_url`.&#x20;

For a seamless experience, we highly recommend using the [Checkout SDK](https://docs.ottu.com/developer/checkout-sdk), which handles these decisions and processes automatically.

Once the customer completes the payment, the card will be saved and associated with the `agreement.id` that was provided earlier. A notification will then be sent to your [webhook\_url](https://docs.ottu.com/checkout-api#webhook_url-string-optional). Within this notification, the saved card will be represented by a parameter named token. It’s crucial to securely save both the token and the `pg_code` used for this payment. The `pg_code` is especially important for [subsequent payments](#subsequent-payments). Since the recurring payment setup is already established with the bank, there’s no need to call the [Payment Methods API](https://docs.ottu.com/developer/payment-methods) again in the future. Storing the `pg_code` ensures you can seamlessly continue with the established payment process.

#### [Card Acceptance Criteria](#card-acceptance-criteria)

It’s noteworthy that the payload includes `card_acceptance_criteria.min_expiry_time` = `30`. This parameter ensures that for this specific payment, any attempt by the customer to add a new card or select a card via the [Checkout SDK](https://docs.ottu.com/developer/checkout-sdk), which has an expiration time not exceeding the current date plus 30 days, will be declined. Tailoring this field according to your operational requirements is crucial to prevent the acceptance of cards nearing their expiration. Ideally, a validity buffer of at least one month should be considered.

Furthermore, parameters under `card_acceptance_criteria,` like `exclude_bins` (allowing only specific BINs to pay), are applicable only for `pg_codes` that are on direct payment integration and not for hosted sessions. For a comprehensive list of `card_acceptance_criteria`, refer to the [Checkout API](https://docs.ottu.com/developer/checkout-api).

#### [Step Summary](#step-summary)

In this pivotal step, several key actions took place:

1. **Bank Settlement:** An agreement or “settlement” was established with the bank, setting the stage for future transactions.
2. **Customer Consent:** The customer gave their consent to save their card details, facilitating smoother future payments.
3. **Card Tokenization:** The customer’s card was tokenized, converting sensitive card details into a secure token. If the customer already had a tokenized card, they could use it to authorize the payments.
4. **Ready for Future Charges:** With these foundational steps completed, everything is now in place! All that remains is to initiate charges as and when they’re due.

Wohoo! The groundwork is laid, and you’re all set to process subsequent payments effortlessly.

### [Subsequent Payments](#subsequent-payments-1)

To ensure a smooth subsequent payment process, follow these steps:

#### 1. [Pre-Charging Notifications](#id-1.-pre-charging-notifications)

Before the charging day, it’s recommended to send the payer 1-2 email notifications, ideally one week before and then one day before the scheduled charge. This serves as a reminder to ensure they have the necessary funds available or to go online and modify the card they wish to use for the payment.

#### 2. [Initiating the `Checkout API` Using the Prior `pg_code`](#id-2.-initiating-the-checkout-api-using-the-prior-pg_codes)

For subsequent payments, generate a new [session\_id](https://docs.ottu.com/checkout-api#session_id-string-mandatory) by initiating a new payment transaction using the `Checkout API`, and this transaction should incorporate the `pg_code` from the previous successful transaction. This is either associated with the current [agreement](#what-is-an-agreement) or derived from the initial payment. While supplying other parameters, ensure consistency with the initial payment setup. Remember, the amount might differ if your agreement allows for variable amounts.

#### Request:&#x20;

```json
{
   "type":"e_commerce",
   "pg_codes":[
      "credit-card"
   ],
   "customer_id":"cust_123",
   "amount":"19",
   "agreement":{
      "id":"A123456789",
      "amount_variability":"fixed",
      "start_date":"13/12/2023",
      "expiry_date":"01/10/2024",
      "cycle_interval_days":1,
      "total_cycles":1,
      "frequency":"daily",
      "type":"recurring",
      "seller":{
         "name":"Test-auto-debit",
         "short_name":"Test",
         "category_code":"1234"
      }
   },
   "payment_type":"auto_debit",
   "currency_code":"KWD"
}
```

#### Response:

```json
{
   "agreement":{
      "id":"A123456789",
      "amount_variability":"fixed",
      "start_date":"13/12/2023",
      "expiry_date":"01/10/2024",
      "cycle_interval_days":1,
      "total_cycles":1,
      "frequency":"daily",
      "type":"recurring",
      "seller":{
         "name":"Test-auto-debit",
         "short_name":"Test",
         "category_code":"1234"
      }
   },
   "amount":"19.000",
   "card_acceptance_criteria":{
      "min_expiry_time":30
   },
   "checkout_url":"https://sandbox.ottu.net/b/checkout/redirect/start/?session_id=19aa7cd3cfc43d9d7641f6c433767b25cbcd6c18",
   "currency_code":"KWD",
   "customer_id":"cust_123",
   "due_datetime":"13/12/2023 13:41:29",
   "expiration_time":"1 00:00:00",
   "language":"en",
   "operation":"purchase",
   "payment_methods":[
      {
         "code":"credit-card",
         "name":"Credit Card",
         "pg":"Ottu PG",
         "type":"sandbox",
         "amount":"19.000",
         "currency_code":"KWD",
         "fee":"0.000",
         "fee_description":"",
         "icon":"https://sandbox.ottu.net/media/gateway/settings/logos/MASTER_q6sxwtA_md4lBKv.jpeg",
         "flow":"redirect",
         "redirect_url":"https://pg.ottu.dev/checkout/c2FuZGJveC5vdHR1Lm5ldA==/Z0FBQUFBQmxlYlNLWDB"
      }
   ],
   "payment_type":"auto_debit",
   "pg_codes":["credit-card"],
   "session_id":"19aa7cd3cfc43d9d7641f6c433767b25cbcd6c18",
   "state":"created",
   "type":"e_commerce"
}
```

#### 3. [Retrieve the `session_id`](#id-3.-retrieve-the-session_id)

The [Checkout API](https://docs.ottu.com/developer/checkout-api) call will return a [session\_id](https://docs.ottu.com/checkout-api#session_id-string-mandatory). This ID is crucial for the next step in the process.\
`session_id`: `19aa7cd3cfc43d9d7641f6c433767b25cbcd6c18`.

`token`: `9923965822244314`.

#### 4. [Initiate the `AutoDebit API` Call](#id-4.-initiate-the-autodebit-api-call)

Use the received `session_id` and the token from the last payment to charge the payer by calling the [AutoDebit API](#api-schema-reference). This call will yield one of two responses: `success` or `failure`.

* **Success:** If you receive a success response, it indicates that the payment was processed successfully. You can then notify the payer about the successful payment.
* **Failure:** In the event of a failed payment, notify the payer about the payment failure and provide the reason, which will be sent to you by Ottu. At this stage, update the payment `session_id` by calling the [Checkout API](https://docs.ottu.com/developer/checkout-api) again and provide both the [expiration\_time](https://docs.ottu.com/checkout-api#expiration_time-string-optional) and [due\_datetime](https://docs.ottu.com/checkout-api#due_datetime-string-date-time-optional) parameters to set a grace period for the customer, for example, 3 days. While waiting for the customer to attempt a manual payment, it’s recommended to try charging again after 24 hours, in case the customer has added funds or resolved the issue with their card.

#### Request:

```json
POST: https://<ottu-url>/b/pbl/v2/auto-debit/
{
    "session_id":"19aa7cd3cfc43d9d7641f6c433767b25cbcd6c18",
    "token":"9923965822244314"
}
```

#### Response:

```json
{
   "agreement":{
      "id":"A123456789",
      "amount_variability":"fixed",
      "start_date":"2023-12-13",
      "expiry_date":"2024-10-01",
      "cycle_interval_days":1,
      "total_cycles":1,
      "frequency":"daily",
      "type":"recurring",
      "seller":{
         "name":"Test-auto-debit",
         "short_name":"Test",
         "category_code":"1234"
      }
   },
   "amount":"19.000",
   "amount_details":{
      "currency_code":"KWD",
      "amount":"19.000",
      "total":"19.000",
      "fee":"0.000"
   },
   "card_acceptance_criteria":{
      "min_expiry_time":30
   },
   "currency_code":"KWD",
   "customer_id":"cust_123",
   "fee":"0.000 KWD",
   "gateway_account":"credit-card",
   "gateway_name":"mpgs",
   "gateway_response":{
      "It will contain the raw pg response sent by the pg to Ottu"
   },
   "initiator":{},
   "is_sandbox":true,
   "paid_amount":"19.000",
   "payment_type":"auto_debit",
   "reference_number":"sandboxAQ5UT",
   "result":"success",
   "session_id":"19aa7cd3cfc43d9d7641f6c433767b25cbcd6c18",
   "settled_amount":"19.000",
   "signature":"9a2043*****************",
   "state":"paid",
   "timestamp_utc":"2023-12-13 13:42:35",
   "token":{
      "customer_id":"cust_123",
      "brand":"VISA",
      "name_on_card":"test-card",
      "number":"**** 1019",
      "expiry_month":"01",
      "expiry_year":"39",
      "token":"992*********",
      "pg_code":"credit-card",
      "is_preferred":true,
      "is_expired":false,
      "will_expire_soon":false,
      "cvv_required":true,
      "agreements":[
         "k3",
         "A123456789"
      ]
   }
}
```

#### 5. [Payer's Manual Action](#id-5.-payers-manual-action)

If the `auto-debit` fails, the payer must be notified that they need to action the payment manually using the provided [checkout\_url](https://docs.ottu.com/checkout-api#checkout_url-string-mandatory). When they access the link, they will be directed to make the payment, which can be done using an existing card or by entering a new card’s details.

### [Updating Card Information for Auto-Debit Payments](#updating-card-information-for-auto-debit-payments)

It's essential to remember that any change to the card associated with an auto-debit payment must be [Cardholder Initiated Transactions](#cardholder-initiated-transactions-cit) (CIT). The customer must be actively involved and give consent when updating or selecting a different card for existing auto-debit payments. Here’s how this process can be facilitated:

#### 1. Customer-Initiated Card Change:

* **Navigation:** The customer visits your website and heads to the auto-debit payment management section with the intent to modify the card linked to their ongoing auto-debit payment.
* **Initiating a New Payment Session:** Once the customer signals their intent, call the [Checkout API](https://docs.ottu.com/developer/checkout-api) to create a new [session\_id](https://docs.ottu.com/checkout-api#session_id-string-mandatory) for the specified auto-debit or agreement payment.
* **Payment Options:** Offer the customer two pathways:
  * Utilize the Checkout SDK to showcase payment choices within your platform.
  * Redirect them to[ Ottu’s checkout\_url](https://docs.ottu.com/checkout-api#checkout_url-string-mandatory), where they can pick an existing card or input new card details.

#### **2. Merchant-Requested Card Change:**

* **Reason for Change:** There may be scenarios where you, as a merchant, need the customer to switch their card. Common reasons include impending card expiration or failed payment attempts.
* **Communication:** When such a situation arises, notify the customer via email or SMS. The communication should include a link to either your platform’s auto-debit payment management or [Ottu’s checkout\_url](https://docs.ottu.com/checkout-api#checkout_url-string-mandatory).
* **Customer Action:** The email/SMS serves as an invitation for the customer to make necessary card changes. They’ll need to follow the same steps as in the [customer-initiated process—navigating](#1.-customer-initiated-card-change) to the designated link, initiating a new session, and completing a payment.
* **Completion:** Like in the previous scenario, any new card details are shared with your system through a [webhook](https://docs.ottu.com/developer/webhooks). Make sure your system is primed to record this update.

{% hint style="info" %}
The above examples are illustrative and the actual API calls would depend on the specific configuration of your Ottu setup.
{% endhint %}

## [Best Practices](#best-practices)

* **Recurring Payment Schedule:** It’s essential to be aware of the frequency of these subsequent payments, whether they’re set to be weekly, monthly, or based on another schedule. This helps in anticipating the transaction and ensuring everything runs smoothly.
* **Record Keeping:** For every transaction made, maintain a detailed record. This aids in account reconciliation, handling customer queries, and staying compliant with any financial regulations.
* **Regular Customer Communication:** Apart from the essential notifications, keep your customers in the loop with regular updates about their subscription or payment plan. This can foster trust and ensure they see the value in the service they’re paying for.
* **Instant Payment Access:** In all your notifications, include a direct link—either to the `Ottu checkout_url` or to the auto-debit payment management section on your platform. This simplifies the process for customers who might want to immediately settle due payments or change their associated card details.
* **Stay Updated:** Periodically review your Ottu integration. With the ever-evolving digital landscape, it’s crucial to ensure you’re leveraging the latest features and adhering to the most recent security protocols.

## [FAQ](#faq)

#### :digit\_one: [**Can I use the Auto-Debit feature even if I'm not PCI DSS compliant?**](#can-i-use-the-auto-debit-feature-even-if-im-not-pci-dss-compliant)

Absolutely. With Ottu, you don't have to worry about PCI DSS compliance. Our platform securely handles all the sensitive data and never exposes this information to the merchant. This means you can safely implement the auto-debit feature just like any other Rest API

#### :digit\_two: [**Can I store card tokens in my database if I'm not PCI DSS compliant?**](#can-i-store-card-tokens-in-my-database-if-im-not-pci-dss-compliant)

Yes, you certainly can. Ottu uses [Tokenization](https://docs.ottu.com/developer/tokenization) to ensure that your customer's Primary Account Number (PAN) is never exposed. What you receive and can safely store is a token, not an actual card number. It's structured like a card number but doesn't carry the same security risks. If you're curious about how tokenization works, you can check out [this](https://en.wikipedia.org/wiki/Tokenization_\(data_security\)) for a deeper dive.

#### :digit\_three: [I don’t have an agreement ID. What should I do?](#i-dont-have-an-agreement-id.-what-should-i-do)

If you’re lacking a specific agreement [ID](#importance-for-merchants) with the payer, you have a couple of options:

1. Create a new agreement ID specifically for interacting with the gateway. Remember to save this `id` and present it to the gateway for all related payments, encompassing the cardholder initiated transaction.
2. Utilize an identifier you already have in your system, such as the order ID for the [Cardholder Initiated Transactions](#cardholder-initiated-transactions-cit) of the series.

#### :digit\_four: [**When should I save the card token in my database?**](#when-should-i-save-the-card-token-in-my-database)

The optimal time to save the card token in your database is immediately after the [First Payment](#first-payment) against the subscription that you plan to auto-debit. While it's not strictly necessary—you can always [fetch](https://docs.ottu.com/user-cards#fetch-cards) this information through the [User Cards API](https://docs.ottu.com/developer/user-cards) and Payment Methods APIs—it does streamline your processes and reduce development complexity.

#### :digit\_five: [**How can I add a new card for a customer?**](#how-can-i-add-a-new-card-for-a-customer)

Currently, the only way to save a new card is by having the customer successfully complete a payment with it. At the moment, it's not possible to just save new card details directly.

#### :digit\_six: [**Do I need to use the Checkout SDK to display payment options to the customer?**](#do-i-need-to-use-the-checkout-sdk-to-display-payment-options-to-the-customer)

No, it's not mandatory to use the [Checkout SDK](https://docs.ottu.com/developer/checkout-sdk). You can control the payment process using the responses from the [Checkout API](https://docs.ottu.com/developer/checkout-api). However, it's worth noting that the Checkout SDK simplifies the UI implementation and is necessary for certain payment methods such as [Apple Pay](https://docs.ottu.com/user-guide/payment-services/apple-pay), Google Pay, STC Pay, and others. While it's recommended to use the Checkout SDK for its simplicity and comprehensive features, the choice ultimately lies in your hands based on your specific needs.

#### :digit\_seven: [I missed saving the card which the customer agreed to be charged. Can I get it back?](#i-missed-saving-the-card-which-the-customer-agreed-to-be-charged.-can-i-get-it-back)

Yes, you can. Use the [User Cards API](https://docs.ottu.com/developer/user-cards) and provide the agreement id for which you want to retrieve the card.

#### :digit\_eight: [Can I update an existing agreement? How?](#can-i-update-an-existing-agreement-how)

For the moment, this feature is not live yet. If you require this functionality, please reach out to us at <mark style="color:blue;">**<support@ottu.com>**</mark>.

As we come to the end of this guide to Ottu's `Auto Debit API`, we hope you found it comprehensive and instructive. This document has aimed to demystify the process of integrating our API into your system, equipping you with the necessary insights to employ auto-debit payments effectively.&#x20;

Should you have more specific queries or require further guidance, we urge you to reach out to our dedicated support team. Their expertise is available to help you navigate any complexities you encounter during integration.&#x20;

At Ottu, we believe in simplifying payments and enhancing user experience. We're confident that with the `Auto Debit API`, you'll have the tools at your disposal to achieve seamless, automated transactions. Thank you for choosing Ottu, and we look forward to powering your business's payment solutions.
