> ## Documentation Index
> Fetch the complete documentation index at: https://docs.monieswitch.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Checkouts

> Learn how to use checkout to easily collect payments from your customers

Monieswitch Checkout is a JavaScript library designed to help developers create secure and user-friendly payment flows for web applications.
It offers two primary checkout methods to accommodate different payment scenarios and security requirements.

## Checkout Methods

### 1. Direct Checkout (checkout())

#### When to Use

* For simple, immediate payment flows
* When you can collect all payment information on the client-side
* For scenarios with minimal security requirements

#### Method Characteristics

* Requires a public key
* All payment details are passed directly from the client
* No prior server-side initialization needed

#### Get started

Let's walk through the steps to integrate the Monieswitch Checkout library into your web application in two simple steps.

* **Integration to your app**: Include the Checkout library via CDN in your HTML file.
* **Utilized our CDN-hosted Library**: Use the Checkout library in your JavaScript code to create a payment form and handle payment processing.

The **Result** and **HTML** (*generated from jsfiddle*) tab explains how to incorporate the Checkout library via CDN and use it in your project.

<iframe width="100%" height="700" title="Checkout with Monieswitch" src="//jsfiddle.net/caesarsage/cqkpL826/embedded/result,js,html,css/" loading="lazy" />

<Steps>
  <Step title="Integration to your app">
    To use the Checkout in your web application, you need to include the library's JavaScript file from the CDN. This is done by adding a **script** tag to your **HTML file**.

    ```html theme={"system"}
    <script defer="defer" src="https://monieswitch-staging-checkout-inline.pages.dev/inline.js"></script>
    ```

    #### Key Points:

    * The src attribute points to the CDN URL where the Checkout library is hosted.
    * The defer attribute is used to ensure that the script is executed after the HTML document has been parsed.
    * Place this **script** tag in the **head** section of your HTML document.
  </Step>

  <Step title="Utilized our CDN-hosted Library">
    Once the library is included via CDN, you can use its functionality in your JavaScript code without any additional imports or requires.

    ```html theme={"system"}
      <script>
        const paymentForm = document.getElementById("paymentForm")

        paymentForm.addEventListener("submit", function(e) {
          e.preventDefault();

          PayWithMonieswitch.checkout({
            publicKey: "pk_test_fDWvDVIBEHoSLchxGx02JtxZYP4tC7qFeGhUtmkgdnML8ZRb",
            reference: Date.now(),
            amount: Number(document.getElementById("amount").value),
            email: document.getElementById("email-address").value,
            currency: "NGN",
            channels: ["BANK"],
            bearer: document.getElementById("bearer").value,
            subaccountId: document.getElementById("subaccount").value,
            redirectURL: "https://google.com?x=monieswitch",
            onClose: function () {},
            onError: function(error) {
                console.log("Error: ", error);
            },
            onSuccess: function (reference) {
                console.log("Success: " + reference);
            }
          });
        });
      </script>
    ```

    #### Key Points:

    * The **PayWithMonieswitch** object is globally available after including the CDN script.
    * Use **PayWithMonieswitch.checkout()** to configure the payment handler with your specific options.
    * Ensure that the **PUBLIC\_KEY** is replaced with your actual public key

    <Warning>
      - Caution: Never expose your SECRET\_KEY in client-side(frontend) **code**.
      - All communication with the Monieswitch API must be routed through your server.
      - Your frontend application should only receive and process responses that have been securely handled by your backend.
    </Warning>
  </Step>
</Steps>

### 2. Continued Checkout (continueCheckout())

The continueCheckout() method represents a more secure and flexible approach to payment processing, providing enhanced control and validation through server-side initialization.
It's involve first initializing the payment on the server-side to get the checkout and then passing the checkout code to the client-side for payment processing.

#### Server-Side Checkout Initialization

First initializing the payment on the server-side to get the checkout.

##### Endpoint:

```
POST https://nini.monieswitch.com/checkout/initialize
```

##### REQUEST HEADERS

* x-access-token: Authentication SECRET\_KEY
* x-pub-key: Merchant's public key

<CodeGroup>
  ```sh curl theme={"system"}
  curl --location 'https://nini.monieswitch.com/checkout/initialize' \
  --header 'x-access-token;' \
  --header 'x-pub-key: {{merchantPublicKey}}' \
  --data-raw '{
      "amount": 1000,
      "email": "john@yahoo.com"
      "redirectURL": "http://google.com",
      "bearer": "account", //account, subaccount, customer
      "subaccountId": "",
      "currency": "NGN", // NGN
      "channels": ["BANK"]
  }'
  ```

  ```js NodeJS theme={"system"}
  var axios = require("axios");
  var data =
    '{\n    "amount": 1000,\n    "email": "john@yahoo.com"\n    // "redirectURL": "http://google.com",\n    // "bearer": "account", //account, subaccount, customer\n    // "subaccountId": "", \n    // "currency": "NGN", // NGN, USD\n    // "channels": ["BANK"]\n}';

  var config = {
    method: "post",
    maxBodyLength: Infinity,
    url: "https://nini.monieswitch.com/checkout/initialize",
    headers: {
      "x-access-token": "{SECRET_KEY}",
      "x-pub-key": "{{PublicKey}}",
    },
    data: data,
  };

  axios(config)
    .then(function (response) {
      console.log(JSON.stringify(response.data));
    })
    .catch(function (error) {
      console.log(error);
    });
  ```

  ```php PHP theme={"system"}
  <?php
    require_once 'HTTP/Request2.php';
    $request = new HTTP_Request2();
    $request->setUrl('https://nini.monieswitch.com/checkout/initialize');
    $request->setMethod(HTTP_Request2::METHOD_POST);
    $request->setConfig(array(
      'follow_redirects' => TRUE
    ));
    $request->setHeader(array(
      'x-access-token' => {{SECRET_KEY}},
      'x-pub-key' => '{{PublicKey}}'
    ));
    $request->setBody('{\n    "amount": 1000,\n    "email": "john@yahoo.com"\n    // "redirectURL": "http://google.com",\n    // "bearer": "account", //account, subaccount, customer\n    // "subaccountId": "", \n    // "currency": "NGN", // NGN, USD\n    // "channels": ["BANK"]\n}');
    try {
      $response = $request->send();
      if ($response->getStatus() == 200) {
        echo $response->getBody();
      }
      else {
        echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
        $response->getReasonPhrase();
      }
    }
    catch(HTTP_Request2_Exception $e) {
      echo 'Error: ' . $e->getMessage();
    }
  ```

  ```py Python theme={"system"}
    import http.client

    conn = http.client.HTTPSConnection("nini.monieswitch.com")
    payload = "{\n    \"amount\": 1000,\n    \"email\": \"john@yahoo.com\"\n    // \"redirectURL\": \"http://google.com\",\n    // \"bearer\": \"account\", //account, subaccount, customer\n    // \"subaccountId\": \"\", \n    // \"currency\": \"NGN\", // NGN, USD\n    // \"channels\": [\"BANK\"]\n}"
    headers = {
      'x-access-token': '{{SECRET_KEY}}',
      'x-pub-key': '{{PublicKey}}'
    }
    conn.request("POST", "/checkout/initialize", payload, headers)
    res = conn.getresponse()
    data = res.read()
    print(data.decode("utf-8"))
  ```
</CodeGroup>

##### REQUEST PARAMETERS

**Required Parameters:**

* amount (Number): Payment amount
* email (String): Customer's email address

**Optional Parameters:**

* redirectURL (String): Redirect after payment
* bearer (String): Payment bearer type
  Options: account, subaccount, customer
* subaccountId (String): Required if bearer is subaccount
* currency (String): Payment currency
  Options: NGN, USD
* channels (Array): Payment channels
  Options: BANK, CARD

##### RESPONSE

```json theme={"system"}
{
  "status": true,
  "message": "Operation is successful",
  "data": {
    "checkout": {
      "id": "cc2c7639-0779-40b8-8e69-1853d8ef4b92",
      "code": "wGOQclyVduY943DW",
      "link": "https://checkout.monieswitch.com/wGOQclyVduY9TyDW",
      "reference": "cktvJgMj8Glxfh5x"
    }
  }
}
```

#### Client-Side Payment Processing

After initializing the payment on the server-side, you can pass the checkout code to the client-side for payment processing.

#### Get started

Let's walk through the steps to integrate the Monieswitch continueCheckout library into your web application in two simple steps.

* **Integration to your app**: Include the Checkout library via CDN in your HTML file.
* **Utilized our CDN-hosted Library**: Use the ContinueCheckout library in your JavaScript code to create a payment form and handle payment processing.

The **Result** and **HTML** (*generated from jsfiddle*) tab explains how to incorporate the ContinueCheckout library and use it in your project.

<iframe width="100%" height="500" src="//jsfiddle.net/caesarsage/rzkLos2p/4/embedded/result,js,html,css/" loading="lazy" />

<Steps>
  <Step title="Integration to your app">
    To use the ContinueCheckout in your web application after server initialization, you need to include the library's JavaScript file from the CDN. This is done by adding a **script** tag to your **HTML file**.

    ```html theme={"system"}
       <script defer="defer" src="https://monieswitch-staging-checkout-inline.pages.dev/inline.js"></script>
    ```

    #### Key Points:

    * The src attribute points to the CDN URL where the  ContinueCheckout library is hosted.
    * The defer attribute is used to ensure that the script is executed after the HTML document has been parsed.
    * Place this **script** tag in the **head** section of your HTML document.
  </Step>

  <Step title="Utilized our CDN-hosted Library">
    Once the library is included via CDN, you can use its functionality in your JavaScript code without any additional imports or requires.

    ```html theme={"system"}
      <script>
        function continuePayWithMonieswitch(e) {
          e.preventDefault();

          PayWithMonieswitch.continueCheckout({
            checkoutCode: document.getElementById("code").value,
            onClose: function () {},
            onError: (error) => {
              console.log("Something went wrong: ", error);
            },
            onSuccess: function (reference) {
              console.log("successful", reference)
            },
          });
        }
     </script>
    ```

    #### Key Points:

    * Use **PayWithMonieswitch.continuePayWithMonieswitch()** to configure the payment handler with your specific options.

    <Warning>
      - Caution: Never expose your SECRET\_KEY in client-side(frontend) **code**.
      - All communication with the Monieswitch API must be routed through your server.
      - Your frontend application should only receive and process responses that have been securely handled by your backend.
    </Warning>
  </Step>
</Steps>

#### When to Use

* For complex payment scenarios
* When additional server-side validation is required
* To add an extra layer of security to your payment process

#### Method Characteristics

* Requires a checkout code generated by your server
* Payment process is initiated and validated on the server-side
* Provides more control over the payment flow

### Confirming Payment Status with Webhooks

When a payment is successfully processed, Monieswitch Checkout sends a webhook event to the webhook URL you've configured in your account settings.
It is strongly advised to utilize these webhooks to verify the payment status before fulfilling orders or providing services to your customers.
Learn more about [Webhooks](/features/payments/webhook) and how to set them up.

### Considerations

* Choose the checkout method based on your specific use case
* Prioritize server-side security
* Implement robust error handling
* Always verify payments through webhooks

<Snippet file="api-reference-link.mdx" />
