# Welcome

Welcome to the Moneroo API documentation.

Moneroo enables businesses to instantly access multiple payment providers primarily in Africa and globally with a single integration. With Moneroo, businesses can give their customers multiple payment options without manually integrating each provider.

This documentation is crafted to offer an in-depth overview of the Moneroo platform and serve as a guide for its integration and usage.

The documentation is structured in a way that first introduces you to [fundamental concepts](/introduction/authentication), followed by a deeper dive into the specifics of integration, diverse use cases, and efficient troubleshooting. Welcome to the effortless world of financial transactions with Moneroo where managing both incoming and outgoing payments is effortless, and you can focus on your core business.

### Help and Support

Moneroo is designed to provide easy user interaction, but we understand that questions and challenges may occur. Here's how you can access our support:

#### Support

For any issues with Moneroo integration, contact our support team via email, chat, or phone. We can assist with transaction issues, API calls, or feature comprehension.

#### Community Forums

Our Slack community is a valuable resource, comprising experienced and novice developers along with Moneroo team members ready to assist you. Check our forums for existing answers before contacting the support team.

Joining the Slack community lets you:

* Ask questions and get help.
* Share your experiences.
* Learn from community members.
* Receive updates and announcements.
* Provide valuable feedback.

Join us by following this Slack invitation [link](https://moneroo.slack.com/join/shared_invite/zt-2a2fc6tuo-Dn~ORQwknfZdU64JqhvEMg). Please maintain respect, patience, and constructiveness within the community.

#### Feedback

Your feedback is invaluable in improving Moneroo. We encourage suggestions for new features, improvements, or documentation changes. Provide feedback via the form in your account dashboard or the feedback link in this documentation.

<table data-card-size="large" data-view="cards"><thead><tr><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th><th data-hidden data-card-cover data-type="files"></th></tr></thead><tbody><tr><td><strong>Join our Slack Community</strong></td><td>Interact with other developers, get real-time assistance, and share your experiences.</td><td><a href="https://moneroo.io/slack">https://moneroo.io/slack</a></td><td><a href="/files/io9bkgQWXPUApmojjVsl">/files/io9bkgQWXPUApmojjVsl</a></td></tr><tr><td><strong>Provide Feedback</strong></td><td>We value your opinion. Share your suggestions and insights to help us improve.</td><td><a href="mailto:support@moneroo.io">mailto:support@moneroo.io</a></td><td><a href="/files/NGJi2qI2FS2afrfJpYyI">/files/NGJi2qI2FS2afrfJpYyI</a></td></tr><tr><td><strong>Contact Support</strong></td><td>Get in touch with our support team for assistance with your integration.</td><td><a href="mailto:support@moneroo.io">mailto:support@moneroo.io</a></td><td><a href="/files/hxpa48C4zdSWfOkLy3gy">/files/hxpa48C4zdSWfOkLy3gy</a></td></tr><tr><td><strong>Report a Bug</strong></td><td>Found a bug? Let us know, so we can fix it as soon as possible.</td><td><a href="mailto:support@moneroo.io">mailto:support@moneroo.io</a></td><td><a href="/files/CnGEVz2DNAeNraYdmSsk">/files/CnGEVz2DNAeNraYdmSsk</a></td></tr></tbody></table>


# Authentication

Moneroo API endpoints are secured with API keys, which you can create from the dashboard. You must include your API key in all API requests to the server as a header field.

To interact with the Moneroo API, you must follow each of your requests with an Authorization header including your secret key in the Authorization header. You can manage your API keys from the dashboard.

We generally provide both public and secret keys. Public keys are intended for use from your interface when integrating using JavaScript SDKs and in our mobile SDKs only. By design, public keys cannot modify any part of your account except to initiate transactions. On the other hand, secret keys must remain secret and should not be used publicly. For better safety, always use the secret keys on the backend server as environment variables if possible. If you suspect your secret key has been compromised or want to reset it, you can do so from the dashboard.

To create API keys, go to the **developer** section of the Moneroo dashboard.

<figure><img src="/files/zQIHVlrbdiwZUOTChXyg" alt=""><figcaption><p>Moneroo.io Create API Keys</p></figcaption></figure>

{% hint style="danger" %}
Do not commit your secret keys to git, or use them in client-side code.
{% endhint %}

As you build and test your integration, think about using Sandbox API keys for a secure environment. You'll find more about Sandbox mode in our detailed Moneroo API testing guide. When you're confident and ready to handle real payments, smoothly switch to Live API keys.

Remember, keeping all API keys secure is vital. Never share them. If by chance a key gets out, you can delete it immediately. Make sure to update your code with the new keys to keep everything running smoothly.

### API key Authentication

Each API request should include the API key or token, sent within the Authorization header of the HTTP call using the Bearer method. For instance, a valid **Authorization header** looks like this: `Bearer test_dHar4XY7LxsDOtmarVtjNVWXLSlXsM`.

Typically, our [SDKs](/sdks/php) offer shortcuts to simplify setting the API key or access token and interacting with the API.

In the example below, we utilize a test API key for the GET method of the payment resource, which retrieves a payment with the payment ID `test_yyfbwekjnsd`.

```bash
curl https://api.moneroo.io/v1/payments/test_yyfbwekjnsd
-H "Authorization: Bearer YOUR_SECRET_KEY"
-X GET
```

{% hint style="warning" %}
Do not set VERIFY\_PEER to FALSE. Ensure your server verifies the SSL connection to Moneroo.
{% endhint %}

### Rate Limiting

The **Moneroo API** enforces a rate limit of 120 requests per minute. If you surpass this threshold, subsequent requests will receive a `429 Too Many Requests` response. In such cases, wait for ***60 seconds*** before attempting to retry your request.


# Responses format

When interacting with the Moneroo APIs, it is essential to understand the format of the responses you will receive. This will help you properly interpret the responses and handle them appropriately in your application.

***

### **Response Structure**

Responses from the Moneroo API are returned in the JSON format and follow a consistent structure. Here's an example of a typical response:

```json
{
  "message": "Transaction initialized successfully.",
  "data": {},
  "errors" : null
}
```

Each part of this response carries specific information:

* **`message`**

This is a string field that provides a human-readable message about the result of the operation. If the API call is a success, this message usually confirms what has been achieved. If the API call has failed, this message usually provides information about what went wrong.

* **`data`**

This object contains any data returned by the operation. Its structure varies based on the specific API endpoint and the information it's designed to provide. For instance, a payment-related API might furnish payment details in this field. If no data is available, this field will be represented as an empty object (`{}`).

Please refer to the specific API endpoint documentation to understand the structure and content of the `data` field for each endpoint.

* **`errors`**

When interacting with the Moneroo APIs, you may encounter an `errors` field in the response body, especially in cases where the operation fails to execute as expected. This field is an array of error objects, each providing detailed context about specific issues encountered during the operation. These objects contain information such as the type of error, a detailed error message, and sometimes, a hint or steps to resolve the issue.&#x20;

Understanding this response format is crucial to making the most of the Moneroo APIs, as it will allow you to handle both successful operations and errors in a robust and user-friendly way.


# Errors

Moneroo API is RESTful and as such, uses conventional HTTP response codes to indicate the success or failure of requests. This section describes the summary of these codes and what they mean in our context.

### Summary

* Codes in the **2XX** range mean that the API request was processed successfully.
* Codes in the **4XX** range mean that something was wrong with the data that you sent. For example, you might have missed some required parameters/headers, or you might be using the wrong API credentials.
* Codes in the **5XX** range indicate an error in processing on our end

### Common HTTP Codes

<table><thead><tr><th width="136">Code</th><th>Description</th></tr></thead><tbody><tr><td><strong>200</strong></td><td><strong>OK</strong> - Request was successful</td></tr><tr><td><strong>201</strong></td><td><strong>Created</strong> - The request was successful, and a resource was created as a result</td></tr><tr><td><strong>202</strong></td><td>Accepted - Request has been accepted and acknowledged. We will now go ahead to process the request and notify you of the status afterwards.</td></tr><tr><td><strong>400</strong></td><td><strong>Bad Request</strong> - Malformed request or missing required parameters</td></tr><tr><td><strong>401</strong></td><td><strong>Unauthorized</strong> - Missing required headers, wrong Public or Secret Key etc</td></tr><tr><td><strong>403</strong></td><td><strong>Forbidden</strong> - You are trying to access a resource for which you don't have proper access rights.</td></tr><tr><td><strong>404</strong></td><td><strong>Not Found</strong> - You are trying to access a resource that does not exist</td></tr><tr><td><strong>422</strong></td><td><strong>Unprocessable Entity</strong> - You provided all the required parameters but they are not proper for the request</td></tr><tr><td><strong>429</strong></td><td><strong>Too Many Requests</strong> - You have exceeded the number of requests allowed in a given time frame.</td></tr><tr><td><strong>500</strong></td><td><strong>Internal Server Error</strong> - We had a glitch in our servers. Retry the request in a little while or <a href="mailto:support@moneroo.io">contact support</a>. Rarely happens.</td></tr><tr><td><strong>503</strong></td><td><strong>Service Unavailable</strong> – We are temporarily offline for maintenance. Please try again later. Rarely happens.</td></tr></tbody></table>


# Testing

During the development process of your integration, it is important to test it properly. As explained briefly in our authentication guide, you can access the Moneroo API sandbox mode using the sandbox API keys.

***

### Testing the Moneroo API

Any payments or other resources you create in sandbox mode are completely isolated from your real data. To switch from sandbox mode to real mode, you just need to change your API key.

{% hint style="info" %}
Sandbox transactions are automatically deleted after **90 days**.
{% endhint %}

### Test mode payment screen

When making a payment in sandbox mode, a red badge appears at the bottom of the page to signify that you're in sandbox mode.&#x20;

It looks like this:

<figure><img src="/files/p8VNpAc2fu4nVWkGCr4d" alt=""><figcaption><p>Moneroo.io Sandbox mode</p></figcaption></figure>


# Webhooks

Webhooks facilitate real-time communication of status updates, like successful payment notifications. They are URLs that Moneroo calls to transmit the ID of an updated object.&#x20;

Upon receiving the call, fetch the latest status and process it if there are any changes.

***

### Introduction

Moneroo can dispatch webhooks to alert your application whenever an event occurs on your account. This is particularly useful for events such as failed or successful transactions. This mechanism is also beneficial for services not directly responsible for creating an API request but still requiring the response to that request.&#x20;

You can specify the webhook URLs where you want to be notified. When an event happens, Moneroo sends you an object with all the details about the event via an HTTP POST request to the defined endpoint URLs.

<figure><img src="/files/RbIz8aHoHEPnLsrjSCEM" alt=""><figcaption><p>Moneroo.io Webhook</p></figcaption></figure>

### Types of events

Here are the current events we trigger. More will be added as we extend our actions in the future.

#### Payment events

<table><thead><tr><th width="264">Event Name</th><th>Description</th></tr></thead><tbody><tr><td><code>payment.initiated</code></td><td>Triggered when a new payment process begins.</td></tr><tr><td><code>payment.success</code></td><td>Triggered when a payment process completes successfully.</td></tr><tr><td><code>payment.failed</code></td><td>Triggered when a payment process fails.</td></tr><tr><td><code>payment.cancelled</code></td><td>Triggered when a payment process is cancelled.</td></tr></tbody></table>

#### Payout events

<table><thead><tr><th width="246">Event Name</th><th>Description</th></tr></thead><tbody><tr><td><code>payout.initiated</code></td><td>Triggered when a payout process begins.</td></tr><tr><td><code>payout.success</code></td><td>Triggered when a payout process completes successfully.</td></tr><tr><td><code>payout.failed</code></td><td>Triggered when a payout process fails.</td></tr></tbody></table>

You can use these event names in your application to instigate specific actions whenever Moneroo emits these events.

### Structure of a webhook

All webhook payloads follow a consistent basic structure, including two main components:

* **Event**: The type of event that has occurred.
* **Data**: The data associated with the event. The contents of this object will vary depending on the event, but typically it will contain details of the event, including:
  * an `id` containing the ID of the transaction
  * a `status`, describing the status of the transaction payment, payout or customer details, if applicable

**Example**

```json
{
  "event": "payment.success",
  "data": {
    "id": "123456",
    "amount": 100,
    "currency": "USD",
    "status": "success",
    "customer": {
      "id": "123456",
      "email": "hello@example.com",
      "firstName": "John",
      "lastName": "Doe",
      "phone": "+1 555 555 5555"
    }
  }
}
```

We do not provide complete information through the webhook, so you'll need to fetch the latest status of the object.

### Configuration

To configure webhooks, navigate to your app [dashboard](https://app.moneroo.io/), access the **Developers** section, and click on the **Webhooks** tab.&#x20;

<figure><img src="/files/gu0bYsZKwl58Er5cbI08" alt=""><figcaption><p>Webhook tab</p></figcaption></figure>

There you can add a new webhook by clicking on the **Add webhook** button and filling in the form with the following details:

* **URL**: The URL of the webhook.
* **Secret**: The secret key used to sign the webhook payload.
* The secret key is used to sign the webhook payload, enabling you to verify that the webhook originated from Moneroo.
* You can add a maximum of **15 webhooks** per application.

You can also enable, disable, or delete an existing webhook by clicking on the respective buttons.

The webhook is sent as a POST request to the URL you specify. The request body contains JSON, detailing the event that occurred. Ensure your endpoint can accept POST requests and parse JSON payloads.

### Receiving a Webhook

When Moneroo sends a webhook to your URL, it includes a JSON payload detailing the event. For example, here's a payload for the `payment.success` event:

```json
{
  "event": "payment.success",
  "data": {
    "id": "123456",
    "amount": 100,
    "currency": "USD",
    "status": "success"
  }
}
```

You can use the `event` field in the payload to determine the action your application should take.

To acknowledge the receipt of a webhook, your endpoint must return a 200 HTTP status code. Any other response codes, including 3xx codes, will be treated as a failure. We do not consider the response body or headers.

If your endpoint doesn't return a 200 HTTP status code or doesn't respond within 3 seconds, we'll retry the webhook up to 3 times with a 10-minute delay between each attempt.

Web frameworks like Rails, Laravel, or Django typically check that every POST request contains a CSRF token. While this is a useful security feature protecting against cross-site request forgery, you'll need to exempt the webhook endpoint from CSRF protection to ensure webhooks work (as demonstrated in the examples below).

### Verifying a Webhook

When you receive a webhook, you should verify its origin. Each webhook request includes a `X-Moneroo-Signature` header. The value of this header is a signature generated using your webhook signing secret and the webhook's payload.

To verify the signature, you'll need to compute the signature on your end and compare it to the `X-Moneroo-Signature` header's value.

The signature is computed using **HMAC-SHA256** with the webhook signing secret as the key and the payload as the value.

If the signature is valid, respond with a `200 OK` status code. If it's not valid, respond with `403 Forbidden`.

### Examples

{% hint style="info" %}
Please replace `'your_webhook_signing_secret'`, `'your_payload'` and `'header_value'` with your actual values. For the Node.js, Java, and Go examples, you need to get the request body and header values from your HTTP request object.
{% endhint %}

{% tabs %}
{% tab title="PHP" %}

```php
<?php
$secret = 'your_webhook_signing_secret';
$payload = file_get_contents('php://input');
$signature = hash_hmac('sha256', $payload, $secret);

if (hash_equals($signature, $_SERVER['HTTP_X_MONEROO_SIGNATURE'])) {
    http_response_code(200);
} else {
    http_response_code(403);
}
?>
```

{% endtab %}

{% tab title="JavaScript (Node.js)" %}

```javascript
const crypto = require("crypto");
const secret = "your_webhook_signing_secret";
const payload = req.body;
const signature = crypto
  .createHmac("sha256", secret)
  .update(JSON.stringify(payload))
  .digest("hex");

if (signature === req.headers["x-moneroo-signature"]) {
  res.sendStatus(200);
} else {
  res.sendStatus(403);
}
```

{% endtab %}

{% tab title="Java" %}

```java
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

// Your secret key
String secret = "your_webhook_signing_secret";
String payload = "your_payload";
String XMonerooSignature = "header_value";

Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
sha256_HMAC.init(secret_key);

String computedSignature = new String(sha256_HMAC.doFinal(payload.getBytes(StandardCharsets.UTF_8)));
if (computedSignature.equals(XMonerooSignature)) {
    System.out.println("200 OK");
} else {
    System.out.println("403 Forbidden");
}
```

{% endtab %}

{% tab title="Python" %}

```python
import hashlib
import hmac

secret = 'your_webhook_signing_secret'
payload = 'your_payload'
XMonerooSignature = 'header_value'

computed_signature = hmac.new(secret.encode(), msg=payload.encode(), digestmod=hashlib.sha256).hexdigest()

if computed_signature == XMonerooSignature:
    print("200 OK")
else:
    print("403 Forbidden")
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/hex"
    "fmt"
)

func main() {
    secret := "your_webhook_signing_secret"
    payload := []byte("your_payload")
    XMonerooSignature := "header_value"

    h := hmac.New(sha256.New, []byte(secret))
    h.Write(payload)
    computedSignature := hex.EncodeToString(h.Sum(nil))

    if computedSignature == XMonerooSignature {
        fmt.Println("200 OK")
    } else {
        fmt.Println("403 Forbidden")
    }
}
```

{% endtab %}
{% endtabs %}

### Webhook Best Practices

* **Don't Rely Solely on Webhooks:** Make sure you have a backup strategy like a background job that checks for the status of any pending transactions at regular intervals. This can be useful in case your webhook endpoint fails or you haven't received a webhook in the following seconds.
* **Use a Secret Hash:** Your webhook URL is public, anyone can send a fake payload. We recommend using a secret hash to authenticate requests.
* **Always Re-query:** Verify received details with our API to ensure data integrity. For example, upon receiving a successful payment notification, use our transaction verification endpoint to verify the transaction status.
* **Respond Quickly:** Your webhook endpoint must respond within a certain time limit to avoid failure and retries. Avoid executing long-running tasks in your webhook endpoint to prevent timeouts. Respond immediately with a 200 status code if successful, and then perform any long-running tasks asynchronously.
* **Handle Duplicates:** Webhooks may be delivered more than once in some cases. For example, if we don't receive a response from your endpoint, we'll retry the webhook. Make sure your endpoint can handle duplicate webhook notifications.
* **Handle Failures:** If your endpoint fails, we'll retry the webhook up to 3 times with a 10-minute delay between each attempt. If all attempts fail, we'll stop retrying and mark the webhook as failed. You can view failed webhooks in your dashboard.


# Initialize payment

When you collect payments with Moneroo, you have many options. Here's a quick overview:

If you're building a website or application

* [**Moneroo Standard**](/payments/standard-integration) **:** This is the basic, "standard" integration approach. To use this, you need to call our API from your server to generate a payment link. You then redirect your customer to this link for them to make the payment. Once the payment has been processed, we'll redirect them back to you.

Another options and integration will be available soon.


# Standard Integration

### Overview

Moneroo Standard is our "standard" payments flow that redirects your customer to a Moneroo-hosted payments page.

Here's how it works:

1. From your server, call the payment initialization endpoint with the payment details.
2. We'll return a link to a payment page. Redirect your customer to this link to make the payment.
3. Upon completion of the transaction, we'll redirect the customer back to you (to the return\_url you provided) with the payment details.

### Step 1: Collect payment details

First, you need to assemble payment details that will be sent to your API as a JSON object.

Here fields you need to collect:

<table><thead><tr><th width="348">Field Name</th><th width="120">Type</th><th width="76">Required</th><th>Description</th></tr></thead><tbody><tr><td><code>amount</code></td><td>integer</td><td>Yes</td><td>The payment amount.</td></tr><tr><td><code>currency</code></td><td>string</td><td>Yes</td><td>The currency of the payment.</td></tr><tr><td><code>description</code></td><td>string</td><td>Yes</td><td>Description of the payment.</td></tr><tr><td><code>return_url</code></td><td>string</td><td>Yes</td><td>Return URL where your customer will be redirected after payment.</td></tr><tr><td><code>customer.email</code></td><td>string</td><td>Yes</td><td>Customer's email address.</td></tr><tr><td><code>customer.first_name</code></td><td>string</td><td>Yes</td><td>Customer's first name.</td></tr><tr><td><code>customer.last_name</code></td><td>string</td><td>Yes</td><td>Customer's last name.</td></tr><tr><td><code>customer.phone</code></td><td>string</td><td>No¹</td><td>Customer's phone number.</td></tr><tr><td><code>customer.address</code></td><td>string</td><td>No¹</td><td>Customer's address.</td></tr><tr><td><code>customer.city</code></td><td>string</td><td>No¹</td><td>Customer's city.</td></tr><tr><td><code>customer.state</code></td><td>string</td><td>No¹</td><td>Customer's state.</td></tr><tr><td><code>customer.country</code></td><td>string</td><td>No¹</td><td>Customer's country.</td></tr><tr><td><code>customer.zip</code></td><td>string</td><td>No¹</td><td>Customer's zip code.</td></tr><tr><td><code>metadata</code></td><td>array</td><td>No²</td><td>Additional data for the payment.</td></tr><tr><td><code>methods</code></td><td>array</td><td>No³</td><td>Payment method you want to make available for this transaction.</td></tr><tr><td><code>restrict_country_code</code></td><td>string</td><td>No⁴</td><td>Restrict the payment to a specific country.</td></tr><tr><td><code>restricted_phone</code></td><td>object</td><td>No⁴</td><td>Restrict the payment to a specific phone number.</td></tr><tr><td><code>restricted_phone.number</code></td><td>string</td><td>Yes⁵</td><td>The phone number to restrict the payment to.</td></tr><tr><td><code>restricted_phone.country_code</code></td><td>string</td><td>Yes⁵</td><td>The country code of the restricted phone number.</td></tr></tbody></table>

1. If not provided, the customer can be prompted to enter these details during the payment process based on the selected payment method.
2. There should be an array of key-value pairs. Only string values are allowed.
3. If not provided, all available payment methods will be allowed. The array should contain only the supported [payment method's](/payments/available-methods) shortcodes.
4. You can use either `restrict_country_code` or restricted\_phone, but not both. They are mutually exclusive.
5. Required if `restricted_phone` is provided.

### Step 2: Obtain a Payment Link

Next, initiate the payment by calling the API with the collected payment details using the secret key for authorization.

#### Example request :

```bash
POST /v1/payments/initialize
Host: https://api.moneroo.io
Authorization: Bearer YOUR_SECRET_KEY
Content-Type: application/json
Accept: application/json
{
    "amount": 100,
    "currency": "USD",
    "description": "Payment for order #123",
    "customer": {
        "email": "john@example.com",
        "first_name": "John",
        "last_name": "Doe"
    },
    "return_url": "https://example.com/payments/thank-you"
    "metadata": {
        "order_id": "123",
        "customer_id": "123" 
    },
    "methods": ["mtn_bj", "moov_bj"] # Once again, it is not required
}
```

#### Example response :

```json
{
  "message": "Transaction initialized successfully",
  "data": {
    "id": "5f7b1b2c",
    "checkout_url": "https://checkout.moneroo.io/5f7b1b2c"
  }
}
```

### Step 3: Redirect the User to the Payment Link

You only need to redirect your customer to the link returned in `data.checkout_url`. We will display our payment interface for the customer to make the payment.

### Step 4: After Payment

Once the payment is made, whether successful or failed, four things will occur:

* We redirect your user to your `return_url` with the status, **`paymentId`**, and **`paymentStatus`** in the query parameters once the payment is completed.
* We will send you a webhook if you have activated it. For more information on webhooks and to see examples, check out our [webhooks guide](/introduction/webhooks).
* If the payment is successful, we will send an acknowledgment email to your customer (unless you have disabled this feature).
* We will email you (unless you have disabled this feature).
* On the server side, you need to handle the redirection and always check the [final status of the transaction](/payments/transaction-verification).&#x20;

If you have webhooks enabled, we'll send you a notification for each failed payment attempt. This is useful in case you want to later reach out to customers who had issues paying. See our [webhooks guide](/introduction/webhooks) for an example.

### Example

{% hint style="danger" %}

* Do not forget to replace `YOUR_SECRET_KEY` with your actual secret key.
* All subsequent examples should be executed in the backend. Never expose your secret key to the public.
  {% endhint %}

{% tabs %}
{% tab title="cURL" %}

```
curl -X POST https://api.moneroo.io/v1/payments/initialize \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer YOUR_SECRET_KEY" \
     -H "Accept: application/json" \
     -d '{
         "amount": 100,
         "currency": "USD",
         "description": "Payment for order #123",
         "customer": {
             "email": "john@example.com",
             "first_name": "John",
             "last_name": "Doe"
         },
         "return_url": "https://example.com/payments/thank-you",
         "metadata": {
             "order_id": "123",
             "customer_id": "123"
         },
         "methods": ["qr_ngn", "bank_transfer_ngn"]
     }'
```

{% endtab %}

{% tab title="PHP" %}

<pre class="language-php"><code class="lang-php"><strong>&#x3C;?php
</strong>
$url = 'https://api.moneroo.io/v1/payments/initialize';

$headers = [
    'Content-Type: application/json',
    'Authorization: Bearer YOUR_SECRET_KEY'
    'Accept: application/json'
];

$data = [
    "amount" => 100,
    "currency" => "USD",
    "description" => "Payment for order #123",
    "customer" => [
        "email" => "john@example.com",
        "first_name" => "John",
        "last_name" => "Doe"
    ],
    "return_url" => "https://example.com/payments/thank-you",
    "metadata" => [
        "order_id" => "123",
        "customer_id" => "123",
    ],
    "methods" => ["qr_ngn", "bank_transfer_ngn"]
];

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

if ($httpcode != 201) {
    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}

$response_data = json_decode($response, true);

// Redirect to the checkout page
header("Location: " . $response_data['checkout_url']);

?>

</code></pre>

{% endtab %}

{% tab title="Python" %}

```python
import requests
import json

url = 'https://api.moneroo.io/v1/payments/initialize'

headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_SECRET_KEY'
    'Accept': 'application/json'
}

data = {
    "amount": 100,
    "currency": "USD",
    "description": "Payment for order #123",
    "customer": {
        "email": "john@example.com",
        "first_name": "John",
        "last_name": "Doe"
    },
    "return_url": "https://example.com/payments/thank-you",
    "metadata": {
        "order_id": "123",
        "customer_id": "123",
    },
    "methods": ["qr_ngn", "bank_transfer_ngn"]
}

response = requests.post(url, headers=headers, data=json.dumps(data))

if response.status_code != 201:
    raise Exception(f"Request failed with status {response.status_code}")

checkout_url = response.json()['checkout_url']
print(f"Redirect to: {checkout_url}")
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"bytes"
	"encoding/json"
	"net/http"
	"fmt"
)

func main() {
	data := map[string]interface{}{
		"amount": 100,
		"currency": "USD",
		"description": "Payment for order #123",
		"customer": map[string]string{
			"email": "john@example.com",
			"first_name": "John",
			"last_name": "Doe",
		},
		"return_url": "https://example.com/payments/thank-you",
		"metadata": map[string]string{
			"order_id": "123",
			"customer_id": "123",
		},
		"methods": []string{"qr_ngn", "bank_transfer_ngn"},
	}

	bytesRepresentation, _ := json.Marshal(data)

	req, _ := http.NewRequest("POST", "https://api.moneroo.io/v1/payments/initialize", bytes.NewBuffer(bytesRepresentation))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer YOUR_SECRET_KEY")
	req.Header.Set("Accept", "application/json")

	client := &http.Client{}
	response, _ := client.Do(req)
	defer response.Body.Close()

	var result map[string]interface{}
	json.NewDecoder(response.Body).Decode(&result)

	if response.StatusCode != 201 {
		panic(fmt.Sprintf("Request failed with status %d", response.StatusCode))
	}

	fmt.Printf("Redirect to: %s", result["checkout_url"])
}
```

{% endtab %}

{% tab title="JavaScript (Node.js)" %}

```javascript
const axios = require('axios');

const data = {
    "amount": 100,
    "currency": "USD",
    "description": "Payment for order #123",
    "customer": {
        "email": "john@example.com",
        "first_name": "John",
        "last_name": "Doe"
    },
    "return_url": "https://example.com/payments/thank-you",
    "metadata": {
        "order_id": "123",
        "customer_id": "123",
    },
    "methods": ["qr_ngn", "bank_transfer_ngn"]
};

const options = {
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_SECRET_KEY'
    'Accept': 'application/json'
  }
};

axios.post('https://api.moneroo.io/v1/payments/initialize', data, options)
    .then((response) => {
        if (response.status !== 201) {
            throw new Error(`Request failed with status ${response.status}`);


 }
        console.log(`Redirect to: ${response.data.checkout_url}`);
    })
    .catch((error) => {
        console.error(error);
    });
```

{% endtab %}
{% endtabs %}


# Transaction verification

After initiating a payment, you should confirm that the transaction was processed through Monero before crediting/debiting your customer in your application. This step ensures that the payment aligns with your expectations.&#x20;

Here are some key points to verify during the payment confirmation:

* **Confirm the Transaction Reference:** Ensure that the transaction reference matches the one you generated.
* **Check the Transaction Status:** Verify the transaction status is marked as `success` for successful payments. For more information on transaction statuses, refer to the Transaction Status Section.
* **Verify the Currency:** Confirm that the payment's currency matches the expected currency.
* **Ensure Correct Payment Amount:** Check that the paid amount is equal to or greater than the anticipated amount. If the amount is higher, provide the customer with the corresponding value and refund the surplus.

To authenticate a payment, use the `verify transaction` endpoint. Specify the transaction ID in the URL. You can obtain the transaction ID from the `data.id` field in the response after creating a transaction, as well as from the webhook payload for any transaction.

### Request

```bash
GET /v1/payments/{paymentId}/verify HTTP/1.1
Host: https://api.moneroo.io
Authorization: Bearer YOUR_SECRET_KEY
Content-Type: application/json
Accept: application/json
```

#### Parameters

* Endpoint: `/v1/payments/{paymentId}/verify`
* Method: `GET`

<table><thead><tr><th width="143">Name</th><th width="81">Type</th><th width="102">Required</th><th>Description</th></tr></thead><tbody><tr><td><code>paymentId</code></td><td>String</td><td>Yes</td><td>The unique ID of the payment transaction to verify.</td></tr></tbody></table>

### **Response Structure**

The response from this API endpoint will be in the standard Moneroo API response format. You'll get a response that looks like this:

```json
{
  "message": "Payment transaction fetched successfully",
  "data": {
    // Details of the payment transaction
  }
}
```

**Successful Response:**

Upon successful retrieval, the endpoint returns a HTTP status code of 200, and the details of the payment transaction in the response body.

**Error Responses:**

If there's an issue with your request, the API will return an error response. The type of error response depends on the nature of the issue. Check out our response format page for more information.

### Security considerations

This endpoint requires a bearer token for authentication. The bearer token must be included in the `Authorization` header of the request. Ensure the token is kept secure and not shared or exposed inappropriately.

### Request examples

Please replace `'paymentId'` with the actual payment transaction ID and `'your_token'` with your valid authorization token in the code snippets above.

{% tabs %}
{% tab title="Curl" %}

```bash
curl --location --request GET 'https://api.moneroo.io/v1/payments/{paymentId}/verify' \
--header 'Authorization: Bearer YOUR_TOKEN'
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php

$paymentId = 'your_payment_id';
$token = 'your_token';

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://api.moneroo.io/v1/payments/{$paymentId}/verify",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer {$token}"
  ]
]);

$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ($httpCode === 200) {
  // Handle successful response
} else {
  // Handle error response
}

curl_close($curl);
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

paymentId = 'your_payment_id'
token = 'your_token'

headers = {
  'Authorization': f'Bearer {token}'
}

response = requests.get(f'https://api.moneroo.io/v1/payments/{paymentId}/verify', headers=headers)

if response.status_code == 200:
  # Handle successful response
else:
  # Handle error response
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"fmt"
	"net/http"
)

func main() {
	paymentId := "your_payment_id"
	token := "your_token"

	url := fmt.Sprintf("https://api.moneroo.io/v1/payments/%s/verify", paymentId)
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		// Handle error
	}

	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		// Handle error
	}
	defer resp.Body.Close()

	if resp.StatusCode == 200 {
		// Handle successful response
	} else {
		// Handle error response
	}
}
```

{% endtab %}

{% tab title="JavaScript (Node.js)" %}

```javascript
const axios = require("axios");

const paymentId = "your_payment_id";
const token = "your_token";

axios
  .get(`https://api.moneroo.io/v1/payments/${paymentId}/verify`, {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  })
  .then((response) => {
    if (response.status === 200) {
      // Handle successful response
    } else {
      // Handle error response
    }
  })
  .catch((error) => {
    // Handle error
  });
```

{% endtab %}
{% endtabs %}

### Response example

You'll get a response that looks like this:

```json
{
    "message": "Payment transaction fetched successfully!",
    "data": {
        "id": "k4su1ii7abdz",
        "status": "success",
        "is_processed": false,
        "processed_at": null,
        "amount": 200,
        "amount_formatted": "XOF 200",
        "currency": {
            "name": "CFA Franc BCEAO",
            "symbol": "XOF",
            "symbol_first": false,
            "decimals": 0,
            "decimal_mark": ",",
            "thousands_separator": ".",
            "subunit": "Centime",
            "subunit_to_unit": 100,
            "symbol_native": "XOF",
            "decimal_digits": 0,
            "rounding": 0,
            "code": "XOF",
            "name_plural": "CFA francs BCEAO",
            "icon_url": "https://assets.cdn.moneroo.io/currencies/XOF.svg"
        },
        "description": "Payment for order #124",
        "return_url": "https://axaship.com?paymentId=k4su1ii7abdz&paymentStatus=success",
        "environment": "sandbox",
        "initiated_at": "2024-01-31T14:46:13.000000Z",
        "metadata": {
            "order_id": "124",
            "customer_id": "124"
        },
        "app": {
            "id": "01HHJYSA4VCBVK135N4KTYF76J",
            "name": "Smarthome",
            "website_url": "https://www.smarthome.com",
            "icon_url": "https://assets.cdn.moneroo.io/samples/business.svg",
            "created_at": "2023-12-14T01:24:17.000000Z",
            "updated_at": "2023-12-14T01:24:17.000000Z",
            "is_enabled": false
        },
        "customer": {
            "id": "tzowl42roc7z",
            "first_name": "John",
            "last_name": "Doe",
            "email": "john@example.com",
            "phone": null,
            "address": null,
            "city": null,
            "state": null,
            "country_code": null,
            "country": null,
            "zip_code": null,
            "profile_url": "https://eu.ui-avatars.com/api/?name=John+Doe&background=5F6368&color=fff&size=256&rounded=true&bold=true",
            "created_at": "2023-12-14T01:49:28.000000Z",
            "updated_at": "2023-12-14T01:49:28.000000Z"
        },
        "capture": {
            "identifier": "14189ccd-4c52-4f29-bbd2-75ab45fc8c80",
            "rate": null,
            "rate_formatted": null,
            "correction_rate": null,
            "phone_number": "22951345780",
            "failure_message": null,
            "failure_error_code": null,
            "failure_error_type": null,
            "metadata": {
                "network_transaction_id": null,
                "amount_debited": null,
                "commission": null,
                "fees": null,
                "selected_payment_method": null
            },
            "amount": 200,
            "amount_formatted": "XOF 200",
            "currency": {
                "name": "CFA Franc BCEAO",
                "symbol": "XOF",
                "symbol_first": false,
                "decimals": 0,
                "decimal_mark": ",",
                "thousands_separator": ".",
                "subunit": "Centime",
                "subunit_to_unit": 100,
                "symbol_native": "XOF",
                "decimal_digits": 0,
                "rounding": 0,
                "code": "XOF",
                "name_plural": "CFA francs BCEAO",
                "icon_url": "https://assets.cdn.moneroo.io/currencies/XOF.svg"
            },
            "method": {
                "id": "kt1itmi9xv0g",
                "name": "MTN MoMo Benin",
                "short_code": "mtn_bj",
                "icon_url": "https://assets.cdn.moneroo.io/icons/circle/mtn_xof.svg"
            },
            "gateway": {
                "id": "6eip4udyt8o6",
                "account_name": "Acme Inc",
                "name": "PawaPay (Sandbox)",
                "short_code": "pawapay_sandbox",
                "icon_url": "https://assets.cdn.moneroo.io/icons/circle/pawapay.svg",
                "transaction_id": "14189ccd-4c52-4f29-bbd2",
                "transaction_status": "COMPLETED",
                "transaction_failure_message": null
            },
            "context": {
                "ip": "2a09:bac5:52d:c8",
                "user_agent": {
                    "is_desktop": true,
                    "is_robot": false,
                    "platform": "OS X",
                    "browser": "Chrome",
                    "version": "120.0.0.0",
                    "device": "Macintosh",
                    "is_mobile": false,
                    "is_phone": false,
                    "is_tablet": false,
                    "is_ios": false,
                    "is_android": false
                },
                "country": {
                    "name": "Benin",
                    "code": "BJ",
                    "alpha_3_code": "BEN",
                    "dial_code": "+229",
                    "currency": "XOF",
                    "currency_symbol": "CFA",
                    "flag": "https://cdn.axazara.com/flags/svg/BJ.svg"
                },
                "local": "en"
            }
        },
        "created_at": "2024-01-31T14:46:13.000000Z"
    },
    "errors": null
}

```

The transaction details are contained in the data object. For instance:

* `id`: A unique identifier for the payment transaction.
* `status`: The current status of the transaction (`success`, `pending`, `failed`).
* `is_processed`: A boolean value indicating whether the transaction has been mark as processed.
* `processed_at`: A timestamp of when the transaction was processed. `null` if not processed yet.
* `amount`: The total amount of the transaction.
* `currency`: An object containing details of the currency used for the transaction.
* `amount_formatted`: A string representing the formatted amount of the transaction.
* `description`: A brief description of the payment transaction.
* `return_url`: The URL where the user will be redirected post-transaction.
* `environment`: Indicates the environment where the transaction was processed (`sandbox` or `live`).
* `capture` : An object detailing specifics details about payment transaction ( `method`, `gateway`, `context` )
* `initiated_at`: The timestamp when the transaction was initiated.
* `metadata`: An object that stores additional information passed along with the transaction.
* `app`: An object containing information about the application through which the transaction was made.

Transaction object

| Field Name             | Description                                          |
| ---------------------- | ---------------------------------------------------- |
| `id`                   | The public ID of the transaction.                    |
| `status`               | The status of the transaction.                       |
| `is_processed`         | Indicates whether the transaction is processed.      |
| `processed_at`         | The time when the transaction was processed.         |
| `amount`               | The amount involved in the transaction.              |
| `currency`             | The currency used in the transaction.                |
| `amount_formatted`     | The formatted amount involved in the transaction.    |
| `description`          | The description of the transaction.                  |
| `return_url`           | The URL to return to after the transaction.          |
| `environment`          | The environment in which the transaction occurred.   |
| `initiated_at`         | The time when the transaction was initiated.         |
| `checkout_url`         | The URL to checkout the transaction.                 |
| `payment_phone_number` | The phone number associated with the payment method. |
| `app`                  | The app associated with the transaction.             |
| `customer`             | The customer associated with the transaction.        |
| `method`               | The payment method associated with the transaction.  |
| `gateway`              | The payment gateway associated with the transaction. |
| `metadata`             | The metadata associated with the transaction.        |
| `context`              | The context associated with the transaction.         |

**`capture` Object:**

| Field Name           | Description                                                                 |
| -------------------- | --------------------------------------------------------------------------- |
| `identifier`         | A unique identifier for the payment capture.                                |
| `rate`               | The exchange rate applied to the transaction, if any. Null if not applied.  |
| `rate_formatted`     | The formatted string of the applied exchange rate. Null if not applied.     |
| `correction_rate`    | Any correction to the initial rate that was applied. Null if not applied.   |
| `phone_number`       | The phone number associated with the payment method.                        |
| `failure_message`    | A message detailing any failure that occurred during capture. Null if none. |
| `failure_error_code` | The error code associated with the failure, if any. Null if no error.       |
| `failure_error_type` | The type of error encountered during capture, if any. Null if no error.     |
| `metadata`           | Additional metadata related to the capture process.                         |
| `amount`             | The amount that was captured.                                               |
| `amount_formatted`   | The formatted amount that was captured according to the currency rules.     |
| `currency`           | A nested object detailing the currency used in the capture.                 |
| `method`             | A nested object describing the payment method used for capture.             |
| `gateway`            | A nested object with details about the payment gateway used.                |
| `context`            | A nested object containing contextual details about the transaction.        |


# Retrieve payment

The Moneroo platform's API offers an endpoint that allows you to fetch the detailed information of a specific payment transaction based on its unique `transaction ID`.

This guide will walk you through the process of retrieving a payment transaction using Moneroo's API.

### Request

```bash
GET /v1/payments/{paymentId} HTTP/1.1
Host: https://api.moneroo.io
Authorization: Bearer YOUR_SECRET_KEY
Content-Type: application/json
Accept: application/json
```

#### Parameters

* Endpoint: `/v1/payments/{paymentId}`
* Method: `GET`

| Name        | Type   | Required | Description                                           |
| ----------- | ------ | -------- | ----------------------------------------------------- |
| `paymentId` | String | Yes      | The unique ID of the payment transaction to retrieve. |

### **Response Structure**

The response from this API endpoint will be in the standard Moneroo API response format.

You'll get a response that looks like this:

```json
{
  "success": true,
  "message": "Payment transaction fetched successfully",
  "data": {
    // Details of the payment transaction
  }
}
```

**Successful Response:**

Upon successful retrieval, the endpoint returns a HTTP status code **200**, and the payment transaction details in the response body.

**Error Responses:**

If there's an issue with your request, the API will return an error response. The type of error response depends on the nature of the issue. Check out the [response format page](/introduction/errors) for more information.

### Security considerations

This endpoint requires a bearer token for authentication. The bearer token must be included in the `Authorization` header of the request. Ensure the token is kept secure and not shared or exposed inappropriately.

### Request examples

{% hint style="info" %}
Please replace `'`**`paymentId`**`'` with the actual payment transaction ID and `'`**`your_token`**`'` with your valid authorization token in the code snippets above.
{% endhint %}

{% tabs %}
{% tab title="Curl" %}

```bash
curl --location --request GET 'https://api.moneroo.io/v1/payments/{paymentId}' \
--header 'Authorization: Bearer YOUR_TOKEN'
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php

$paymentId = 'your_payment_public_id';
$token = 'your_token';

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://api.moneroo.io/v1/payments/{$paymentId}",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer {$token}"
  ]
]);

$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ($httpCode === 200) {
  $responseData = json_decode($response, true);
  // Handle successful response and retrieve the payment transaction details
} else {
  // Handle error response
}

curl_close($curl);
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

payment_public_id = 'your_payment_public_id'
token = 'your_token'

headers = {
  'Authorization': f'Bearer {token}'
}

response = requests.get(f'https://api.moneroo.io/v1/payments/{payment_public_id}', headers=headers)

if response.status_code == 200:
  data = response.json()
  # Handle successful response and retrieve the payment transaction details
else:
  # Handle error response
```

{% endtab %}

{% tab title="Go" %}

<pre class="language-go"><code class="lang-go"><strong>package main
</strong>
import (
	"fmt"
	"net/http"
	"io/ioutil"
)

func main() {
	paymentPublicID := "your_payment_public_id"
	token := "your_token"

	url := fmt.Sprintf("https://api.moneroo.io/v1/payments/%s", paymentPublicID)
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		// Handle error
	}

	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))

	client := &#x26;http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		// Handle error
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// Handle error
	}

	if resp.StatusCode == 200 {
		// Handle successful response and retrieve the payment transaction details
	} else {
		// Handle error response
	}
}
</code></pre>

{% endtab %}

{% tab title="JavaScript (Node.js)" %}

```javascript
const axios = require("axios");

const paymentId = "your_payment_public_id";
const token = "your_token";

axios
  .get(`https://api.moneroo.io/v1/payments/${paymentId}`, {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  })
  .then((response) => {
    if (response.status === 200) {
      const data = response.data;
      // Handle successful response and retrieve the payment transaction details
    } else {
      // Handle error response
    }
  })
  .catch((error) => {
    // Handle error
  });
```

{% endtab %}
{% endtabs %}

### Response example

You'll get a response that looks like this:

```json
{
  "success": true,
  "message": "Payment transaction fetched successfully",
  "data": {
    "id": "abc123",
    "status": "success",
    "is_processed": true,
    "processed_at": "2023-05-21T12:00:00Z",
    "amount": 100.0,
    "currency": "USD",
    "amount_formatted": "$100.00",
    "description": "Purchase of goods",
    "return_url": "https://example.com/return",
    "environment": "production",
    "initiated_at": "2023-05-21T11:00:00Z",
    "checkout_url": "https://example.com/checkout",
    "payment_phone_number": "+1234567890",
    "app": {
      "id": "app1",
      "name": "Example App",
      "icon_url": "https://example.com/icon.png"
    },
    "customer": {
      "id": "cust1",
      "first_name": "John",
      "last_name": "Doe",
      "email": "john.doe@example.com",
      "phone": "+1234567890",
      "address": "123 Main St",
      "city": "Springfield",
      "state": "IL",
      "country_code": "US",
      "country": "United States",
      "zip_code": "62701",
      "environment": "production",
      "created_at": "2023-01-01T00:00:00Z",
      "updated_at": "2023-05-21T00:00:00Z"
    },
    "method": {
      "name": "Credit Card",
      "code": "cc",
      "icon_url": "https://example.com/cc.png",
      "environment": "production"
    },
    "gateway": {
      "name": "Stripe",
      "account_name": "Acme Corp",
      "code": "stripe",
      "icon_url": "https://example.com/stripe.png",
      "environment": "production"
    },
    "metadata": {
      "custom_field1": "custom_value1",
      "custom_field2": "custom_value2"
    },
    "context": {
      "ip": "192.0.2.0",
      "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (HTML, like Gecko) Chrome/58.0.3029.110 Safari/537",
      "country": "US",
      "local": "en-US"
    }
  }
}
```

The `data` field will contain the transaction details. The specific structure and content of this field depend on the details of the individual transaction.


# Status

When initiating payments, monitoring the transaction statuses allows you to track their progress effectively. This section will help you understand the meaning of each transaction status at Moneroo.

Each payment stage processed through our platform is marked with a specific transaction status. These statuses are categorized into two groups: **transitional** and **final**.

#### Simple View of Payment Transaction Statuses

<figure><img src="/files/rex7vjOqRzsrUycLxiiV" alt=""><figcaption><p>Moneroo payment transaction state</p></figcaption></figure>

To provide a clear overview of the payment transaction statuses, refer to the table below:

<table><thead><tr><th width="165.33333333333331">Status</th><th width="144" align="center">State</th><th>Description</th></tr></thead><tbody><tr><td><code>initiated</code></td><td align="center">Transactional</td><td>Transaction has been initiated and is awaiting customer to complete the payment on checkout page.</td></tr><tr><td><code>pending</code></td><td align="center">Transactional</td><td>Customer started the payment process, but it is not completed yet.</td></tr><tr><td><code>cancelled</code></td><td align="center">Final</td><td>Transaction has been cancelled. This is a final status.</td></tr><tr><td><code>failed</code></td><td align="center">Final</td><td>Transaction has failed. This is a final status.</td></tr><tr><td><code>success</code></td><td align="center">Final</td><td>Transaction has been successfully completed. This is a final status.</td></tr></tbody></table>


# Available methods

Below is a list of payment methods we support. The list is constantly growing, so check back for updates.

To learn more about a specific payment method and what payment gateway supports it, please check your [connection list section](http://moneroo.io/connection).

{% hint style="info" %}
You can get updated list of all available payment methods by calling [GET /utils/payment/methods](https://api.moneroo.io/utils/payment/methods) endpoint.

```
GET /utils/payout/methods HTTP/1.1
Host: https://api.moneroo.io
Accept: application/json
```

{% endhint %}

***

| Name                     | Code                   | Currency | Countries                                                                                                  |
| ------------------------ | ---------------------- | -------- | ---------------------------------------------------------------------------------------------------------- |
| Airtel Congo             | airtel\_cd             | CDF      | CD                                                                                                         |
| Airtel Money Malawi      | airtel\_mw             | MWK      | MW                                                                                                         |
| Airtel Niger             | airtel\_ne             | XOF      | NE                                                                                                         |
| Airtel Money Nigeria     | airtel\_ng             | NGN      | NG                                                                                                         |
| Airtel Rwanda            | airtel\_rw             | RWF      | RW                                                                                                         |
| Airtel Tanzania          | airtel\_tz             | TZS      | TZ                                                                                                         |
| Airtel Uganda            | airtel\_ug             | UGX      | UG                                                                                                         |
| Airtel Zambia            | airtel\_zm             | ZMW      | ZM                                                                                                         |
| Bank Transfer NG         | bank\_transfer\_ng     | NGN      | NG                                                                                                         |
| Barter                   | barter                 | NGN      | NG                                                                                                         |
| Credit Card GHS          | card\_ghs              | GHS      | GH                                                                                                         |
| Card Kenya               | card\_kes              | KES      | KE                                                                                                         |
| Credit Card NGN          | card\_ngn              | NGN      | NG                                                                                                         |
| Card Tanzania            | card\_tzs              | TZS      | TZ                                                                                                         |
| Card Uganda              | card\_ugx              | UGX      | UG                                                                                                         |
| Credit Card USD          | card\_usd              | USD      | World                                                                                                      |
| Credit Card XAF          | card\_xaf              | XAF      | CM, CF, CG, GA, GQ, TD                                                                                     |
| Credit Card XOF          | card\_xof              | XOF      | CI, BF, TG, BJ, ML                                                                                         |
| Credit Card ZAR          | card\_zar              | ZAR      | ZA                                                                                                         |
| Crypto EUR               | crypto\_eur            | EUR      | AT, BE, BG, CY, CZ, DE, DK, EE, ES, FI, FR, GR, HR, HU, IE, IT, LT, LU, LV, MT, NL, PL, PT, RO, SE, SI, SK |
| Crypto GHS               | crypto\_ghs            | GHS      | GH                                                                                                         |
| Crypto NGN               | crypto\_ngn            | NGN      | NG                                                                                                         |
| Crypto USD               | crypto\_usd            | USD      | US                                                                                                         |
| Crypto XAF               | crypto\_xaf            | XAF      | CM, CF, CG, GA, GQ, TD                                                                                     |
| Crypto XOF               | crypto\_xof            | XOF      | BJ, BF, CI, GW, ML, NE, SN, TG                                                                             |
| E-Money Senegal          | e\_money\_sn           | XOF      | SN                                                                                                         |
| EU Mobile Money Cameroon | eu\_mobile\_cm         | XAF      | CM                                                                                                         |
| Free Money Senegal       | freemoney\_sn          | XOF      | SN                                                                                                         |
| Halopesa                 | halopesa\_tz           | TZS      | TZ                                                                                                         |
| Mobi Cash Mali           | mobi\_cash\_ml         | XOF      | ML                                                                                                         |
| Test Payment Method      | moneroo\_payment\_demo | USD      | US                                                                                                         |
| Moov Burkina Faso        | moov\_bf               | XOF      | BF                                                                                                         |
| Moov Money Benin         | moov\_bj               | XOF      | BJ                                                                                                         |
| Moov Money CI            | moov\_ci               | XOF      | CI                                                                                                         |
| Moov Money Mali          | moov\_ml               | XOF      | ML                                                                                                         |
| Moov Money Togo          | moov\_tg               | XOF      | TG                                                                                                         |
| M-Pesa Kenya             | mpesa\_ke              | KES      | KE                                                                                                         |
| Vodacom Tanzania         | mpesa\_tz              | TZS      | TZ                                                                                                         |
| MTN MoMo Benin           | mtn\_bj                | XOF      | BJ                                                                                                         |
| MTN MoMo CI              | mtn\_ci                | XOF      | CI                                                                                                         |
| MTN MoMo Cameroon        | mtn\_cm                | XAF      | CM                                                                                                         |
| MTN MoMo Ghana           | mtn\_gh                | GHS      | GH                                                                                                         |
| MTN MoMo Guinea          | mtn\_gn                | GNF      | GN                                                                                                         |
| MTN Nigeria              | mtn\_ng                | NGN      | NG                                                                                                         |
| MTN MoMo Rwanda          | mtn\_rw                | RWF      | RW                                                                                                         |
| MTN MoMo Uganda          | mtn\_ug                | UGX      | UG                                                                                                         |
| MTN MoMo Zambia          | mtn\_zm                | ZMW      | ZM                                                                                                         |
| Orange Burkina Faso      | orange\_bf             | XOF      | BF                                                                                                         |
| Orange Congo             | orange\_cd             | CDF      | CD                                                                                                         |
| Orange Money CI          | orange\_ci             | XOF      | CI                                                                                                         |
| Orange Money Cameroon    | orange\_cm             | XAF      | CM                                                                                                         |
| Orange Money Guinea      | orange\_gn             | GNF      | GN                                                                                                         |
| Orange Money Mali        | orange\_ml             | XOF      | ML                                                                                                         |
| Orange Money Senegal     | orange\_sn             | XOF      | SN                                                                                                         |
| QR Code Nigeria          | qr\_ngn                | NGN      | NG                                                                                                         |
| Airtel/Tigo Ghana        | tigo\_gh               | GHS      | GH                                                                                                         |
| Tigo Tanzania            | tigo\_tz               | TZS      | TZ                                                                                                         |
| TNM Mpamba Malawi        | tnm\_mw                | MWK      | MW                                                                                                         |
| Togocel Money            | togocel                | XOF      | TG                                                                                                         |
| USSD NGN                 | ussd\_ngn              | NGN      | NG                                                                                                         |
| Vodacom Congo            | vodacom\_cd            | CDF      | CD                                                                                                         |
| Vodafone Ghana           | vodafone\_gh           | GHS      | GH                                                                                                         |
| Wave CI                  | wave\_ci               | XOF      | CI                                                                                                         |
| Wave Senegal             | wave\_sn               | XOF      | SN                                                                                                         |
| Wizall Senegal           | wizall\_sn             | XOF      | SN                                                                                                         |
| Zamtel Kwacha            | zamtel\_zm             | ZMW      | ZM                                                                                                         |
| Mobi Cash Mali           | mobi\_cash\_ml         | XOF      | ML                                                                                                         |
| Test Payment Method      | moneroo\_payment\_demo | USD      | US                                                                                                         |
| Moov Burkina Faso        | moov\_bf               | XOF      | BF                                                                                                         |
| Moov Money Benin         | moov\_bj               | XOF      | BJ                                                                                                         |
| Moov Money CI            | moov\_ci               | XOF      | CI                                                                                                         |
| Moov Money Mali          | moov\_ml               | XOF      | ML                                                                                                         |
| Moov Money Togo          | moov\_tg               | XOF      | TG                                                                                                         |
| M-Pesa Kenya             | mpesa\_ke              | KES      | KE                                                                                                         |
| Vodacom Tanzania         | mpesa\_tz              | TZS      | TZ                                                                                                         |
| MTN MoMo Benin           | mtn\_bj                | XOF      | BJ                                                                                                         |
| MTN MoMo CI              | mtn\_ci                | XOF      | CI                                                                                                         |
| MTN MoMo Cameroon        | mtn\_cm                | XAF      | CM                                                                                                         |
| MTN MoMo Ghana           | mtn\_gh                | GHS      | GH                                                                                                         |
| MTN MoMo Guinea          | mtn\_gn                | GNF      | GN                                                                                                         |
| MTN Nigeria              | mtn\_ng                | NGN      | NG                                                                                                         |
| MTN MoMo Rwanda          | mtn\_rw                | RWF      | RW                                                                                                         |
| MTN MoMo Uganda          | mtn\_ug                | UGX      | UG                                                                                                         |
| MTN MoMo Zambia          | mtn\_zm                | ZMW      | ZM                                                                                                         |
| Orange Burkina Faso      | orange\_bf             | XOF      | BF                                                                                                         |
| Orange Congo             | orange\_cd             | CDF      | CD                                                                                                         |
| Orange Money CI          | orange\_ci             | XOF      | CI                                                                                                         |
| Orange Money Cameroon    | orange\_cm             | XAF      | CM                                                                                                         |
| Orange Money Guinea      | orange\_gn             | GNF      | GN                                                                                                         |
| Orange Money Mali        | orange\_ml             | XOF      | ML                                                                                                         |
| Orange Money Senegal     | orange\_sn             | XOF      | SN                                                                                                         |
| QR Code Nigeria          | qr\_ngn                | NGN      | NG                                                                                                         |
| Airtel/Tigo Ghana        | tigo\_gh               | GHS      | GH                                                                                                         |
| Tigo Tanzania            | tigo\_tz               | TZS      | TZ                                                                                                         |
| TNM Mpamba Malawi        | tnm\_mw                | MWK      | MW                                                                                                         |
| Togocel Money            | togocel                | XOF      | TG                                                                                                         |
| USSD NGN                 | ussd\_ngn              | NGN      | NG                                                                                                         |
| Vodacom Congo            | vodacom\_cd            | CDF      | CD                                                                                                         |
| Vodafone Ghana           | vodafone\_gh           | GHS      | GH                                                                                                         |
| Wave CI                  | wave\_ci               | XOF      | CI                                                                                                         |
| Wave Senegal             | wave\_sn               | XOF      | SN                                                                                                         |
| Wizall Senegal           | wizall\_sn             | XOF      | SN                                                                                                         |
| Zamtel Kwacha            | zamtel\_zm             | ZMW      | ZM                                                                                                         |

We are constantly adding new payment methods. If you don't see your preferred payment method, please [contact us](https://moneroo.io/contact).


# Testing

Testing your integration is a crucial step in ensuring a seamless payment experience with Moneroo. Moneroo offers a dedicated sandbox environment for testing purposes, allowing you to validate your integration before going live. In the sandbox mode, you can simulate real transactions without processing actual payments.

#### Using the Sandbox Environment

To conduct tests in the sandbox environment, you will use specific keys known as "sandbox keys" or "test keys." These keys differ from the production keys and are intended solely for testing purposes. They provide a secure and controlled setting to experiment with and validate your integration.

#### Benefits of Using the Sandbox

By using the sandbox keys and the Moneroo sandbox environment, you can:

* Thoroughly test your integration
* Ensure compatibility with Moneroo systems
* Address any potential issues before deployment to the live production environment.

{% hint style="warning" %}
Sandbox data is automatically deleted after **90 days**. This only affects transactions and customers.
{% endhint %}

### Default Payment Processor: Moneroo Test Payment Gateway

By default, your Moneroo app includes the "Moneroo Test Payment Gateway" as the default payment gateway in the sandbox environment. This gateway allows you to simulate various transaction scenarios, providing insights into how your system responds in each case.

#### Simulating Transaction Scenarios

To thoroughly test your integration, Moneroo provides specific test phone numbers. These numbers enable you to simulate both successful and failed transactions, allowing you to assess how your system manages each scenario. During your testing, use these test phone numbers to mimic real transaction behaviors and observe how your integration responds.

#### Key Features of Test Payment Gateway

* **Flexibility in Testing:** Simulate a wide range of transaction scenarios to ensure your application is robust and reliable.
* **Realistic Response Simulation:** Observe detailed responses from your system as it would handle actual transactions, helping you to fine-tune your integration before going live.

Using these tools, you can ensure that your integration is fully prepared for production deployment, minimizing potential issues for real users.

{% hint style="info" %}

* The test phone numbers are only available for the Moneroo Test Payment Gateway and cannot be used with other payment gateways in the sandbox mode.
* These numbers can be used to simulate their respective scenarios for all payment methods associated with the Moneroo Test Payment Gateway.
  {% endhint %}

<table><thead><tr><th width="185">Phone Number</th><th width="258">Scenario</th><th width="120">Currency</th><th width="100">Country</th></tr></thead><tbody><tr><td>(414)951-8161</td><td><span data-gb-custom-inline data-tag="emoji" data-code="2705">✅</span> Successful transaction</td><td>USD</td><td>US</td></tr><tr><td>(414)951-8162</td><td><span data-gb-custom-inline data-tag="emoji" data-code="231b">⌛</span>Pending transaction</td><td>USD</td><td>US</td></tr><tr><td>(414)951-8163</td><td><span data-gb-custom-inline data-tag="emoji" data-code="274c">❌</span>Failed transaction</td><td>USD</td><td>US</td></tr></tbody></table>

### Testing with Other Payment Gateways in Sandbox Mode

Moneroo offers the ability to integrate with other payment gateways in the `sandbox` mode.

For each payment gateway available in the sandbox mode, you should consult the specific payment gateway's documentation for their test instructions. These instructions will provide you with the necessary information on how to integrate with the payment gateway, use the test keys or credentials, and simulate different transaction scenarios specific to that payment gateway.

Moneroo is continuously working on expanding the availability of supported payment gateways in the sandbox mode. Therefore, be sure to stay updated with the latest announcements and updates from Moneroo regarding new integrations and sandbox testing options. Here is a link to each payment gateway supported in the sandbox mode test instructions to their documentation:

| Payment Processor  | Test Instructions                                                                               |
| ------------------ | ----------------------------------------------------------------------------------------------- |
| KkiaPay (Sandbox)  | [View Instructions](https://docs.kkiapay.me/v1/v/en-1.0.0/compte/kkiapay-sandbox-guide-de-test) |
| Flutterwave (Test) | [View Instructions](https://developer.flutterwave.com/docs/integration-guides/testing-helpers)  |
| Paydunya (Sandbox) | [View Instructions](https://developers.paydunya.com/doc/EN/introduction#section-3)              |
| Paystack (Sandbox) | [View Instructions](https://paystack.com/docs/payments/test-payments/)                          |
| Stripe (Sandbox)   | [View Instructions](https://stripe.com/docs/testing)                                            |
| Fedapay (Sandbox)  | [View Instructions](https://docs.fedapay.com/paiements/test)                                    |
| PawaPay (Sandbox)  | [View Instructions](https://docs.pawapay.co.uk/#section/Testing-the-API)                        |


# Initialize payout

Moneroo's Payout API lets you send money to your customers. You can use it for refunds, rebates, salary payments, and more.

**How It Works**

1. **Send a POST Request**
   * From your server, send a POST request to Moneroo's Payout API with the payment details.
2. **Processing the Request**
   * Moneroo processes the request through the appropriate payment processor based on your chosen payout method.
3. **Receive the Response**
   * Moneroo will return a response with the status of your request.

### Step 1: Collect payout details

First, gather the payment details and format them as a JSON object to send to our API.

Here are the fields that you need to gather:

<table><thead><tr><th width="248">Field Name</th><th width="101" align="center">Type</th><th width="96" align="center">Required</th><th>Description</th></tr></thead><tbody><tr><td><code>amount</code></td><td align="center">integer</td><td align="center">Yes</td><td>The payout amount.</td></tr><tr><td><code>currency</code></td><td align="center">string</td><td align="center">Yes</td><td>The currency of the payment. Currency should be a supported currency in valid <a href="https://en.wikipedia.org/wiki/ISO_4217">ISO 4217</a> format.</td></tr><tr><td><code>description</code></td><td align="center">string</td><td align="center">Yes</td><td>Description of the payment.</td></tr><tr><td><code>method</code></td><td align="center">string</td><td align="center">Yes</td><td>Payout method. Should be a valid supported payout method. Please check the supported payout method list</td></tr><tr><td><code>customer</code></td><td align="center">object</td><td align="center">Yes</td><td>Customer details.</td></tr><tr><td><code>customer.email</code></td><td align="center">string</td><td align="center">Yes</td><td>Customer's email address.</td></tr><tr><td><code>customer.first_name</code></td><td align="center">string</td><td align="center">Yes</td><td>Customer's first name.</td></tr><tr><td><code>customer.last_name</code></td><td align="center">string</td><td align="center">Yes</td><td>Customer's last name.</td></tr><tr><td><code>customer.phone</code></td><td align="center">integer</td><td align="center">No</td><td>Customer's phone number.</td></tr><tr><td><code>customer.address</code></td><td align="center">string</td><td align="center">No</td><td>Customer's address.</td></tr><tr><td><code>customer.city</code></td><td align="center">string</td><td align="center">No</td><td>Customer's city.</td></tr><tr><td><code>customer.state</code></td><td align="center">string</td><td align="center">No</td><td>Customer's state.</td></tr><tr><td><code>customer.country</code></td><td align="center">string</td><td align="center">No</td><td>Customer's country. Should be Should be a code in valid <a href="https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2">ISO 3166-1 alpha-2</a> format.</td></tr><tr><td><code>customer.zip</code></td><td align="center">string</td><td align="center">No</td><td>Customer's zip code.</td></tr><tr><td><code>metadata</code></td><td align="center">array</td><td align="center">No</td><td>Additional data for the payment.</td></tr></tbody></table>

### Step 2: Add required fields for specific payout methods

Each payout method has its [required fields](/payouts/available-methods#required-fields). Please check the supported payout method list to see the required fields for each payout method.  These  required fields should be provided via `recipient` fields\
For example, the `mtn_bj` (MTN Mobile Money Benin) method requires you to provide `msisdn` via the following object:

<pre class="language-json"><code class="lang-json">"recipient" : {
<strong>    "msisdn" : "22951345020" //the MTN Mobile Money Phone number of customer
</strong>} 
</code></pre>

### Step 3: Send the payout request

Next, initiate the payout by calling our API with the collected payout details (don't forget to authorize with your secret key).

#### Example request :

<pre class="language-bash"><code class="lang-bash">POST /v1/payouts/initialize
Host: https://api.moneroo.io
Authorization: Bearer YOUR_SECRET_KEY
Content-Type: application/json
Accept: application/json
{
    "amount": 1000,
    "currency": "XOF",
    "description": "Order refund",
    "customer": {
        "email": "john@example.com",
        "first_name": "John",
        "last_name": "Doe"
    },

    "metadata": {
        "payout_request": "123",
        "customer_id": "123"
    },
    "method": "mtn_bj",
    "recipient" : {
<strong>        "msisdn" : "22951345020"
</strong><strong>    } 
</strong>}
</code></pre>

#### Example response :

```json
{
  "success": true,
  "message": "Payout transaction initialized successfully",
  "data": {
    "id": "5f7b1b2c-1b2c-5f7b-0000-000000000000"
  }
}
```

### Step 3: After the payout request is sent

Once the payout is made (successful or failed), four things will occur:

1. **Webhook Notification**: If you have activated webhooks, we will send you a notification. For more information and examples, check out our guide on webhooks.
2. **Email Notification**: We will email you unless you have disabled this feature.
3. **Server-Side Verification**: You can verify the transaction on the server side by calling our API with the transaction ID.
4. **Failed Payout Notification**: If webhooks are enabled, we'll notify you for each failed payout. This can help you reach out to customers or take other actions. See our webhooks guide for an example.

If you have the webhooks setting enabled on your Moneroo application, we'll send you a notification for each failed payout. This is useful in case you want to later reach out to customers or perform other actions. See our webhooks guide for an example.

### Example

{% hint style="info" %}

* Please do not forget to replace `YOUR_SECRET_KEY` with your actual secret key.
* All following examples should be made in the backend, never expose your secret key to the public.
  {% endhint %}

#### cURL

```bash
curl -X POST https://api.moneroo.io/v1/payouts/initialize \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer YOUR_SECRET_KEY" \
     -H "Accept: application/json" \
     -d '{
    "amount": 1000,
    "currency": "XOF",
    "description": "Order refund",
    "customer": {
        "email": "john@example.com",
        "first_name": "John",
        "last_name": "Doe"
    },

    "metadata": {
        "payout_request": "123",
        "customer_id": "123"
    },
    "method": "mtn_bj",
    "recipient" : {
        "msisdn" : "22951345020"
    } 
}'
```


# Verify payout

After a payout, it's crucial to confirm that the transaction was processed through Moneroo before crediting value to your customer wallet or balance in your application. This precaution ensures the payment received aligns with your expectations.

Here are some key points to verify during the payment confirmation:

1. **Transaction Reference**: Confirm that the transaction reference corresponds with the one you generated.
2. **Transaction Status**: Check the transaction status for accuracy. The status should be "success" for successful payments. To learn more about transaction statuses, see the transaction status section.
3. **Payment Currency**: Verify that the payment's currency matches the expected currency.
4. **Paid Amount**: Ensure the paid amount is equal to or greater than the anticipated amount. If the amount is higher, you can provide the customer with the corresponding value and refund the surplus.

To authenticate a payment, use the "verify transaction" endpoint, specifying the transaction ID in the URL. You can obtain the transaction ID from the `data.id` field in the response after transaction creation, as well as in the webhook payload for any transaction.

### Request

```bash
GET /v1/payouts/{payoutId}/verify HTTP/1.1
Host: https://api.moneroo.io
Authorization: Bearer YOUR_SECRET_KEY
Content-Type: application/json
Accept: application/json
```

#### Parameters

* Endpoint: `/v1/payouts/{payoutId}/verify`
* Method: `GET`

| Name       | Type   | Required | Description                                        |
| ---------- | ------ | -------- | -------------------------------------------------- |
| `payoutId` | String | Yes      | The unique ID of the payout transaction to verify. |

### **Response Structure**

The response from this API endpoint will be in the standard Moneroo API response format. You'll get a response that looks like this:

```json
{
  "message": "Payout transaction fetched successfully",
  "data": {
    // Details of the payout transaction
  }
}
```

**Successful Response:**

Upon successful retrieval, the endpoint returns an HTTP status code of 200 and the details of the payment transaction in the response body.

**Error Responses**:

1. **401 Unauthorized**: This error is returned if you didn't provide a valid authorization token in your request.
2. **404 Not Found**: This error is returned if the provided `payoutId` doesn't correspond to any transaction in the system.
3. **500 Internal Server Error**: This error indicates an unexpected issue on the server while processing your request. It happens rarely.

### Security considerations

This endpoint requires a bearer token for authentication. The bearer token must be included in the `Authorization` header of the request. Ensure the token is kept secure and not shared or exposed inappropriately.

### Request examples

{% hint style="info" %}
Replace *`'paymentId'`* with the actual payment transaction ID and *`'your_token'`* with a valid API key in the code snippets above.
{% endhint %}

{% tabs %}
{% tab title="Curl" %}

```bash
curl --location --request GET 'https://api.moneroo.io/v1/payouts/{payoutId}/verify' \
--header 'Authorization: Bearer YOUR_TOKEN'
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php

$paymentId = 'your_payment_id';
$token = 'your_token';

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://api.moneroo.io/v1/payments/{$paymentId}/verify",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer {$token}"
  ]
]);

$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ($httpCode === 200) {
  // Handle successful response
} else {
  // Handle error response
}

curl_close($curl);
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

paymentId = 'your_payment_id'
token = 'your_token'

headers = {
  'Authorization': f'Bearer {token}'
}

response = requests.get(f'https://api.moneroo.io/v1/payments/{paymentId}/verify', headers=headers)

if response.status_code == 200:
  # Handle successful response
else:
  # Handle error response
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"fmt"
	"net/http"
)

func main() {
	paymentId := "your_payment_id"
	token := "your_token"

	url := fmt.Sprintf("https://api.moneroo.io/v1/payments/%s/verify", paymentId)
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		// Handle error
	}

	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		// Handle error
	}
	defer resp.Body.Close()

	if resp.StatusCode == 200 {
		// Handle successful response
	} else {
		// Handle error response
	}
}
```

{% endtab %}

{% tab title="JavaScript (Node.js)" %}

<pre class="language-javascript"><code class="lang-javascript"><strong>const axios = require("axios");
</strong>
const paymentId = "your_payment_id";
const token = "your_token";

axios
  .get(`https://api.moneroo.io/v1/payments/${paymentId}/verify`, {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  })
  .then((response) => {
    if (response.status === 200) {
      // Handle successful response
    } else {
      // Handle error response
    }
  })
  .catch((error) => {
    // Handle error
  });
</code></pre>

{% endtab %}
{% endtabs %}

You'll get a response that looks like this:

```json
{
    "message": "Payout transaction fetched successfully!",
    "data": {
        "id": "go86j8csuq51",
        "status": "success",
        "amount": 500,
        "currency": {
            "name": "US Dollar",
            "symbol": "$",
            "symbol_first": true,
            "decimals": 2,
            "decimal_mark": ".",
            "thousands_separator": ",",
            "subunit": "Cent",
            "subunit_to_unit": 100,
            "symbol_native": "$",
            "decimal_digits": 2,
            "rounding": 0,
            "code": "USD",
            "name_plural": "US dollars",
            "icon_url": "https://assets.cdn.moneroo.io/currencies/USD.svg"
        },
        "amount_formatted": "$ 500.00",
        "description": "hello",
        "environment": "sandbox",
        "metadata": [],
        "app": {
            "id": "01HHJYSA4VCBVKN4KTYF76J",
            "name": "Smarte",
            "website_url": "https://www.smarthome.com",
            "icon_url": "https://assets.cdn.moneroo.io/samples/business.svg",
            "created_at": "2023-12-14T01:24:17.000000Z",
            "updated_at": "2023-12-14T01:24:17.000000Z",
            "is_enabled": false
        },
        "customer": {
            "id": "fsbh12wot2c3",
            "first_name": "John",
            "last_name": "Doe",
            "email": "john@test.com",
            "phone": null,
            "address": null,
            "city": null,
            "state": null,
            "country_code": null,
            "country": null,
            "zip_code": null,
            "profile_url": "https://eu.ui-avatars.com/api/?name=John+Dow&background=ffcc00&color=fff&size=256&rounded=true&bold=true",
            "created_at": "2023-12-22T01:00:37.000000Z",
            "updated_at": "2024-01-08T13:09:23.000000Z"
        },
        "disburse": {
            "id": "0nj13p3bheje",
            "identifier": "pd_65miz6qf4u9y",
            "failure_message": null,
            "failure_error_code": null,
            "failure_error_type": null,
            "method": {
                "id": "6zyu010zn6wo",
                "name": "Test Payout Method",
                "short_code": "moneroo_payout_demo",
                "icon_url": "https://assets.cdn.moneroo.io/icons/circle/moneroo.svg"
            },
            "gateway": {
                "id": "8heokxp8yyxj",
                "account_name": "Moneroo Test Payout Gateway",
                "name": "Test Payout Gateway (Sandbox)",
                "short_code": "moneroo_payout_test",
                "icon_url": "https://assets.cdn.moneroo.io/icons/circle/moneroo.svg",
                "transaction_id": "b1f26365-3e02-4360-b646-39c2e91adce1",
                "transaction_status": "test_success",
                "transaction_failure_message": "This is a failed test payout, you do not use valid test phone number."
            }
        },
        "failed_at": null,
        "pending_at": "2023-12-26T22:04:49.000000Z",
        "success_at": "2023-12-26T22:04:50.000000Z"
    },
    "errors": null
}
```

The transaction details are contained in the `data` object. For instance:

* The status of the transaction is in `data.status`.
* The details of the customer are in the `data.customer` field.
* The `data.amount` field says how much the customer was charged.
* Some fields will vary depending on the type of transaction or state of the transaction.
* The `data.method` field contains the payment method used by the customer.
* The `data.gateway` field contains the payment gateway used to process the transaction.
* The `data.metadata` field contains any custom metadata you may have provided when creating the transaction.
* The `data.context` field contains the context of the transaction.
* The `data.app` field contains the app details.

<table><thead><tr><th width="268">Field Name</th><th>Description</th></tr></thead><tbody><tr><td><code>id</code></td><td>The public ID of the transaction.</td></tr><tr><td><code>status</code></td><td>The status of the transaction.</td></tr><tr><td><code>is_processed</code></td><td>Indicates whether the transaction is processed.</td></tr><tr><td><code>processed_at</code></td><td>The time when the transaction was processed.</td></tr><tr><td><code>amount</code></td><td>The amount involved in the transaction.</td></tr><tr><td><code>currency</code></td><td>The currency used in the transaction.</td></tr><tr><td><code>amount_formatted</code></td><td>The formatted amount involved in the transaction.</td></tr><tr><td><code>description</code></td><td>The description of the transaction.</td></tr><tr><td><code>return_url</code></td><td>The URL to return to after the transaction.</td></tr><tr><td><code>environment</code></td><td>The environment in which the transaction occurred.</td></tr><tr><td><code>initiated_at</code></td><td>The time when the transaction was initiated.</td></tr><tr><td><code>checkout_url</code></td><td>The URL to checkout the transaction.</td></tr><tr><td><code>app</code></td><td>The app associated with the transaction.</td></tr><tr><td><code>customer</code></td><td>The customer associated with the transaction.</td></tr><tr><td><code>method</code></td><td>The payment method associated with the transaction.</td></tr><tr><td><code>gateway</code></td><td>The payment gateway associated with the transaction.</td></tr><tr><td><code>metadata</code></td><td>The metadata associated with the transaction.</td></tr><tr><td><code>context</code></td><td>The context associated with the transaction.</td></tr></tbody></table>


# Retrieve payout

The Moneroo platform's API offers an endpoint that allows you to fetch the detailed information of a specific payout transaction based on its unique `transaction ID`.

This guide will walk you through the process of retrieving a payout transaction using Moneroo's API.

### Request

```bash
GET /v1/payouts/{payoutId} HTTP/1.1
Host: https://api.moneroo.io
Authorization: Bearer YOUR_SECRET_KEY
Content-Type: application/json
Accept: application/json
```

#### Parameters

* Endpoint: `/v1/payouts/{payoutId}`
* Method: `GET`

<table><thead><tr><th width="200">Name</th><th>Type</th><th>Required</th><th>Description</th></tr></thead><tbody><tr><td><code>payoutId</code></td><td>String</td><td>Yes</td><td>The unique ID of the payout transaction to retrieve.</td></tr></tbody></table>

### **Response Structure**

The response from this API endpoint will be in the standard Moneroo API response format.

You'll get a response that looks like this:

```json
{
  "success": true,
  "message": "Payout transaction fetched successfully",
  "data": {
    // Details of the payout transaction
  }
}
```

**Successful Response:**

Upon successful retrieval, the endpoint returns a HTTP status code of 200, and the details of the payout transaction in the response body.

**Error Responses:**

If there's an issue with your request, the API will return an error response. The type of error response depends on the nature of the issue. Check out our [response format page](/introduction/responses-format) for more information.

### Security Considerations

This endpoint requires an API key for authentication. Include the bearer token in the `Authorization` header of your request. Ensure the token is kept secure and not shared or exposed inappropriately.

### Request example

#### Curl

```bash
curl --location --request GET 'https://api.moneroo.io/v1/payouts/{payoutId}' \
--header 'Authorization: Bearer YOUR_TOKEN'
```

#### PHP

```php
<?php

$payoutId = 'your_payout_public_id';
$token = 'your_token';

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://api.moneroo.io/v1/payouts/{$payoutId}",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer {$token}"
  ]
]);

$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ($httpCode === 200) {
  $responseData = json_decode($response, true);
  // Handle successful response and retrieve the payout transaction details
} else {
  // Handle error response
}

curl_close($curl);
```

#### Python

```python
import requests

payout_public_id = 'your_payout_public_id'
token = 'your_token'

headers = {
  'Authorization': f'Bearer {token}'
}

response = requests.get(f'https://api.moneroo.io/v1/payouts/{payout_public_id}', headers=headers)

if response.status_code == 200:
  data = response.json()
  # Handle successful response and retrieve the payout transaction details
else:
  # Handle error response
```

#### Go

```go
package main

import (
	"fmt"
	"net/http"
	"io/ioutil"
)

func main() {
	payoutPublicID := "your_payout_public_id"
	token := "your_token"

	url := fmt.Sprintf("https://api.moneroo.io/v1/payouts/%s", payoutPublicID)
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		// Handle error
	}

	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		// Handle error
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// Handle error
	}

	if resp.StatusCode == 200 {
		// Handle successful response and retrieve the payout transaction details
	} else {
		// Handle error response
	}
}
```

#### JavaScript (Node.js)

```javascript
const axios = require("axios");

const payoutId = "your_payout_public_id";
const token = "your_token";

axios
  .get(`https://api.moneroo.io/v1/payouts/${payoutId}`, {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  })
  .then((response) => {
    if (response.status === 200) {
      const data = response.data;
      // Handle successful response and retrieve the payout transaction details
    } else {
      // Handle error response
    }
  })
  .catch((error) => {
    // Handle error
  });
```

Please replace `'payoutId'` with the actual payout transaction Id and `'your_token'` with your valid authorization token in the code snippets above.

### Response example

You'll get a response that looks like this:

```json
{
  "message": "Payout transaction fetched successfully",
  "data": {
    "id": "abc123",
    "status": "success",
    "is_processed": true,
    "processed_at": "2023-05-21T12:00:00Z",
    "amount": 100.0,
    "currency": "USD",
    "amount_formatted": "$100.00",
    "description": "Purchase of goods",
    "return_url": "https://example.com/return",
    "environment": "production",
    "initiated_at": "2023-05-21T11:00:00Z",
    "payout_phone_number": "+1234567890",
    "app": {
      "id": "app1",
      "name": "Example App",
      "icon_url": "https://example.com/icon.png"
    },
    "customer": {
      "id": "cust1",
      "first_name": "John",
      "last_name": "Doe",
      "email": "john.doe@example.com",
      "phone": "+1234567890",
      "address": "123 Main St",
      "city": "Springfield",
      "state": "IL",
      "country_code": "US",
      "country": "United States",
      "zip_code": "62701",
      "environment": "production",
      "created_at": "2023-01-01T00:00:00Z",
      "updated_at": "2023-05-21T00:00:00Z"
    },
    "method": {
      "name": "Credit Card",
      "code": "cc",
      "icon_url": "https://example.com/cc.png",
      "environment": "production"
    },
    "gateway": {
      "name": "Stripe",
      "account_name": "Acme Corp",
      "code": "stripe",
      "icon_url": "https://example.com/stripe.png",
      "environment": "production"
    },
    "metadata": {
      "custom_field1": "custom_value1",
      "custom_field2": "custom_value2"
    },
    "context": {
      "ip": "192.0.2.0",
      "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (HTML, like Gecko) Chrome/58.0.3029.110 Safari/537",
      "country": "US",
      "local": "en-US"
    }
  }
}
```

The `data` field will contain the transaction details. The specific structure and content of this field depend on the details of the individual transaction.


# Payout status

When it comes to payouts, keeping track of their progress is crucial. To do this effectively, it's important to understand the different transaction statuses associated with each payout. At Moneroo, we have categorized these statuses into two groups: transitional and final.

Here's a simple view of payout transaction statuses in the image below:

<figure><img src="/files/nkmQHwpywYQhREmbdkjy" alt=""><figcaption><p>Moneroo.io Payout Status</p></figcaption></figure>

To provide a clear overview of the payout transaction statuses, refer to the table below:

| Status      |     State     | Description                                                                                                  |
| ----------- | :-----------: | ------------------------------------------------------------------------------------------------------------ |
| `initiated` | Transactional | The payout transaction has been initiated and is currently in the queue, awaiting processing.                |
| `pending`   | Transactional | The payout transaction has been processed and is now waiting for a final status from the gateway or network. |
| `failed`    |     Final     | The transaction has failed, and this is its final status.                                                    |
| `success`   |     Final     | The transaction has been successfully completed, and this is its final status.                               |

By understanding these different payout transaction statuses, you'll be able to effectively monitor and manage your payouts with ease.


# Available methods

Below is a list of payout methods we support. The list is constantly growing, so check back for updates.

To learn more about a specific payout method and what payout gateway supports it, please check your [connection list section](http://moneroo.io/connection).

{% hint style="info" %}
You can get updated list of all available payout methods by calling [GET /utils/payout/methods](https://api.moneroo.io/utils/payout/methods) endpoint.

{% code overflow="wrap" fullWidth="false" %}

```bash
GET /utils/payout/methods HTTP/1.1
Host: https://api.moneroo.io
Accept: application/json
```

{% endcode %}
{% endhint %}

***

### Payout methods

| Name                     | Code                  | Currency | Countries |
| ------------------------ | --------------------- | -------- | --------- |
| Airtel Congo             | `airtel_cd`           | CDF      | CD        |
| Airtel Money Malawi      | `airtel_mw`           | MWK      | MW        |
| Airtel Money Nigeria     | `airtel_ng`           | NGN      | NG        |
| Airtel Rwanda            | `airtel_rw`           | RWF      | RW        |
| Airtel Tanzania          | `airtel_tz`           | TZS      | TZ        |
| Airtel Uganda            | `airtel_ug`           | UGX      | UG        |
| Airtel Zambia            | `airtel_zm`           | ZMW      | ZM        |
| Djamo CI                 | `djamo_ci`            | XOF      | CI        |
| Djamo SN                 | `djamo_sn`            | XOF      | SN        |
| E-Money Senegal          | `e_money_sn`          | XOF      | SN        |
| EU Mobile Money Cameroon | `eu_mobile_cm`        | XAF      | CM        |
| Free Money Senegal       | `freemoney_sn`        | XOF      | SN        |
| Halopesa                 | `halopesa_tz`         | TZS      | TZ        |
| Test Payout Method       | `moneroo_payout_demo` | USD      | US        |
| Moov Money Benin         | `moov_bj`             | XOF      | BJ        |
| Moov Money CI            | `moov_ci`             | XOF      | CI        |
| Moov Money Togo          | `moov_tg`             | XOF      | TG        |
| M-Pesa Kenya             | `mpesa_ke`            | KES      | KE        |
| Vodacom Tanzania         | `mpesa_tz`            | TZS      | TZ        |
| MTN MoMo Benin           | `mtn_bj`              | XOF      | BJ        |
| MTN MoMo CI              | `mtn_ci`              | XOF      | CI        |
| MTN MoMo Cameroon        | `mtn_cm`              | XAF      | CM        |
| MTN MoMo Ghana           | `mtn_gh`              | GHS      | GH        |
| MTN Nigeria              | `mtn_ng`              | NGN      | NG        |
| MTN MoMo Rwanda          | `mtn_rw`              | RWF      | RW        |
| MTN MoMo Uganda          | `mtn_ug`              | UGX      | UG        |
| MTN MoMo Zambia          | `mtn_zm`              | ZMW      | ZM        |
| Orange Congo             | `orange_cd`           | CDF      | CD        |
| Orange Money CI          | `orange_ci`           | XOF      | CI        |
| Orange Money Cameroon    | `orange_cm`           | XAF      | CM        |
| Orange Money Mali        | `orange_ml`           | XOF      | ML        |
| Orange Money Senegal     | `orange_sn`           | XOF      | SN        |
| Airtel/Tigo Ghana        | `tigo_gh`             | GHS      | GH        |
| Tigo Tanzania            | `tigo_tz`             | TZS      | TZ        |
| TNM Mpamba Malawi        | `tnm_mw`              | MWK      | MW        |
| Togocel Money            | `togocel`             | XOF      | TG        |
| Vodacom Congo            | `vodacom_cd`          | CDF      | CD        |
| Vodafone Ghana           | `vodafone_gh`         | GHS      | GH        |
| Wave CI                  | `wave_ci`             | XOF      | CI        |
| Wave Senegal             | `wave_sn`             | XOF      | SN        |
| Zamtel Kwacha            | `zamtel_zm`           | ZMW      | ZM        |

We are constantly adding new payout methods. If you don't see the payout method you need, please [contact us](https://moneroo.io/contact).

### Required fields

Each payout method has its own set of required fields, y**ou should provide them in the request body when creating a payout**.

<table><thead><tr><th>Code</th><th align="center">Fields</th><th align="center">Type</th><th width="157">Example</th><th>Description</th></tr></thead><tbody><tr><td>airtel_cd</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>243XXXXXXXXX</td><td>Airtel Congo account phone number that will receive money in international format.</td></tr><tr><td>airtel_mw</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>265XXXXXXXXX</td><td>Airtel Money Malawi account phone number that will receive money in international format.</td></tr><tr><td>airtel_ng</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>234XXXXXXXXX</td><td>Airtel Money Nigeria account phone number that will receive money in international format.</td></tr><tr><td>airtel_rw</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>250XXXXXXXXX</td><td>Airtel Rwanda account phone number that will receive money in international format.</td></tr><tr><td>airtel_tz</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>255XXXXXXXXX</td><td>Airtel Tanzania account phone number that will receive money in international format.</td></tr><tr><td>airtel_ug</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>256XXXXXXXXX</td><td>Airtel Uganda account phone number that will receive money in international format.</td></tr><tr><td>airtel_zm</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>260XXXXXXXXX</td><td>Airtel Zambia account phone number that will receive money in international format.</td></tr><tr><td>djamo_ci</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>225XXXXXXXXX</td><td>Djamo CI account phone number that will receive money in international format.</td></tr><tr><td>djamo_sn</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>221XXXXXXXXX</td><td>Djamo SN account phone number that will receive money in international format.</td></tr><tr><td>e_money_sn</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>221XXXXXXXXX</td><td>E-Money Senegal account phone number that will receive money in international format.</td></tr><tr><td>eu_mobile_cm</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>237XXXXXXXXX</td><td>EU Mobile Money Cameroon account phone number that will receive money in international format.</td></tr><tr><td>freemoney_sn</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>221XXXXXXXXX</td><td>Free Money Senegal account phone number that will receive money in international format.</td></tr><tr><td>halopesa_tz</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>255XXXXXXXXX</td><td>Halopesa account phone number that will receive money in international format.</td></tr><tr><td>moneroo_payout_demo</td><td align="center"><code>account_number</code></td><td align="center"><code>integer</code></td><td>1XXXXXXXXX</td><td>Test Payout account phone number that will receive money in international format.</td></tr><tr><td>moov_bj</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>229XXXXXXXXX</td><td>Moov Money Benin account phone number that will receive money in international format.</td></tr><tr><td>moov_ci</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>225XXXXXXXXX</td><td>Moov Money CI account phone number that will receive money in international format.</td></tr><tr><td>moov_tg</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>228XXXXXXXXX</td><td>Moov Money Togo account phone number that will receive money in international format.</td></tr><tr><td>mpesa_ke</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>254XXXXXXXXX</td><td>M-Pesa Kenya account phone number that will receive money in international format.</td></tr><tr><td>mpesa_tz</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>255XXXXXXXXX</td><td>Vodacom Tanzania account phone number that will receive money in international format.</td></tr><tr><td>mtn_bj</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>229XXXXXXXXX</td><td>MTN MoMo Benin account phone number that will receive money in international format.</td></tr><tr><td>mtn_ci</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>225XXXXXXXXX</td><td>MTN MoMo CI account phone number that will receive money in international format.</td></tr><tr><td>mtn_cm</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>237XXXXXXXXX</td><td>MTN MoMo Cameroon account phone number that will receive money in international format.</td></tr><tr><td>mtn_gh</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>233XXXXXXXXX</td><td>MTN MoMo Ghana account phone number that will receive money in international format.</td></tr><tr><td>mtn_ng</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>234XXXXXXXXX</td><td>MTN Nigeria account phone number that will receive money in international format.</td></tr><tr><td>mtn_rw</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>250XXXXXXXXX</td><td>MTN MoMo Rwanda account phone number that will receive money in international format.</td></tr><tr><td>mtn_ug</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>256XXXXXXXXX</td><td>MTN MoMo Uganda account phone number that will receive money in international format.</td></tr><tr><td>mtn_zm</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>260XXXXXXXXX</td><td>MTN MoMo Zambia account phone number that will receive money in international format.</td></tr><tr><td>orange_cd</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>243XXXXXXXXX</td><td>Orange Congo account phone number that will receive money in international format.</td></tr><tr><td>orange_ci</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>225XXXXXXXXX</td><td>Orange Money CI account phone number that will receive money in international format.</td></tr><tr><td>orange_cm</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>237XXXXXXXXX</td><td>Orange Money Cameroon account phone number that will receive money in international format.</td></tr><tr><td>orange_ml</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>223XXXXXXXXX</td><td>Orange Money Mali account phone number that will receive money in international format.</td></tr><tr><td>orange_sn</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>221XXXXXXXXX</td><td>Orange Money Senegal account phone number that will receive money in international format.</td></tr><tr><td>tigo_gh</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>233XXXXXXXXX</td><td>Airtel/Tigo Ghana account phone number that will receive money in international format.</td></tr><tr><td>tigo_tz</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>255XXXXXXXXX</td><td>Tigo Tanzania account phone number that will receive money in international format.</td></tr><tr><td>tnm_mw</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>265XXXXXXXXX</td><td>TNM Mpamba Malawi account phone number that will receive money in international format.</td></tr><tr><td>togocel</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>228XXXXXXXXX</td><td>Togocel Money account phone number that will receive money in international format.</td></tr><tr><td>vodacom_cd</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>243XXXXXXXXX</td><td>Vodacom Congo account phone number that will receive money in international format.</td></tr><tr><td>vodafone_gh</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>233XXXXXXXXX</td><td>Vodafone Ghana account phone number that will receive money in international format.</td></tr><tr><td>wave_ci</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>225XXXXXXXXX</td><td>Wave CI account phone number that will receive money in international format.</td></tr><tr><td>wave_sn</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>221XXXXXXXXX</td><td>Wave Senegal account phone number that will receive money in international format.</td></tr><tr><td>zamtel_zm</td><td align="center"><code>msisdn</code></td><td align="center"><code>integer</code></td><td>260XXXXXXXXX</td><td>Zamtel Kwacha account phone number that will receive money in international format.</td></tr></tbody></table>


# Testing

Testing your integration is a crucial step in ensuring a seamless payout experience with Moneroo. Moneroo provides a dedicated sandbox environment for testing purposes, allowing you to validate your integration before going live. In the sandbox mode, you can simulate real transactions without processing actual payments.

To perform testing in the sandbox environment, you will use specific keys known as "sandbox keys" or "test keys." These keys are distinct from the live keys and are meant for testing purposes only. They provide a secure and controlled environment to experiment and validate your integration.

By utilizing the sandbox keys and the Moneroo sandbox environment, you can thoroughly test your integration, ensure compatibility, and address any issues before deploying to the live production environment.

{% hint style="warning" %}
Sandbox data is automatically deleted after 90 days. This only affects transactions and customers.
{% endhint %}

### **Default Payout Gateway: Moneroo Test Payout Gateway**

By default, your Moneroo app includes the "Moneroo Test Payout Gateway" as the default payout gateway in the sandbox environment. This payout gateway allows you to simulate various transaction scenarios and observe how your system responds in each case.

To simulate different payout transaction scenarios and thoroughly test your integration, Moneroo provides specific test phone numbers. These numbers can be used to simulate both successful and failed transactions, allowing you to evaluate how your system handles each scenario. During your testing process, you can use these test phone numbers to mimic the behavior of real transactions and observe your integration's responses accordingly.

{% hint style="info" %}

* The test phone numbers are only available for the Moneroo Test Payout Gateway and cannot be used with other payout gateways in the sandbox mode.
* These numbers can be used to simulate their respective scenarios for all payment methods associated with the Moneroo Test Payout Gateway.
  {% endhint %}

<table><thead><tr><th>Phone Number</th><th width="244">Scenario</th><th width="125">Currency</th><th>Country</th></tr></thead><tbody><tr><td>4149518161</td><td><span data-gb-custom-inline data-tag="emoji" data-code="2705">✅</span> Successful transaction</td><td>USD</td><td>US</td></tr><tr><td>4149518162</td><td><span data-gb-custom-inline data-tag="emoji" data-code="274c">❌</span> Failed transaction</td><td>USD</td><td>US</td></tr><tr><td>4149518163</td><td><span data-gb-custom-inline data-tag="emoji" data-code="23f3">⏳</span> ending transaction</td><td>USD</td><td>US</td></tr></tbody></table>

### Testing with Other Payout Gateways in Sandbox Mode

Moneroo offers the ability to integrate with other payout gateways in the sandbox mode.

For each payment gateway available in the sandbox mode, consult the specific payment gateway's documentation for their test instructions. These instructions will provide you with the necessary information on how to integrate with the payment gateway, utilize the test keys or credentials, and simulate different transaction scenarios specific to that payment gateway.

Moneroo is continuously working on expanding the availability of supported payment gateways in the sandbox mode. Therefore, be sure to stay updated with the latest announcements and updates from Moneroo regarding new integrations and sandbox testing options.

Here are the links to the documentation for each payment gateway supported in the sandbox mode for test instructions:

<table><thead><tr><th width="364">Payment Processor</th><th>Test Instructions</th></tr></thead><tbody><tr><td>KkiaPay (Sandbox)</td><td><a href="https://docs.kkiapay.me/v1/v/en-1.0.0/compte/kkiapay-sandbox-guide-de-test">View Instructions</a></td></tr><tr><td>Flutterwave (Test)</td><td><a href="https://developer.flutterwave.com/docs/integration-guides/testing-helpers">View Instructions</a></td></tr><tr><td>Paydunya (Sandbox)</td><td><a href="https://developers.paydunya.com/doc/EN/introduction#section-3">View Instructions</a></td></tr><tr><td>Paystack (Sandbox)</td><td><a href="https://paystack.com/docs/payments/test-payments/">View Instructions</a></td></tr><tr><td>Stripe (Sandbox)</td><td><a href="https://stripe.com/docs/testing">View Instructions</a></td></tr><tr><td>Fedapay (Sandbox)</td><td><a href="https://docs.fedapay.com/paiements/test">View Instructions</a></td></tr><tr><td>PawaPay (Sandbox)</td><td><a href="https://docs.pawapay.co.uk/#section/Using-the-API/Correspondents">View Instructions</a></td></tr></tbody></table>


# PHP SDK

[![GitHub](https://img.shields.io/badge/GitHub-100000?style=for-the-badge\&logo=github\&logoColor=white)](https://github.com/MonerooHQ/moneroo-php) [![Star on GitHub](https://img.shields.io/badge/Star-GitHub-blue?style=for-the-badge\&logo=github)](https://github.com/MonerooHQ/moneroo-php/stargazers)\
[![PHP Version](https://img.shields.io/packagist/php-v/moneroo/moneroo-php.svg)](https://packagist.org/packages/moneroo/moneroo-php) [![Build Status](https://github.com/monerooHQ/moneroo-php/actions/workflows/run-tests.yml/badge.svg?branch=main)](https://github.com/moneroo/moneroo-php/actions?query=branch%3Amain) [![Latest Stable Version](https://poser.pugx.org/moneroo/moneroo-php/v/stable.svg)](https://packagist.org/packages/moneroo/moneroo-php) [![Total Downloads](https://poser.pugx.org/moneroo/moneroo-php/downloads.svg)](https://packagist.org/packages/moneroo/moneroo-php) [![License](https://poser.pugx.org/moneroo/moneroo-php/license.svg)](https://packagist.org/packages/moneroo/moneroo-php)

The Moneroo PHP SDK is a comprehensive library that enables PHP developers to interact with the Moneroo Payment Orchestration service.

### Requirements

* PHP 7.4 and later.

### Installation

You can install the package via composer:

```bash
composer require moneroo/moneroo-php
```

### Payment

The `Moneroo\Payment` class provides methods for initialise, verifying, retrieving, and marking payments as processed. You can use it like so:

#### Initialise Payment

To create a payment, you need to pass an array of payment data to the `create` method. The array must contain the following keys:

Here are the required fields in a table format:

<table><thead><tr><th width="241">Field Name</th><th width="108">Type</th><th width="105">Required</th><th>Description</th></tr></thead><tbody><tr><td><code>amount</code></td><td>integer</td><td>Yes</td><td>The payment amount.</td></tr><tr><td><code>currency</code></td><td>string</td><td>Yes</td><td>The currency of the payment.</td></tr><tr><td><code>description</code></td><td>string</td><td>No</td><td>Description of the payment.</td></tr><tr><td><code>return_url</code></td><td>string</td><td>Yes</td><td>Callback URL for payment updates.</td></tr><tr><td><code>customer.email</code></td><td>string</td><td>Yes</td><td>Customer's email address.</td></tr><tr><td><code>customer.first_name</code></td><td>string</td><td>Yes</td><td>Customer's first name.</td></tr><tr><td><code>customer.last_name</code></td><td>string</td><td>Yes</td><td>Customer's last name.</td></tr><tr><td><code>customer.phone</code></td><td>string</td><td>No<strong>¹</strong></td><td>Customer's phone number.</td></tr><tr><td><code>customer.address</code></td><td>string</td><td>No<strong>¹</strong></td><td>Customer's address.</td></tr><tr><td><code>customer.city</code></td><td>string</td><td>No<strong>¹</strong></td><td>Customer's city.</td></tr><tr><td><code>customer.state</code></td><td>string</td><td>No<strong>¹</strong></td><td>Customer's state.</td></tr><tr><td><code>customer.country</code></td><td>string</td><td>No<strong>¹</strong></td><td>Customer's country.</td></tr><tr><td><code>customer.zip</code></td><td>string</td><td>No<strong>¹</strong></td><td>Customer's zip code.</td></tr><tr><td><code>metadata</code></td><td>array</td><td>No<strong>²</strong></td><td>Additional data for the payment.</td></tr><tr><td><code>methods</code></td><td>array</td><td>No<strong>³</strong></td><td>Allowed payment methods.</td></tr></tbody></table>

1. If not provided, the customer can be prompted to enter these details during the payment process based on the selected payment method.
2. There Should be an array of key-value pairs. Only string values are allowed.
3. If not provided, all available payment methods will be allowed. Array should contain only supported payment methods.

**Example Usage**

<pre class="language-php"><code class="lang-php"><strong>$paymentData = [
</strong>    'amount' => 100,
    'currency' => 'USD',
    'customer' => [
        'email' => 'john.doe@example.com',
        'first_name' => 'John',
        'last_name' => 'Doe',
        'phone' => '123456789',
        'address' => '123 Main St',
        'city' => 'Los Angeles',
        'state' => 'CA',
        'country' => 'USA',
        'zip' => '90001',
    ],
    'description' => 'Payment for order #123',
    'return_url' => 'https://yourwebsite.com/thanks',
    'metadata' => [
        'order_id' => '123',
        'customer_id' => '456',
    ],
    'methods' => ['card', 'orange_ci'],
];
$monerooPayment = new \Moneroo\Payment($secretKey);
$payment = $monerooPayment->init($paymentData);

// Redirect the customer to the Checkout URL
header('Location: ' . $payment->checkout_url);

</code></pre>

The `create` method returns an object containing the payment details, including the transaction ID, Checkout URL where yous should redirect the customer to complete the payment. You can use this transaction ID to verify the payment later on.

#### Verify Payment

You can verify a payment by its transaction ID. This is useful when you want to check the status of a payment before processing an order on your end.

```php
$transactionId = 'your-payment-transaction-id';

$monerooPayment = new \Moneroo\Payment($secretKey);
$payment = $monerooPayment->verify($transactionId);
```

#### Retrieve Payment

To get details of a payment, use the `get` method with the transaction ID.

```php
$transactionId = 'your-payment-transaction-id';

$monerooPayment = new \Moneroo\Payment($secretKey);
$payment = $monerooPayment->get($transactionId);
```

#### Mark Payment as Processed

{% hint style="warning" %}
This is currently an experimental feature, please use with caution and report any issues you encounter.
{% endhint %}

This method is useful when you want to mark a payment as processed after you've received a successful callback from the Moneroo API, and you've processed the order on your end. This will also allow you to prevent duplicate orders or store transactions IDs in your database for future reference.

To mark a payment as processed, use the `makeAsProcessed` method with the transaction ID.

Example usage:

```php
$transactionId = 'your-payment-transaction-id';

$monerooPayment = new \Moneroo\Payment($secretKey);
$payment = $monerooPayment->makeAsProcessed($transactionId);
```

### Payout

The `Moneroo\Payout` class provides methods for initialise, verifying, and retrieving payouts.

#### Initialise Payout

To initialise a payout, you need to pass an array of data that meets the specified validation rules. The array must contain the following keys:

Here are the required fields in a table format:

<table><thead><tr><th width="261">Field Name</th><th width="90">Type</th><th width="103">Required</th><th>Description</th></tr></thead><tbody><tr><td><code>amount</code></td><td>integer</td><td>Yes</td><td>The payout amount.</td></tr><tr><td><code>currency</code></td><td>string</td><td>Yes</td><td>The currency of the payout.</td></tr><tr><td><code>description</code></td><td>string</td><td>Yes</td><td>Description of the payout.</td></tr><tr><td><code>customer.email</code></td><td>string</td><td>Yes</td><td>Customer's email address.</td></tr><tr><td><code>customer.first_name</code></td><td>string</td><td>Yes</td><td>Customer's first name.</td></tr><tr><td><code>customer.last_name</code></td><td>string</td><td>Yes</td><td>Customer's last name.</td></tr><tr><td><code>return_url</code></td><td>string</td><td>Yes</td><td>Callback URL for payout updates.</td></tr><tr><td><code>customer.phone</code></td><td>string</td><td>No</td><td>Customer's phone number.</td></tr><tr><td><code>customer.address</code></td><td>string</td><td>No</td><td>Customer's address.</td></tr><tr><td><code>customer.city</code></td><td>string</td><td>No</td><td>Customer's city.</td></tr><tr><td><code>customer.state</code></td><td>string</td><td>No</td><td>Customer's state.</td></tr><tr><td><code>customer.country</code></td><td>string</td><td>No</td><td>Customer's country.</td></tr><tr><td><code>customer.zip</code></td><td>string</td><td>No</td><td>Customer's zip code.</td></tr><tr><td><code>metadata</code></td><td>array</td><td>No</td><td>Additional data for the payout.</td></tr><tr><td><code>method</code></td><td>string</td><td>Yes<strong>¹</strong></td><td>Payout method</td></tr><tr><td><code>request_confirmation</code><strong>²</strong></td><td>bool</td><td>No</td><td>If you want to require confirmation from customer.</td></tr></tbody></table>

{% hint style="info" %}

1. Should be a Moneroo supported [payout methods](/payouts/available-methods)
2. This feature is currently in the experimental phase and is not available to all users/applications. It allows you to request confirmation from a customer before proceeding with payment. Moneroo will send an e-mail to the customer containing a confirmation code. The customer is then directed to a confirmation page where they can check the payment amount and account details. If the information is correct, the customer can enter the confirmation code to approve or reject the payment request. This function is a valuable tool for avoiding incorrect information or fraudulent transactions. If the user does not respond within 15 minutes, the payment request will be automatically cancelled.
   {% endhint %}

In addition to the above information, you need to add payout methods required fields for account details. For example, if the payment method is `mtn_bj`, you should provide `msisdn` fields in `recipient` object.

This is different from user information, it accounts where money will be paid. For more information, please check the [required fields](/payouts/available-methods#required-fields) for each [payout method](/payouts/available-methods).

```php
$payoutData = [
    'amount' => 100,
    'currency' => 'USD',
    'customer' => [
        'email' => 'john.doe@example.com',
        'first_name' => 'John',
        'last_name' => 'Doe',
        // other customer details...
    ],
    'description' => 'Salary payment',
    'method' => 'mtn_bj',
    'recipient => [
        'msisdn' => '22912345678', // required field for mtn_bj payout method
    ],
   'metadata' => [
        'payout_id' => '123',
        'customer_id' => '456',
    ],
];

$monerooPayout = new Moneroo\Payout($secretKey);
$payout = $monerooPayout->init($payoutData);
```

The `create` method returns an object containing the payout details, including the transaction ID, and the payout status. You can use this transaction ID to verify the payout later on.

#### Verify Payout

You can verify a payout by its transaction ID.

```php
$transactionId = 'your-payout-transaction-id';

$monerooPayout = new Moneroo\Payout($secretKey);
$payout = $monerooPayout->verify($transactionId);
```

#### Retrieve Payout

To get details of a payout, use the `get` method with the transaction ID.

```php
$transactionId = 'your-payout-transaction-id';

$payout = new \Moneroo\Payout($secretKey);
$payout = $payout->get($transactionId);
```

### Exception Handling

The SDK comes with a number of custom exceptions to help you manage potential errors that may occur when using the Moneroo API. These exceptions are as follows:

* **InvalidPayloadException**: This exception is thrown when the payload sent to the API does not meet the expected criteria.
* **ForbiddenException**: This exception is thrown when an action is attempted that the authenticated user does not have the necessary permissions for.
* **InvalidResourceException**: This exception is thrown when a request is made to a non-existent or invalid resource.
* **ServerErrorException**: This exception is thrown when there is an error on the server's side.
* **NotAcceptableException**: This exception is thrown when the client request's content characteristics are not acceptable according to the Accept headers sent in the request.
* **ServiceUnavailableException**: This exception is thrown when the service is currently unavailable, perhaps due to maintenance or load issues on the server.
* **UnauthorizedException**: This exception is thrown when the request lacks valid authentication credentials for the target resource.

For each exception, you can access the error message by calling `$exception->getMessage()`, and the error code (if available) by calling `$exception->getCode()`.

### Support

If you have any questions or need help, feel free to [contact us](https://moneroo.io/contact).&#x20;

We are always happy to help you with any questions you may have.

### Security Vulnerabilities

If you discover a security vulnerability within Moneroo PHP SDK, please send an e-mail to Moneroo Security via <security@moneroo.io>.&#x20;

All security vulnerabilities will be promptly addressed.

### License

The Moneroo PHP SDK is open-sourced software licensed under the MIT license.


# Laravel SDK

[![PHP Version](https://img.shields.io/packagist/php-v/moneroo/moneroo-laravel.svg)](https://packagist.org/packages/moneroo/moneroo-laravel) [![Build Status](https://github.com/moneroohq/moneroo-laravel/actions/workflows/run-tests.yml/badge.svg?branch=main)](https://github.com/moneroohq/moneroo-laravel/actions?query=branch%3Amain) [![Latest Stable Version](https://poser.pugx.org/moneroohq/moneroo-laravel/v/stable.svg)](https://packagist.org/packages/moneroo/moneroo-laravel) [![Total Downloads](https://poser.pugx.org/moneroo/moneroo-laravel/downloads.svg)](https://packagist.org/packages/moneroo/moneroo-laravel) [![License](https://poser.pugx.org/moneroo/moneroo-laravel/license.svg)](https://packagist.org/packages/moneroo/moneroo-laravel)

The Moneroo Laravel SDK is a comprehensive library that enables Laravel developers to interact with the Moneroo Payment Orchestration service.

### Requirements

Laravel 9.0 or higher PHP Requirements: PHP 8.1 and later

### Installation

You can install the package via composer:

```bash
composer require moneroo/moneroo-laravel
```

#### Installation Command

The package provides a convenient command to install the Moneroo Laravel SDK and publish its configuration to your Laravel project. After you've installed the package via composer, you can run this command:

```bash
php artisan moneroo:install
```

This command will:

1. Publish a `moneroo.php` file in your config directory
2. Append your `.env` file with the `MONEROO_PUBLIC_KEY` and `MONEROO_SECRET_KEY` variables if they don't already exist.

You will have to replace 'your-public-key' and 'your-secret-key' with your actual Moneroo public key and secret key respectively.

```env
MONEROO_PUBLIC_KEY=your-public-key
MONEROO_SECRET_KEY=your-secret-key
```

Please keep in mind that these are sensitive keys and should not be publicly exposed. Laravel .env file is ignored by Git, which makes it a good place to store sensitive information.

### Payment

The `Moneroo\Payment` class provides methods for initialise, verifying, retrieving, and marking payments as processed. You can use it like so:

#### Initialise Payment

To create a payment, you need to pass an array of payment data to the `create` method. The array must contain the following keys:

Here are the required fields in a table format:

| Field Name            | Type    | Required | Description                       |
| --------------------- | ------- | -------- | --------------------------------- |
| `amount`              | integer | Yes      | The payment amount.               |
| `currency`            | string  | Yes      | The currency of the payment.      |
| `description`         | string  | No       | Description of the payment.       |
| `return_url`          | string  | Yes      | Callback URL for payment updates. |
| `customer.email`      | string  | Yes      | Customer's email address.         |
| `customer.first_name` | string  | Yes      | Customer's first name.            |
| `customer.last_name`  | string  | Yes      | Customer's last name.             |
| `customer.phone`      | string  | No**¹**  | Customer's phone number.          |
| `customer.address`    | string  | No**¹**  | Customer's address.               |
| `customer.city`       | string  | No**¹**  | Customer's city.                  |
| `customer.state`      | string  | No**¹**  | Customer's state.                 |
| `customer.country`    | string  | No**¹**  | Customer's country.               |
| `customer.zip`        | string  | No**¹**  | Customer's zip code.              |
| `metadata`            | array   | No**²**  | Additional data for the payment.  |
| `methods`             | array   | No**³**  | Allowed payment methods.          |

1. If not provided, the customer can be prompted to enter these details during the payment process based on the selected payment method.
2. There Should be an array of key-value pairs. Only string values are allowed.
3. If not provided, all available payment methods will be allowed. Array should contain only supported payment methods.

**Example Usage**

```php
$paymentData = [
    'amount' => 100,
    'currency' => 'USD',
    'customer' => [
        'email' => 'john.doe@example.com',
        'first_name' => 'John',
        'last_name' => 'Doe',
        'phone' => '123456789',
        'address' => '123 Main St',
        'city' => 'Los Angeles',
        'state' => 'CA',
        'country' => 'USA',
        'zip' => '90001',
    ],
    'description' => 'Payment for order #123',
    'return_url' => 'https://yourwebsite.com/thanks',
    'metadata' => [
        'order_id' => '123',
        'customer_id' => '456',
    ],
    'methods' => ['card', 'orange_ci'],
];
$monerooPayment = new Moneroo\Payment();
$payment = $monerooPayment->init($paymentData);

// Redirect the customer to the Checkout URL
header('Location: ' . $payment->checkout_url);

```

The `create` method returns an object containing the payment details, including the transaction ID, Checkout URL where yous should redirect the customer to complete the payment. You can use this transaction ID to verify the payment later on.

#### Verify Payment

You can verify a payment by its transaction ID. This is useful when you want to check the status of a payment before processing an order on your end.

```php
$transactionId = 'your-payment-transaction-id';

$monerooPayment = new Moneroo\Payment();
$payment = $monerooPayment->verify($transactionId);
```

#### Retrieve Payment

To get details of a payment, use the `get` method with the transaction ID.

```php
$transactionId = 'your-payment-transaction-id';

$monerooPayment = new Moneroo\Payment();
$payment = $monerooPayment->get($transactionId);
```

#### Mark Payment as Processed

This is currently an experimental feature, please use with caution and report any issues you encounter.

This method is useful when you want to mark a payment as processed after you've received a successful callback from the Moneroo API, and you've processed the order on your end. This will also allow you to prevent duplicate orders or store transactions IDs in your database for future reference.

To mark a payment as processed, use the `makeAsProcessed` method with the transaction ID.

Example usage:

```php
$transactionId = 'your-payment-transaction-id';

$monerooPayment = new Moneroo\Payment();
$payment = $monerooPayment->makeAsProcessed($transactionId);
```

### Payout

The `MonerooPayout` class extends the main `Moneroo` class and provides methods for creating, verifying, and retrieving payouts.

#### Create Payout

To create a payout, you need to pass an array of data that meets the specified validation rules. The array must contain the following keys:

Here are the required fields in a table format:

| Field Name                  | Type    | Required | Description                                        |
| --------------------------- | ------- | -------- | -------------------------------------------------- |
| `amount`                    | integer | Yes      | The payout amount.                                 |
| `currency`                  | string  | Yes      | The currency of the payout.                        |
| `description`               | string  | Yes      | Description of the payout.                         |
| `customer.email`            | string  | Yes      | Customer's email address.                          |
| `customer.first_name`       | string  | Yes      | Customer's first name.                             |
| `customer.last_name`        | string  | Yes      | Customer's last name.                              |
| `return_url`                | string  | Yes      | Callback URL for payout updates.                   |
| `customer.phone`            | string  | No       | Customer's phone number.                           |
| `customer.address`          | string  | No       | Customer's address.                                |
| `customer.city`             | string  | No       | Customer's city.                                   |
| `customer.state`            | string  | No       | Customer's state.                                  |
| `customer.country`          | string  | No       | Customer's country.                                |
| `customer.zip`              | string  | No       | Customer's zip code.                               |
| `metadata`                  | array   | No       | Additional data for the payout.                    |
| `method`                    | string  | Yes**¹** | Payout method                                      |
| `request_confirmation`**²** | bool    | No       | If you want to require confirmation from customer. |

1. Should be a Moneroo supported payout methods
2. This feature is currently in the experimental phase and is not available to all users/applications. It allows you to request confirmation from a customer before proceeding with payment. Moneroo will send an e-mail to the customer containing a confirmation code. The customer is then directed to a confirmation page where they can check the payment amount and account details. If the information is correct, the customer can enter the confirmation code to approve or reject the payment request. This function is a valuable tool for avoiding incorrect information or fraudulent transactions. If the user does not respond within 15 minutes, the payment request will be automatically cancelled.

In addition to the above information, you need to add payout methods required fields for account details. For example, if the payment method is `mtn_bj`, you should provide `phone` fields.

This is different from user information, it accounts where money will be paid. For more information, please check the required fields for each payout method.

```php
$payoutData = [
    'amount' => 100,
    'currency' => 'USD',
    'customer' => [
        'email' => 'john.doe@example.com',
        'first_name' => 'John',
        'last_name' => 'Doe',
        // other customer details...
    ],
    'description' => 'Payout for order #123',
    'method' => 'bank_transfer',
    // other data...
];

$monerooPayout = new Moneroo\Payout();
$payout = Moneroo\Payout::init($payoutData);
```

The `create` method returns an object containing the payout details, including the transaction ID, and the payout status. You can use this transaction ID to verify the payout later on.

#### Verify Payout

You can verify a payout by its transaction ID.

```php
$transactionId = 'your-payout-transaction-id';

$payout = Moneroo\Payout::verify($transactionId);
```

#### Retrieve Payout

To get details of a payout, use the `get` method with the transaction ID.

```php
$transactionId = 'your-payout-transaction-id';

$payout = Moneroo\Payout::get($transactionId);
```

Example usage:

```php
$payout = new Moneroo\Payout();
$response = $payout->get('your-payout-transaction-id');
```

### Exception Handling

The SDK comes with a number of custom exceptions to help you manage potential errors that may occur when using the Moneroo API. These exceptions are as follows:

* **InvalidPayloadException**: This exception is thrown when the payload sent to the API does not meet the expected criteria.
* **ForbiddenException**: This exception is thrown when an action is attempted that the authenticated user does not have the necessary permissions for.
* **InvalidResourceException**: This exception is thrown when a request is made to a non-existent or invalid resource.
* **ServerErrorException**: This exception is thrown when there is an error on the server's side.
* **NotAcceptableException**: This exception is thrown when the client request's content characteristics are not acceptable according to the Accept headers sent in the request.
* **ServiceUnavailableException**: This exception is thrown when the service is currently unavailable, perhaps due to maintenance or load issues on the server.
* **UnauthorizedException**: This exception is thrown when the request lacks valid authentication credentials for the target resource.

For each exception, you can access the error message by calling `$exception->getMessage()`, and the error code (if available) by calling `$exception->getCode()`.

### Support

If you have any questions or need help, feel free to [contact us](https://moneroo.io/contact). We are always happy to help you with any questions you may have.

### Security Vulnerabilities

If you discover a security vulnerability within Moneroo Laravel SDK, please send an e-mail to Moneroo Security via <security@moneroo.io>. All security vulnerabilities will be promptly addressed.

### License

The Moneroo Laravel SDK is open-sourced software licensed under the MIT license.


# WooCommerce

### Overview

Moneroo is a versatile payment orchestration platform designed to streamline online transactions by providing a single integration point for multiple payment providers. The Moneroo WooCommerce plugin brings this flexibility and convenience to your WordPress eCommerce store, enabling you to accept a variety of payment methods with ease. This guide walks you through the steps to install and configure the Moneroo plugin for your **WooCommerce** store.

### Prerequisites

* A WordPress website with WooCommerce installed and activated
* Admin access to the WordPress dashboard
* Moneroo Plugin ZIP file or access via the WordPress Plugin Repository

### Installation Steps

#### Installing via WordPress Plugin Repository

{% hint style="info" %}
[Watch this video](https://www.youtube.com/watch?v=9QZ1f5XVj4M) to learn how to install the Moneroo plugin for WooCommerce via the WordPress Plugin Repository
{% endhint %}

1. Log in to WordPress Dashboard: Navigate to your WordPress Admin Dashboard.
2. Navigate to Plugins: Click on Plugins > Add New.&#x20;
3. Search for Moneroo: Use the search bar to find "Moneroo".&#x20;
4. Install and Activate: Click Install Now next to Moneroo, and then click Activate.&#x20;

### Configuration

{% hint style="info" %}
[Watch this video](https://www.youtube.com/watch?v=9QZ1f5XVj4M) to learn how to configure the Moneroo plugin for WooCommerce.
{% endhint %}

#### Enable Moneroo

* Navigate to **WooCommerce** > **Settings**
* Click on the Payments tab.&#x20;

<figure><img src="/files/XyeCyy5Vg9jRIbq0h9Un" alt=""><figcaption></figcaption></figure>

* Find "Moneroo" and click Manage or Set Up. Enable by checking the "Enable Moneroo" box and click "Save changes".&#x20;

<figure><img src="/files/iUVjbVdKlUgoWjSsUmAl" alt=""><figcaption></figcaption></figure>

#### Setup API Credentials

1. Go to [Moneroo Dashboard](https://app.moneroo.io) > **Developers** > **API Keys** section and create a new API key.
2. Create a "Secret key", and input them into the corresponding fields.
3. You can name the API key anything you like (e.g. "My WooCommerce Store Secret Key").   &#x20;

#### Setup Webhook

Moneroo uses webhooks to notify your store when a payment is successful or fails. This is very useful for updating the order status in your store when customers are not redirected to your store after payment, as is the case with some payment methods.

1. In Moneroo settings pages in your store, we already provide a **webhook URL** and a **secret key** for you to use.
2. Copy the webhook URL and webhook secret key, and go to **Moneroo Dashboard** > **Developers** > **Webhooks** section.
3. Click on **Add webhook** and fill in the form with the following details:

* **URL**: The URL of the webhook.
* **Secret**: The secret key used to sign the webhook payload.&#x20;

#### Save configurations

Click on **Save Changes** to save the configurations.&#x20;

**Test Payment**

Test the payment by placing an order on your store and completing the payment. Done! You have successfully installed and configured the Moneroo plugin for your WooCommerce store.

### Others settings

Moneroo plugin for WooCommerce has some other settings that you can configure to suit your needs.

* **Title**: The title of the payment method displayed to customers during checkout.
* **Description**: The description of the payment method displayed to customers during checkout.
* The **Title** and **Description** fields are optional. If you leave them blank, the default values will be used.
* Do not forget to click **Save Changes** after making any changes to the settings.

### Support

If you have any questions or need help, feel free to [contact us](https://moneroo.io/contact). We are always happy to help you with any questions you may have.


# Bienvenue

Bienvenue dans la documentation de l'API Moneroo.

Moneroo permet aux entreprises d'accéder instantanément à de multiples passerelles de paiement en Afrique et dans le monde avec une seule intégration. Grâce à Moneroo, les entreprises peuvent offrir à leurs clients diverses options de paiement sans devoir intégrer manuellement chaque passerelle.

Cette documentation offre une vue d'ensemble détaillée de la plateforme Moneroo et sert de guide pour son intégration et son utilisation.

La documentation est structurée pour vous présenter d'abord les concepts fondamentaux, puis pour approfondir les spécificités de l'intégration, les différents cas d'utilisation et les solutions de dépannage. Bienvenue dans le monde des transactions financières avec Moneroo, où la gestion des paiements entrants et sortants se fait sans effort, vous permettant de vous concentrer sur votre cœur de métier.

### Aide et Assistance

Moneroo est conçu pour faciliter l'interaction avec les utilisateurs, mais nous comprenons que des questions et des difficultés puissent survenir.&#x20;

Voici comment vous pouvez accéder à notre support :

#### - Assistance

Pour tout problème lié à l'intégration de Moneroo, contactez notre équipe d'assistance par e-mail, chat ou téléphone. Nous pouvons vous aider pour les problèmes de transaction, les appels API ou la compréhension des fonctionnalités.

#### - Forums communautaires

Notre [communauté Slack](https://moneroo.io/slack) est une ressource précieuse, composée de développeurs expérimentés et novices ainsi que de membres de l'équipe Moneroo prêts à vous aider. Consultez nos forums pour trouver des réponses existantes avant de contacter l'équipe d'assistance.

Rejoindre la communauté Slack vous permet :

* Poser des questions et obtenir de l'aide
* Partagez vos expériences,
* Apprendre des membres de la communauté,
* Recevoir des mises à jour et des annonces,
* Fournir un retour d'information utile.

Rejoignez-nous en suivant ce [lien d'invitation Slack](https://moneroo.io/slack). Merci de faire preuve de respect, de patience et d'esprit constructif au sein de la communauté.

#### Retour d'information

Vos retours sont précieux pour l'amélioration de Moneroo. Nous encourageons les suggestions de nouvelles fonctionnalités, d'améliorations ou de modifications de la documentation. Vous pouvez nous faire part de vos retours via le formulaire de votre tableau de bord ou le lien "feedback" de cette documentation.

<table data-card-size="large" data-view="cards"><thead><tr><th></th><th></th><th data-hidden data-card-cover data-type="files"></th></tr></thead><tbody><tr><td><strong>Rejoignez notre communauté Slack</strong></td><td>Interagissez avec d'autres développeurs, bénéficiez d'une assistance en temps réel et partagez vos expériences.</td><td><a href="/files/jGNHL13Vj58aorGkpCbl">/files/jGNHL13Vj58aorGkpCbl</a></td></tr><tr><td><strong>Fournir un Retour</strong></td><td>Votre avis nous intéresse. Faites-nous part de vos suggestions et de vos idées pour nous aider à nous améliorer.</td><td><a href="/files/34MeupO4HwoxPX32Honv">/files/34MeupO4HwoxPX32Honv</a></td></tr><tr><td><strong>Contacter l'Assistance</strong></td><td>Contactez notre équipe d'assistance pour obtenir de l'aide pour votre intégration.</td><td><a href="/files/IgYkTTnNTgZ1Knsvevbc">/files/IgYkTTnNTgZ1Knsvevbc</a></td></tr><tr><td><strong>Signaler un bug</strong></td><td>Vous avez trouvé un bug ? Faites-le nous savoir afin que nous puissions le corriger le plus rapidement possible.</td><td><a href="/files/EJOBy7ZgfNSf2VOCHSnu">/files/EJOBy7ZgfNSf2VOCHSnu</a></td></tr></tbody></table>


# Authentication

Les endpoints de l'API de Moneroo sont sécurisés par des clés d'API, que vous pouvez créer à partir du tableau de bord. Vous devez inclure votre **clé d'API** dans toutes les requêtes d'API adressées au serveur en tant que champ d'en-tête.

Pour interagir avec l'API de Moneroo, vous devez ajouter un en-tête d'autorisation (`Authorization header`) incluant votre **clé secrète**. Vous pouvez gérer vos clés d'API depuis le tableau de bord.

En général, nous fournissons des **clés publiques** et **clés secrètes**. Les clés publiques sont destinées à être utilisées à partir de votre interface lors de l'intégration à l'aide des SDK JavaScript et dans nos SDK mobiles uniquement. De par leur conception, les clés publiques ne peuvent modifier aucune partie de votre compte, sauf pour initier des transactions vers vous. Les clés secrètes, en revanche, doivent rester **secrètes**. Si, pour une raison quelconque, vous pensez que votre clé secrète a été compromise ou si vous souhaitez la réinitialiser, vous pouvez le faire à partir du tableau de bord.

Pour créer des clés d'API, rendez-vous dans la section développeur de votre application Moneroo.

<figure><img src="/files/95a6okaGqvpqXpA9bUUA" alt=""><figcaption></figcaption></figure>

{% hint style="danger" %}
Ne "commitez" pas vos clés secrètes sur git, et ne les utilisez pas dans du code côté client.
{% endhint %}

Lorsque vous construisez et testez votre intégration, vous devez utiliser les **clés API Sandbox**. Pour en savoir plus sur le mode Sandbox, consultez notre guide sur les tests de l'API Moneroo. Une fois que vous êtes prêt à traiter des paiements réels, remplacez votre **clé de test** par des **clés d'API en direct**.

Il est très important de **sécuriser toutes les clés d'API**. Ne les partagez jamais. Toutefois, si une clé fuite, vous pouvez toujours la supprimer. N'oubliez pas d'appliquer les nouvelles clés à votre code. Tant que vous ne l'aurez pas fait, votre intégration ne fonctionnera pas.

### Authentication d'une requête API

La **clé ou le jeton d'API** doit être envoyé avec chaque demande d'API, en le fournissant dans l'en-tête `Authorization` de l'appel HTTP à l'aide de la méthode Bearer.

Par exemple, un en-tête Authorization valide est :&#x20;

```
Authorization: Bearer test_dHar4XY7LxsDOtmarVtjNVWXLSlXsM
```

En général, nos SDK fournissent des raccourcis permettant de définir facilement la clé API ou le jeton d'accès.

Dans l'exemple ci-dessous, nous utilisons une **clé API de test** pour la méthode GET de la ressource de paiement. Cette méthode permet de récupérer un paiement, dans ce cas, le paiement avec l'ID `test_yyfbwekjnsd`.

```http
GET /payments/test_yyfbwekjnsd HTTP/1.1
Host: api.moneroo.com
Authorization: Bearer test_dHar4XY7LxsDOtmarVtjNVWXLSlXsM
```

```bash
curl https://api.moneroo.io/v1/payments/test_yyfbwekjnsd
-H "Authorization: Bearer YOUR_SECRET_KEY"
-X GET
```

{% hint style="warning" %}
Ne mettez pas `VERIFY_PEER` à `FALSE`. Assurez-vous que votre serveur vérifie la connexion SSL à Moneroo.
{% endhint %}

### Limites de nombre de requêtes

L'API Moneroo a une limite de **120 requêtes par minute**. Si vous dépassez cette limite, vous obtiendrez une réponse **429 Too Many Requests**. Si vous obtenez cette réponse, attendez une minute avant de réessayer votre requête.


# Format des réponses

Lorsque vous interagissez avec les API de Moneroo, il est essentiel de comprendre le format des réponses que vous recevrez. Cela vous aidera à interpréter correctement les réponses et à les traiter de manière appropriée dans votre application.

***

### Structure d'une réponse

Les réponses de l'API Moneroo sont renvoyées au format JSON et suivent une structure cohérente.

Voici un exemple de réponse typique :

```json
{
  "success": true,
  "message": "Transaction initialized successfully.",
  "data": {}
}
```

Chaque partie de cette réponse contient des informations spécifiques :

* **status**\
  Il s'agit d'un champ indiquant si l'appel à l'API a abouti. Si la valeur est "success", cela signifie que l'opération a réussi. Si la valeur est "error", cela signifie qu'il y a eu une erreur.
* **message**\
  Il s’agit d’un champ de texte fournissant un message lisible par l’humain concernant le résultat de l’opération. Si le champ `status` est "success", ce message donne généralement une confirmation de ce qui a été accompli. Si `status` est "error", ce message fournit généralement des informations sur ce qui n’a pas fonctionné.
* **data**\
  Il s'agit d'un objet qui contient toutes les données renvoyées par l'opération. La structure exacte de cet objet dépend du point de terminaison spécifique de l'API avec lequel vous interagissez et des informations qu'il est censé renvoyer. Par exemple, une requête liée à un paiement peut renvoyer des informations sur le paiement dans ce champ. S'il n'y a pas de données à renvoyer, ce champ sera un objet vide `{}`.

Veuillez vous référer à la documentation spécifique à chaque endpoint de l'API pour comprendre la structure et le contenu du champ de données pour chaque point de terminaison.

La compréhension de ce format de réponse est essentielle pour tirer le meilleur parti des API de Moneroo, car elle vous permettra de gérer les opérations réussies et les erreurs d'une manière robuste et conviviale.


# Erreurs

L'API Moneroo est RESTful et, en tant que telle, utilise les codes de réponse HTTP conventionnels pour indiquer le succès ou l'échec des requêtes. Cette section décrit le résumé de ces codes et ce qu'ils signifient dans notre contexte.

**Résumé :**

* **Codes de la série 2XX :** Signifient que la requête d'API a été traitée avec succès.
* **Codes de la série 4XX :** Signifient que quelque chose n'allait pas avec les données que vous avez envoyées. Par exemple, il se peut que vous ayez omis certains paramètres/en-têtes requis ou que vous ayez utilisé les mauvaises informations d'identification de l'API.
* **Codes de la série 5XX :** Indiquent une erreur de traitement de notre part.

### Codes HTTP

<table><thead><tr><th width="104">Code</th><th>Description</th></tr></thead><tbody><tr><td><strong>200</strong></td><td>OK - La requête a été acceptée</td></tr><tr><td><strong>201</strong></td><td>Créé - La demande a abouti et une ressource a été créée en conséquence.</td></tr><tr><td><strong>202</strong></td><td>Accepté - La requête a été acceptée et a fait l'objet d'un accusé de réception. Nous allons maintenant traiter la requête et vous informer de l'état d'avancement.</td></tr><tr><td><strong>400</strong></td><td>Mauvaise demande - Requête malformée ou paramètres requis manquants</td></tr><tr><td><strong>401</strong></td><td>Non autorisé - En-têtes obligatoires manquants, mauvaise clé publique ou secrète, etc.</td></tr><tr><td><strong>403</strong></td><td>Interdit - Vous essayez d'accéder à une ressource pour laquelle vous ne disposez pas des droits d'accès appropriés.</td></tr><tr><td><strong>404</strong></td><td>Non trouvé - Vous essayez d'accéder à une ressource qui n'existe pas.</td></tr><tr><td><strong>422</strong></td><td>Entité non traitable - Vous avez fourni tous les paramètres requis, mais ils ne correspondent pas à la demande.</td></tr><tr><td><strong>429</strong></td><td>Trop de requêtes - Vous avez dépassé le nombre de requêtes autorisées dans un délai donné.</td></tr><tr><td><strong>500</strong></td><td>Erreur de serveur interne - Nous avons eu un problème sur nos serveurs. Réessayez la requête dans quelques instants ou <a href="htpps://moneroo.io/contact">contactez l'assistance</a>. Cela arrive rarement.</td></tr><tr><td><strong>503</strong></td><td>Service indisponible - Nous sommes temporairement hors ligne pour maintenance. Veuillez réessayer plus tard.</td></tr></tbody></table>


# Test

Durant le processus de développement de votre intégration, il est important de la tester correctement. Comme expliqué brièvement dans notre guide d'authentification, vous pouvez accéder au **mode sandbox** de l'API Moneroo en utilisant les **clés API sandbox**.

***

### Test de l'API Moneroo

Tous les paiements ou autres ressources que vous créez en mode sandbox sont complètement isolés de vos données réelles. Pour passer du mode sandbox au mode réel, il vous suffit de changer votre **clé API**.

{% hint style="info" %}
Les transactions en sandbox sont automatiquement supprimées après **90 jours**.
{% endhint %}

### Écran de paiement en mode test

Lorsque vous effectuez un paiement en mode sandbox, un **badge rouge** est présent en haut de la page pour indiquer que vous êtes en mode sandbox.

Il se présente comme suit :

<figure><img src="/files/p8VNpAc2fu4nVWkGCr4d" alt=""><figcaption><p>Moneroo.io Sandbox mode</p></figcaption></figure>


# Webhooks

Les **Webhooks** sont conçus pour communiquer des mises à jour d'état en temps réel, telles que des notifications de paiement réussi. Il s'agit essentiellement d'URL que Moneroo appelle pour fournir l'ID d'un objet mis à jour. Dès réception de l'appel, vous devez récupérer le dernier statut et le traiter s'il y a eu des changements.

***

### Introduction

Moneroo peut envoyer des **Webhooks** pour alerter votre application chaque fois qu'un événement se produit sur votre compte. Ceci est particulièrement utile pour les événements tels que les transactions échouées ou réussies. Ce mécanisme est également utile pour les services qui ne sont pas directement responsables de la création d'une requête d'API, mais qui ont besoin de la réponse à cette requête. Vous pouvez spécifier les URLs du Webhook où vous souhaitez être notifié.

Lorsqu'un événement se produit, Moneroo vous envoie un objet contenant tous les détails de l'événement via une requête HTTP POST aux URLs définies.

<figure><img src="/files/RbIz8aHoHEPnLsrjSCEM" alt=""><figcaption><p>Moneroo.io Webhook</p></figcaption></figure>

### Types d'événements

Voici les événements que nous déclenchons actuellement.&#x20;

D'autres seront ajoutés au fur et à mesure que nous étendrons nos actions à l'avenir.

#### Événements de paiement

| Type d'événement    | Description                                          |
| ------------------- | ---------------------------------------------------- |
| `payment.initiated` | Déclenché lorsqu'un nouveau paiement est initié.     |
| `payment.success`   | Déclenché lorsqu'un paiement se termine avec succès. |
| `payment.failed`    | Déclenché lorsqu'un paiement échoue.                 |
| `payment.cancelled` | Déclenché lorsqu'un paiement est annulé.             |

#### Événements de transfert

| Type d'événement   | Description                                           |
| ------------------ | ----------------------------------------------------- |
| `payout.initiated` | Déclenché lorsqu'un transfert est initié.             |
| `payout.success`   | Déclenché lorsqu'un transfert se termine avec succès. |
| `payout.failed`    | Déclenché lorsqu'un transfert échoue.                 |

Vous pouvez utiliser ces types d'événements dans votre application pour déclencher des actions spécifiques lorsque Moneroo émet ces événements.

### Structure du Webhook

Tous les contenus des Webhooks suivent une structure de base cohérente, comprenant deux éléments principaux :

* **Event** : Le type d'événement qui s'est produit.
* **Data** : Les données associées à l'événement. Le contenu de cet objet varie en fonction de l'événement, mais il contient généralement les détails de l'événement, y compris :
  * un **id** contenant l'ID de la transaction.
  * un **status**, décrivant l'état du paiement de la transaction, le paiement ou les détails du client, le cas échéant.

**Exemple**

{% hint style="info" %}
Nous ne fournissons pas d'informations complètes par le biais du Webhook, vous devrez donc récupérer le dernier statut de l'objet par une requête pour retrouver un paiement/payout.
{% endhint %}

```json
{
  "event": "payment.success",
  "data": {
    "id": "123456",
    "amount": 100,
    "currency": "USD",
    "status": "success",
    "customer": {
      "id": "123456",
      "email": "hello@example.com",
      "firstName": "John",
      "lastName": "Doe",
      "phone": "+1 555 555 5555"
    }
  }
}
```

### Configuration

Pour configurer les **Webhooks**, naviguez dans le tableau de bord de votre application, accédez à la section **Développeurs** et cliquez sur l'onglet **Webhooks**.

Vous pouvez ajouter un nouveau Webhook en cliquant sur le bouton **Ajouter un Webhook** et en remplissant le formulaire avec les détails suivants :

* **URL** : L'URL du Webhook.
* **Secret** : La clé secrète utilisée pour signer la charge utile du Webhook.

{% hint style="info" %}

* La clé secrète est utilisée pour signer le Webhook, ce qui vous permet de vérifier que le Webhook provient réellement de Moneroo.
* Vous pouvez ajouter un maximum de <mark style="color:red;">**15 Webhooks**</mark> par application.
  {% endhint %}

Vous pouvez également **activer**, **désactiver** ou **supprimer** un Webhook existant en cliquant sur les boutons correspondants.

Le Webhook est envoyé sous la forme d'une requête POST à l'URL que vous avez spécifiée. Le corps de la requête contient du JSON et des informations sur l'événement qui s'est produit. Assurez-vous que votre point d'accès peut accepter les requêtes POST et analyser les données utiles JSON.

### Réception d'un Webhook

Lorsque Moneroo envoie un Webhook à votre URL, il inclut un corps en format JSON détaillant l'événement.&#x20;

Par exemple, voici un corps de réponse pour l'événement `payment.success`⁣ :

```json
{
  "event": "payment.success",
  "data": {
    "id": "123456",
    "amount": 100,
    "currency": "USD",
    "status": "success"
  }
}
```

Vous pouvez utiliser le champ `event` dans le contenu de la requête pour déterminer l'action que votre application doit entreprendre.

Pour accuser réception d'un Webhook, votre point d'accès doit renvoyer un code d'état HTTP **200**. Tout autre code de réponse, y compris les codes **3xx**, sera considéré comme un échec. Nous ne tenons pas compte du corps de la réponse ni des en-têtes.

Si votre point d'accès ne renvoie pas un code d'état HTTP **200** ou ne répond pas dans les **3 secondes**, nous réessayerons le Webhook jusqu'à **3 fois** avec un délai de **10 minutes** entre chaque tentative.Les frameworks web tels que Rails, Laravel ou Django vérifient généralement que chaque requête POST contient un jeton CSRF.&#x20;

{% hint style="danger" %}
Bien qu'il s'agisse d'une fonctionnalité de sécurité utile contre la falsification des requêtes intersites, vous devrez exempter le point de terminaison du Webhook de la protection CSRF pour garantir le fonctionnement du Webhook.
{% endhint %}

### Vérification d'un Webhook

Lorsque vous recevez un Webhook, vous devez en vérifier l'origine. Chaque demande de Webhook comprend un en-tête `X-Moneroo-Signature`. La valeur de cet en-tête est une signature générée à l'aide du **secret de signature** de votre Webhook et du corps du Webhook.

Pour vérifier la signature, vous devez calculer la signature de votre côté et la comparer à la valeur de l'en-tête `X-Moneroo-Signature`.

La signature est calculée en utilisant **HMAC-SHA256** avec le secret de signature du Webhook comme clé et le corps comme valeur.

Si la signature est valide, la réponse doit être un code d'état **200 OK**. Si elle n'est pas valide, la réponse doit être **403 Forbidden**.

### Exemples

{% hint style="info" %}
Veuillez remplacer `'your_webhook_signing_secret'`, `'your_payload'` et `'header_value'` par vos valeurs réelles. Pour les exemples en Node.js, Java et Go, vous devez obtenir le corps de la requête et la valeur de l'en-tête à partir de votre objet de requête HTTP.
{% endhint %}

{% tabs %}
{% tab title="PHP" %}

```php
<?php
$secret = 'your_webhook_signing_secret';
$payload = file_get_contents('php://input');
$signature = hash_hmac('sha256', $payload, $secret);

if (hash_equals($signature, $_SERVER['HTTP_X_MONEROO_SIGNATURE'])) {
    http_response_code(200);
} else {
    http_response_code(403);
}
?>
```

{% endtab %}

{% tab title="JavaScript (Node.js)" %}

```javascript
const crypto = require("crypto");
const secret = "your_webhook_signing_secret";
const payload = req.body;
const signature = crypto
  .createHmac("sha256", secret)
  .update(JSON.stringify(payload))
  .digest("hex");

if (signature === req.headers["x-moneroo-signature"]) {
  res.sendStatus(200);
} else {
  res.sendStatus(403);
}
```

{% endtab %}

{% tab title="Java" %}

```java
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

// Your secret key
String secret = "your_webhook_signing_secret";
String payload = "your_payload";
String XMonerooSignature = "header_value";

Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
sha256_HMAC.init(secret_key);

String computedSignature = new String(sha256_HMAC.doFinal(payload.getBytes(StandardCharsets.UTF_8)));
if (computedSignature.equals(XMonerooSignature)) {
    System.out.println("200 OK");
} else {
    System.out.println("403 Forbidden");
}
```

{% endtab %}

{% tab title="Python" %}

```python
import hashlib
import hmac

secret = 'your_webhook_signing_secret'
payload = 'your_payload'
XMonerooSignature = 'header_value'

computed_signature = hmac.new(secret.encode(), msg=payload.encode(), digestmod=hashlib.sha256).hexdigest()

if computed_signature == XMonerooSignature:
    print("200 OK")
else:
    print("403 Forbidden")
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/hex"
    "fmt"
)

func main() {
    secret := "your_webhook_signing_secret"
    payload := []byte("your_payload")
    XMonerooSignature := "header_value"

    h := hmac.New(sha256.New, []byte(secret))
    h.Write(payload)
    computedSignature := hex.EncodeToString(h.Sum(nil))

    if computedSignature == XMonerooSignature {
        fmt.Println("200 OK")
    } else {
        fmt.Println("403 Forbidden")
    }
}
```

{% endtab %}
{% endtabs %}

### Bonnes Pratiques de Webhook

* **Ne vous fiez pas uniquement aux Webhooks** : Veillez à disposer d'une stratégie de sauvegarde, telle qu'une tâche d'arrière-plan qui vérifie à intervalles réguliers l'état des transactions en attente. Cela peut s'avérer utile en cas de défaillance de votre point d'accès au Webhook.
* **Utilisez un hachage secret** : L'URL de votre Webhook est publique, n'importe qui peut envoyer une fausse charge utile. Nous recommandons d'utiliser un hachage secret pour authentifier les demandes.
* **Toujours réinterroger** : Vérifiez les détails reçus avec notre API pour garantir l'intégrité des données. Par exemple, lors de la réception d'une notification de paiement réussie, utilisez notre point de terminaison de vérification de transaction pour vérifier le statut de la transaction.
* **Répondre rapidement** : Votre point d'accès au Webhook doit répondre dans un certain délai pour éviter les échecs et les nouvelles tentatives. Évitez d'exécuter des tâches de longue haleine dans votre point de terminaison du Webhook afin d'éviter les dépassements de délai. Répondez immédiatement avec un code d'état 200, puis exécutez toutes les tâches longues de manière asynchrone.
* **Gérer les doublons** : Dans certains cas, les Webhooks peuvent être transmis plusieurs fois. Par exemple, si nous ne recevons pas de réponse de votre point d'accès, nous relançons le Webhook. Assurez-vous que votre point d'accès peut gérer des notifications de Webhooks en double.
* **Gérer les échecs** : En cas d'échec de votre point de terminaison, nous réessayerons le Webhook jusqu'à trois fois, avec un délai de 10 minutes entre chaque tentative. Si toutes les tentatives échouent, nous cessons d'essayer et marquons le Webhook comme ayant échoué. Vous pouvez consulter les Webhooks qui ont échoué dans votre tableau de bord.


# Initialiser un paiement

Lorsque vous encaissez des paiements avec Moneroo, de nombreuses options s'offrent à vous. En voici un bref aperçu :

* [**Moneroo Standard** ](/fr/payments/integration-standard)**:** Il s'agit de l'approche d'intégration de base, "standard". Pour l'utiliser, vous devez appeler notre API depuis votre serveur pour générer un lien de paiement. Vous redirigez ensuite votre client vers ce lien pour qu'il effectue le paiement. Une fois le paiement traité, nous le redirigeons vers vous.

D'autres options et intégrations seront bientôt disponibles.


# Intégration Standard

### Vue d'ensemble

Moneroo Standard est notre flux de paiement qui redirige votre client vers une page de paiement hébergée par Moneroo.

Voici comment cela fonctionne :

* Depuis votre serveur, appelez le endpoint "initialiser le paiement" de notre API avec les détails du paiement.
* Nous vous renvoyons un lien vers une page de paiement. Redirigez votre client vers ce lien pour effectuer le paiement.
* Lorsque la transaction est terminée, nous redirigeons le client vers vous (vers `return_url` que vous avez fournie) avec les détails du paiement.

### Étape 1 : Collecte des données de paiement

Tout d'abord, vous devez rassembler les données de paiement qui seront envoyées à votre API sous la forme d'un objet JSON.

Voici les champs à collecter :

<table><thead><tr><th width="305">Nom du champ</th><th width="145">Type</th><th width="125">Exigée</th><th>Description</th></tr></thead><tbody><tr><td><code>amount</code></td><td>integer</td><td>Oui</td><td>Le montant du paiement.</td></tr><tr><td><code>currency</code></td><td>string</td><td>Oui</td><td>La devise du paiement.</td></tr><tr><td><code>description</code></td><td>string</td><td>Oui</td><td>Description du paiement.</td></tr><tr><td><code>return_url</code></td><td>string</td><td>Oui</td><td>URL de retour où votre client sera redirigé après le paiement.</td></tr><tr><td><code>customer.email</code></td><td>string</td><td>Oui</td><td>Adresse e-mail du client.</td></tr><tr><td><code>customer.first_name</code></td><td>string</td><td>Oui</td><td>Prénom du client.</td></tr><tr><td><code>customer.last_name</code></td><td>string</td><td>Oui</td><td>Nom de famille du client.</td></tr><tr><td><code>customer.phone</code></td><td>string</td><td>Non<strong>¹</strong></td><td>Numéro de téléphone du client.</td></tr><tr><td><code>customer.address</code></td><td>string</td><td>Non<strong>¹</strong></td><td>Adresse du client.</td></tr><tr><td><code>customer.city</code></td><td>string</td><td>Non<strong>¹</strong></td><td>Ville du client.</td></tr><tr><td><code>customer.state</code></td><td>string</td><td>Non<strong>¹</strong></td><td>État du client.</td></tr><tr><td><code>customer.country</code></td><td>string</td><td>Non<strong>¹</strong></td><td>Pays du client.</td></tr><tr><td><code>customer.zip</code></td><td>string</td><td>Non<strong>¹</strong></td><td>Code postal du client.</td></tr><tr><td><code>metadata</code></td><td>array</td><td>Non<strong>²</strong></td><td>Données complémentaires pour le paiement.</td></tr><tr><td><code>methods</code></td><td>array</td><td>Non<strong>³</strong></td><td>Méthodes de paiement autorisées.</td></tr><tr><td><code>restrict_country_code</code></td><td>string</td><td>Non⁴</td><td>Restreindre le paiement à un pays spécifique.</td></tr><tr><td><code>restricted_phone</code></td><td>object</td><td>Non⁴</td><td>Restreindre le paiement à un numéro de téléphone spécifique.</td></tr><tr><td><code>restricted_phone.number</code></td><td>string</td><td>Oui⁵</td><td>Le numéro de téléphone auquel restreindre le paiement.</td></tr><tr><td><code>restricted_phone.country_code</code></td><td>string</td><td>Oui⁵</td><td>Le code pays du numéro de téléphone restreint.</td></tr></tbody></table>

1. Si ces informations ne sont pas fournies, le client peut être invité à les saisir au cours de la procédure de paiement, en fonction de la méthode de paiement sélectionnée.
2. Il doit s'agir d'un tableau de paires clé-valeur. Seules les chaînes de caractères sont autorisées.
3. S'il n'est pas fourni, tous les modes de paiement disponibles seront autorisés. Le tableau ne doit contenir que les modes de paiement pris en charge.
4. Vous pouvez utiliser soit `restrict_country_code`, soit `restricted_phone`, mais pas les deux. Ils sont mutuellement exclusifs.
5. Obligatoire si `restricted_phone` est fourni.

### Étape 2 : Obtention d'un lien de paiement

Ensuite, initiez le paiement en appelant notre API avec les détails de paiement collectés (n'oubliez pas d'autoriser avec votre clé secrète).

#### Exemple de demande :

```bash
POST /v1/payments/initialize
Host: https://api.moneroo.io
Authorization: Bearer YOUR_SECRET_KEY
Content-Type: application/json
Accept: application/json
{
    "amount": 100,
    "currency": "USD",
    "description": "Payment for order #123",
    "customer": {
        "email": "john@example.com",
        "first_name": "John",
        "last_name": "Doe"
    },
    "return_url": "https://example.com/payments/thank-you"
    "metadata": {
        "order_id": "123",
        "customer_id": "123" 
    },
    "methods": ["qr_ngn", "bank_transfer_ngn"]
}
```

#### Exemple de réponse :

```json
{
  "success": true,
  "message": "Transaction initialized successfully",
  "data": {
    "id": "5f7b1b2c-1b2c-5f7b-0000-000000000000",
    "checkout_url": "https://checkout.moneroo.io/5f7b1b2c-1b2c-5f7b-0000-000000000000"
  }
}
```

### Étape 3 : Redirection de l'utilisateur vers le lien de paiement

Il vous suffit de rediriger votre client vers le lien renvoyé dans data.link. Nous afficherons notre interface de paiement pour que le client puisse effectuer le paiement.

### Étape 4 : Après le paiement

Une fois le paiement effectué (avec ou sans succès), cinq choses se produisent :

* Nous redirigeons vers votre URL de retour avec le statut, `monerooPaymentId`, et `monerooPaymentStatus` dans les paramètres de la requête une fois que le paiement est terminé.
* Nous vous enverrons un Webhook si vous l'avez activé. Pour plus d'informations sur les Webhooks et pour voir des exemples, consultez notre guide sur les Webhooks.
* Nous enverrons un accusé de réception à votre client si le paiement a été effectué avec succès (sauf si vous l'avez désactivé).
* Nous vous enverrons un email (sauf si vous l'avez désactivé).
* Côté serveur, vous devez gérer la redirection et toujours vérifier l'état final de la transaction. Un exemple de vérification d'une transaction dans une application PHP avec notre backend SDK sera fourni plus loin.

Si vous avez activé les Webhooks, nous vous enverrons une notification pour chaque tentative de paiement échouée. C'est utile si vous souhaitez contacter ultérieurement les clients qui ont eu des difficultés à payer. Consultez notre guide des Webhooks pour un exemple.

### Exemple

{% hint style="warning" %}

* N'oubliez pas de remplacer `YOUR_SECRET_KEY` par votre véritable clé secrète.
* Tous les exemples suivants doivent être réalisés dans le backend, ne jamais exposer votre clé secrète au public.
  {% endhint %}

{% tabs %}
{% tab title="cURL" %}

```
curl -X POST https://api.moneroo.io/v1/payments/initialize \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer YOUR_SECRET_KEY" \
     -H "Accept: application/json" \
     -d '{
         "amount": 100,
         "currency": "USD",
         "description": "Payment for order #123",
         "customer": {
             "email": "john@example.com",
             "first_name": "John",
             "last_name": "Doe"
         },
         "return_url": "https://example.com/payments/thank-you",
         "metadata": {
             "order_id": "123",
             "customer_id": "123"
         },
         "methods": ["qr_ngn", "bank_transfer_ngn"]
     }'
```

{% endtab %}

{% tab title="PHP" %}

<pre class="language-php"><code class="lang-php"><strong>&#x3C;?php
</strong>
$url = 'https://api.moneroo.io/v1/payments/initialize';

$headers = [
    'Content-Type: application/json',
    'Authorization: Bearer YOUR_SECRET_KEY'
    'Accept: application/json'
];

$data = [
    "amount" => 100,
    "currency" => "USD",
    "description" => "Payment for order #123",
    "customer" => [
        "email" => "john@example.com",
        "first_name" => "John",
        "last_name" => "Doe"
    ],
    "return_url" => "https://example.com/payments/thank-you",
    "metadata" => [
        "order_id" => "123",
        "customer_id" => "123",
    ],
    "methods" => ["qr_ngn", "bank_transfer_ngn"]
];

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

if ($httpcode != 201) {
    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}

$response_data = json_decode($response, true);

// Redirect to checkout page
header("Location: " . $response_data['checkout_url']);

?>

</code></pre>

{% endtab %}

{% tab title="Python" %}

```python
import requests
import json

url = 'https://api.moneroo.io/v1/payments/initialize'

headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_SECRET_KEY'
    'Accept': 'application/json'
}

data = {
    "amount": 100,
    "currency": "USD",
    "description": "Payment for order #123",
    "customer": {
        "email": "john@example.com",
        "first_name": "John",
        "last_name": "Doe"
    },
    "return_url": "https://example.com/payments/thank-you",
    "metadata": {
        "order_id": "123",
        "customer_id": "123",
    },
    "methods": ["qr_ngn", "bank_transfer_ngn"]
}

response = requests.post(url, headers=headers, data=json.dumps(data))

if response.status_code != 201:
    raise Exception(f"Request failed with status {response.status_code}")

checkout_url = response.json()['checkout_url']
print(f"Redirect to: {checkout_url}")
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"bytes"
	"encoding/json"
	"net/http"
	"fmt"
)

func main() {
	data := map[string]interface{}{
		"amount": 100,
		"currency": "USD",
		"description": "Payment for order #123",
		"customer": map[string]string{
			"email": "john@example.com",
			"first_name": "John",
			"last_name": "Doe",
		},
		"return_url": "https://example.com/payments/thank-you",
		"metadata": map[string]string{
			"order_id": "123",
			"customer_id": "123",
		},
		"methods": []string{"qr_ngn", "bank_transfer_ngn"},
	}

	bytesRepresentation, _ := json.Marshal(data)

	req, _ := http.NewRequest("POST", "https://api.moneroo.io/v1/payments/initialize", bytes.NewBuffer(bytesRepresentation))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer YOUR_SECRET_KEY")
	req.Header.Set("Accept", "application/json")

	client := &http.Client{}
	response, _ := client.Do(req)
	defer response.Body.Close()

	var result map[string]interface{}
	json.NewDecoder(response.Body).Decode(&result)

	if response.StatusCode != 201 {
		panic(fmt.Sprintf("Request failed with status %d", response.StatusCode))
	}

	fmt.Printf("Redirect to: %s", result["checkout_url"])
}
```

{% endtab %}

{% tab title="JavaScript (Node.js)" %}

```javascript
const axios = require('axios');

const data = {
    "amount": 100,
    "currency": "USD",
    "description": "Payment for order #123",
    "customer": {
        "email": "john@example.com",
        "first_name": "John",
        "last_name": "Doe"
    },
    "return_url": "https://example.com/payments/thank-you",
    "metadata": {
        "order_id": "123",
        "customer_id": "123",
    },
    "methods": ["qr_ngn", "bank_transfer_ngn"]
};

const options = {
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_SECRET_KEY'
    'Accept': 'application/json'
  }
};

axios.post('https://api.moneroo.io/v1/payments/initialize', data, options)
    .then((response) => {
        if (response.status !== 201) {
            throw new Error(`Request failed with status ${response.status}`);


 }
        console.log(`Redirect to: ${response.data.checkout_url}`);
    })
    .catch((error) => {
        console.error(error);
    });
```

{% endtab %}
{% endtabs %}


# Vérifier un paiement

Après le paiement, il est essentiel de confirmer que la transaction a été traitée par Moneroo avant d'accréditer la valeur de votre client dans votre application. Cette précaution permet de s'assurer que le paiement reçu correspond à vos attentes.

Voici quelques points clés à vérifier lors de la confirmation du paiement :

1. Confirmez que la référence de la transaction correspond à celle que vous avez générée.
2. Vérifiez l'exactitude du statut de la transaction. Le statut de la transaction doit être "succès" pour les paiements réussis. Pour en savoir plus sur les statuts de transaction, voir la section Statut de transaction.
3. Vérifier que la devise du paiement correspond à la devise attendue.
4. Assurez-vous que le montant payé est égal ou supérieur au montant prévu. Si le montant est supérieur, vous pouvez fournir au client la valeur correspondante et rembourser l'excédent.

Pour authentifier un paiement, utilisez le endpoint "verify transaction", en spécifiant l'ID de la transaction dans l'URL. Vous pouvez obtenir l'ID de la transaction à partir du champ `data.id` dans la réponse après la création de la transaction, ainsi que dans le contenu du Webhook pour toute transaction.

### Demande

```bash
GET /v1/payments/{paymentId}/verify HTTP/1.1
Host: https://api.moneroo.io
Authorization: Bearer YOUR_SECRET_KEY
Content-Type: application/json
Accept: application/json
```

#### Paramètres

* Endpoint: `/v1/payments/{paymentId}/verify`
* Method: `GET`

<table><thead><tr><th>Nom</th><th width="76">Type</th><th width="103">Exigée</th><th>Description</th></tr></thead><tbody><tr><td><code>paymentId</code></td><td>String</td><td>Oui</td><td>L'ID unique de l'opération de paiement à vérifier.</td></tr></tbody></table>

### Structure de la réponse

La réponse de ce endpoint de l'API sera dans le format de réponse standard de l'API Moneroo. Vous obtiendrez une réponse qui ressemble à ceci :

```json
{
  "success": true,
  "message": "Payment transaction fetched successfully",
  "data": {
    // Details of the payment transaction
  }
}
```

**Réponse positive**

En cas de récupération réussie, l'endpoint renvoie un code d'état HTTP de 200 et les détails de l'opération de paiement dans le corps de la réponse.

**Réponses d'erreurs:**

Si votre demande pose un problème, l'API renvoie une réponse d'erreur. Le type de réponse dépend de la nature du problème. Consultez notre page sur les formats de réponse pour plus d'informations.

### Considérations de sécurité

Cet endpoint nécessite un jeton de support pour l'authentification. Ce jeton doit être inclus dans l'en-tête `Authorization` de la demande. Assurez-vous que le jeton est conservé en toute sécurité et qu'il n'est pas partagé ou exposé de manière inappropriée.

### Exemples de demandes

Veuillez remplacer`'paymentId'` par l'id de la transaction de paiement et`'your_token'` par votre jeton d'autorisation valide dans les extraits de code ci-dessus.

{% tabs %}
{% tab title="Curl" %}

```bash
curl --location --request GET 'https://api.moneroo.io/v1/payments/{paymentId}/verify' \
--header 'Authorization: Bearer YOUR_TOKEN'
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php

$paymentId = 'your_payment_id';
$token = 'your_token';

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://api.moneroo.io/v1/payments/{$paymentId}/verify",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer {$token}"
  ]
]);

$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ($httpCode === 200) {
  // Handle successful response
} else {
  // Handle error response
}

curl_close($curl);
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

paymentId = 'your_payment_id'
token = 'your_token'

headers = {
  'Authorization': f'Bearer {token}'
}

response = requests.get(f'https://api.moneroo.io/v1/payments/{paymentId}/verify', headers=headers)

if response.status_code == 200:
  # Handle successful response
else:
  # Handle error response
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"fmt"
	"net/http"
)

func main() {
	paymentId := "your_payment_id"
	token := "your_token"

	url := fmt.Sprintf("https://api.moneroo.io/v1/payments/%s/verify", paymentId)
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		// Handle error
	}

	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		// Handle error
	}
	defer resp.Body.Close()

	if resp.StatusCode == 200 {
		// Handle successful response
	} else {
		// Handle error response
	}
}
```

{% endtab %}

{% tab title="JavaScript (Node.js)" %}

```javascript
const axios = require("axios");

const paymentId = "your_payment_id";
const token = "your_token";

axios
  .get(`https://api.moneroo.io/v1/payments/${paymentId}/verify`, {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  })
  .then((response) => {
    if (response.status === 200) {
      // Handle successful response
    } else {
      // Handle error response
    }
  })
  .catch((error) => {
    // Handle error
  });
```

{% endtab %}
{% endtabs %}

### Exemple de réponse

Vous obtiendrez une réponse qui ressemble à celle-ci :

```json
{
  "success": true,
  "message": "Payment transaction fetched successfully",
  "data": {
    "id": "abc123",
    "status": "success",
    "is_processed": true,
    "processed_at": "2023-05-21T12:00:00Z",
    "amount": 100.0,
    "currency": "USD",
    "amount_formatted": "$100.00",
    "description": "Purchase of goods",
    "return_url": "https://example.com/return",
    "environment": "production",
    "initiated_at": "2023-05-21T11:00:00Z",
    "checkout_url": "https://example.com/checkout",
    "payment_phone_number": "+1234567890",
    "app": {
      "id": "app1",
      "name": "Example App",
      "icon_url": "https://example.com/icon.png"
    },
    "customer": {
      "id": "cust1",
      "first_name": "John",
      "last_name": "Doe",
      "email": "john.doe@example.com",
      "phone": "+1234567890",
      "address": "123 Main St",
      "city": "Springfield",
      "state": "IL",
      "country_code": "US",
      "country": "United States",
      "zip_code": "62701",
      "environment": "production",
      "created_at": "2023-01-01T00:00:00Z",
      "updated_at": "2023-05-21T00:00:00Z"
    },
    "method": {
      "name": "Credit Card",
      "code": "cc",
      "icon_url": "https://example.com/cc.png",
      "environment": "production"
    },
    "gateway": {
      "name": "Stripe",
      "account_name": "Acme Corp",
      "code": "stripe",
      "icon_url": "https://example.com/stripe.png",
      "environment": "production"
    },
    "metadata": {
      "custom_field1": "custom_value1",
      "custom_field2": "custom_value2"
    },
    "context": {
      "ip": "192.0.2.0",
      "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (HTML, like Gecko) Chrome/58.0.3029.110 Safari/537",
      "country": "US",
      "local": "en-US"
    }
  }
}
```

Les détails de la transaction sont contenus dans l'objet de données. Par exemple :

* Le statut de la transaction est indiqué dans `data.status`.
* Les détails du client se trouvent dans le champ`data.customer`.
* Le champ `data.amount` indique le montant facturé au client.
* Certains champs varient en fonction du type de transaction ou de l'état de la transaction.
* Le champ `data.method` contient la méthode de paiement utilisée par le client.
* Le champ `data.gateway` contient la passerelle de paiement utilisée pour traiter la transaction.
* Le champ `data.metadata` contient toutes les métadonnées personnalisées que vous avez pu fournir lors de la création de la transaction.
* Le champ `data.context` contient le contexte de la transaction.
* Le champ `data.app` contient les détails de l'application.

| Nom du champ           | Description                                              |
| ---------------------- | -------------------------------------------------------- |
| `id`                   | L'ID public de la transaction.                           |
| `status`               | Le statut de la transaction.                             |
| `is_processed`         | Indique si la transaction est traitée.                   |
| `processed_at`         | L'heure à laquelle la transaction a été traitée.         |
| `amount`               | Le montant de la transaction.                            |
| `currency`             | La devise utilisée dans la transaction.                  |
| `amount_formatted`     | Le montant formaté impliqué dans la transaction.         |
| `description`          | La description de la transaction.                        |
| `return_url`           | L'URL à laquelle retourner après la transaction.         |
| `environment`          | L'environnement dans lequel la transaction a eu lieu.    |
| `initiated_at`         | L'heure à laquelle la transaction a été initiée.         |
| `checkout_url`         | L'URL pour vérifier la transaction.                      |
| `payment_phone_number` | Le numéro de téléphone associé à la méthode de paiement. |
| `app`                  | L'application associée à la transaction.                 |
| `customer`             | Le client associé à la transaction.                      |
| `method`               | Le mode de paiement associé à la transaction.            |
| `gateway`              | La passerelle de paiement associée à la transaction.     |
| `metadata`             | Les métadonnées associées à la transaction.              |
| `context`              | Le contexte associé à la transaction.                    |


# Retrouver un paiement

L'API de la plateforme Moneroo offre un endpoint qui vous permet de récupérer les informations détaillées d'une transaction de paiement spécifique sur la base de son `transaction ID`.

Ce guide vous guidera à travers le processus de récupération d'une transaction de paiement en utilisant l'API de Moneroo.

### Demande

```bash
GET /v1/payments/{paymentId} HTTP/1.1
Host: https://api.moneroo.io
Authorization: Bearer YOUR_SECRET_KEY
Content-Type: application/json
Accept: application/json
```

#### Paramètres

* Endpoint: `/v1/payments/{paymentId}`
* Method: `GET`

<table><thead><tr><th width="211">Nom</th><th width="107">Type</th><th width="89">Exigée</th><th>Description</th></tr></thead><tbody><tr><td><code>paymentId</code></td><td>String</td><td>Oui</td><td>L'id de l'opération de paiement à récupérer.</td></tr></tbody></table>

### Structure de la Réponse

La réponse de cet endpoint de l'API sera dans le format standard de réponse de l'API Moneroo.

Vous obtiendrez une réponse qui ressemble à celle-ci :

```json
{
  "success": true,
  "message": "Payment transaction fetched successfully",
  "data": {
    // Details of the payment transaction
  }
}
```

**Réponse Positive:**

En cas de récupération réussie, l'endpoint renvoie un code d'état HTTP de 200 et les détails de l'opération de paiement dans le corps de la réponse.

**Réponses d'erreurs :**

Si votre demande pose un problème, l'API renvoie une réponse d'erreur. Le type de réponse dépend de la nature du problème. Consultez notre page sur les formats de réponse pour plus d'informations.

### Considérations de sécurité

Cet endpoint nécessite un jeton de support pour l'authentification. Ce jeton doit être inclus dans l'en-tête Authorization de la demande. Assurez-vous que le jeton est conservé en toute sécurité et qu'il n'est pas partagé ou exposé de manière inappropriée.

### Exemples de demandes

{% hint style="info" %}
Veuillez remplacer `'`**`paymentId`**`'` par l'identifiant de la transaction de paiement et`'`**`your_token`**`'` par votre jeton d'autorisation valide dans les extraits de code ci-dessus.
{% endhint %}

{% tabs %}
{% tab title="Curl" %}

```bash
curl --location --request GET 'https://api.moneroo.io/v1/payments/{paymentId}' \
--header 'Authorization: Bearer YOUR_TOKEN'
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php

$paymentId = 'your_payment_public_id';
$token = 'your_token';

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://api.moneroo.io/v1/payments/{$paymentId}",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer {$token}"
  ]
]);

$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ($httpCode === 200) {
  $responseData = json_decode($response, true);
  // Handle successful response and retrieve the payment transaction details
} else {
  // Handle error response
}

curl_close($curl);
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

payment_public_id = 'your_payment_public_id'
token = 'your_token'

headers = {
  'Authorization': f'Bearer {token}'
}

response = requests.get(f'https://api.moneroo.io/v1/payments/{payment_public_id}', headers=headers)

if response.status_code == 200:
  data = response.json()
  # Handle successful response and retrieve the payment transaction details
else:
  # Handle error response
```

{% endtab %}

{% tab title="Go" %}

<pre class="language-go"><code class="lang-go"><strong>package main
</strong>
import (
	"fmt"
	"net/http"
	"io/ioutil"
)

func main() {
	paymentPublicID := "your_payment_public_id"
	token := "your_token"

	url := fmt.Sprintf("https://api.moneroo.io/v1/payments/%s", paymentPublicID)
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		// Handle error
	}

	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))

	client := &#x26;http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		// Handle error
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// Handle error
	}

	if resp.StatusCode == 200 {
		// Handle successful response and retrieve the payment transaction details
	} else {
		// Handle error response
	}
}
</code></pre>

{% endtab %}

{% tab title="JavaScript (Node.js)" %}

```javascript
const axios = require("axios");

const paymentId = "your_payment_public_id";
const token = "your_token";

axios
  .get(`https://api.moneroo.io/v1/payments/${paymentId}`, {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  })
  .then((response) => {
    if (response.status === 200) {
      const data = response.data;
      // Handle successful response and retrieve the payment transaction details
    } else {
      // Handle error response
    }
  })
  .catch((error) => {
    // Handle error
  });
```

{% endtab %}
{% endtabs %}

### Exemple de réponse

Vous obtiendrez une réponse qui ressemble à celle-ci :

```json
{
  "success": true,
  "message": "Payment transaction fetched successfully",
  "data": {
    "id": "abc123",
    "status": "success",
    "is_processed": true,
    "processed_at": "2023-05-21T12:00:00Z",
    "amount": 100.0,
    "currency": "USD",
    "amount_formatted": "$100.00",
    "description": "Purchase of goods",
    "return_url": "https://example.com/return",
    "environment": "production",
    "initiated_at": "2023-05-21T11:00:00Z",
    "checkout_url": "https://example.com/checkout",
    "payment_phone_number": "+1234567890",
    "app": {
      "id": "app1",
      "name": "Example App",
      "icon_url": "https://example.com/icon.png"
    },
    "customer": {
      "id": "cust1",
      "first_name": "John",
      "last_name": "Doe",
      "email": "john.doe@example.com",
      "phone": "+1234567890",
      "address": "123 Main St",
      "city": "Springfield",
      "state": "IL",
      "country_code": "US",
      "country": "United States",
      "zip_code": "62701",
      "environment": "production",
      "created_at": "2023-01-01T00:00:00Z",
      "updated_at": "2023-05-21T00:00:00Z"
    },
    "method": {
      "name": "Credit Card",
      "code": "cc",
      "icon_url": "https://example.com/cc.png",
      "environment": "production"
    },
    "gateway": {
      "name": "Stripe",
      "account_name": "Acme Corp",
      "code": "stripe",
      "icon_url": "https://example.com/stripe.png",
      "environment": "production"
    },
    "metadata": {
      "custom_field1": "custom_value1",
      "custom_field2": "custom_value2"
    },
    "context": {
      "ip": "192.0.2.0",
      "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (HTML, like Gecko) Chrome/58.0.3029.110 Safari/537",
      "country": "US",
      "local": "en-US"
    }
  }
}
```

Le champ de `data` contient les détails de la transaction. La structure et le contenu de ce champ dépendent des détails de chaque transaction.


# Statut

Lorsque vous acceptez des paiements, vous pouvez suivre leur évolution en prêtant attention aux statuts spécifiques des transactions. Cette section a pour but de vous aider à comprendre la signification de chaque statut de transaction sur Moneroo.

Ainsi, chaque étape de paiement passant par notre plateforme est accompagnée d'un certain statut de transaction. Tous ces statuts sont divisés en deux groupes : **transitoire** ou **final**.

Vue simple des statuts des transactions de paiement :

<figure><img src="/files/rex7vjOqRzsrUycLxiiV" alt=""><figcaption><p>Etat de la transaction de paiement Moneroo</p></figcaption></figure>

Le tableau ci-dessous donne une vue d'ensemble des statuts des opérations de paiement :

| Statuts     |      Etat      | Description                                                                                        |
| ----------- | :------------: | -------------------------------------------------------------------------------------------------- |
| `initiated` | Transactionnel | La transaction a été initiée et attend que le client complète le paiement sur la page de paiement. |
| `pending`   | Transactionnel | Le client a commencé le processus de paiement, mais il n'est pas encore terminé.                   |
| `cancelled` |      Final     | La transaction a été annulée. Il s'agit d'un statut final.                                         |
| `failed`    |      Final     | La transaction a échoué. Il s'agit d'un état final.                                                |
| `success`   |      Final     | La transaction a été effectuée avec succès. Il s'agit d'un statut final.                           |


# Méthodes Disponibles

Vous trouverez ci-dessous une liste des méthodes de paiement que nous acceptons. Cette liste s'enrichit constamment, alors n'hésitez pas à la consulter régulièrement pour des mises à jour.

Pour en savoir plus sur une méthode de paiement spécifique et sur la passerelle de paiement qui la prend en charge, veuillez consulter la section de votre [liste de connexions](http://moneroo.io/connection)

{% hint style="info" %}
Vous pouvez obtenir une liste actualisée de toutes les méthodes de paiement disponibles en appelant l'endpoint [GET /utils/payment/methods](https://api.moneroo.io/utils/payment/methods).

```
GET /utils/payout/methods HTTP/1.1
Host: https://api.moneroo.io
Accept: application/json
```

{% endhint %}

***

| Noms                           | Codes              | Devises |          Pays          |
| ------------------------------ | ------------------ | :-----: | :--------------------: |
| Orange Money Côte d'Ivoire     | `orange_ci`        |   XOF   |           CI           |
| Orange Money Sénégal           | `orange_sn`        |   XOF   |           SN           |
| Orange Money Burkina Faso      | `orange_bf`        |   XOF   |           BF           |
| Orange Money Mali              | `orange_ml`        |   XOF   |           ML           |
| E-Money Sénégal                | `e_money_sn`       |   XOF   |           SN           |
| Orange Money Cameroon          | `orange_cm`        |   XAF   |           CM           |
| EU Mobile Money Cameroon       | `eu_mobile_cm`     |   XAF   |           CM           |
| MTN Mobile Money Cameroon      | `mtn_cm`           |   XAF   |           CM           |
| MTN Mobile Money Bénin         | `mtn_bj`           |   XOF   |           BJ           |
| MTN Mobile Money Côte d'Ivoire | `mtn_ci`           |   XOF   |           CI           |
| Airtel Money Nigéria           | `airtel_ng`        |   NGN   |           NG           |
| Moov Money Bénin               | `moov_bj`          |   XOF   |           BJ           |
| Moov Money Burkina Faso        | `moov_bf`          |   XOF   |           BF           |
| Moov Money Togo                | `moov_tg`          |   XOF   |           TG           |
| Moov Money Côte d'Ivoire       | `moov_ci`          |   XOF   |           CI           |
| Moov Money Mali                | `moov_ml`          |   XOF   |           ML           |
| Togocel Money (TMoney)         | `togocel`          |   XOF   |           TG           |
| Credit Card NGN                | `card_ngn`         |   NGN   |           NG           |
| Credit Card USD                | `card_usd`         |   USD   |           US           |
| Credit Card GHS                | `card_ghs`         |   GHS   |           GH           |
| Credit Card XOF                | `card_xof`         |   XOF   |   CI, BF, TG, BJ, ML   |
| Credit Card XAF                | `card_xaf`         |   XAF   | CM, CF, CG, GA, GQ, TD |
| Credit Card ZAR                | `card_zar`         |   ZAR   |           ZA           |
| Wave Côte d'Ivoire             | `wave_ci`          |   XOF   |           CI           |
| Wave Sénégal                   | `wave_sn`          |   XOF   |           SN           |
| Free Money Sénégal             | `freemoney_sn`     |   XOF   |           SN           |
| MTN Nigéria                    | `mtn_ng`           |   NGN   |           NG           |
| MTN Ghana                      | `mtn_gh`           |   GHS   |           GH           |
| Mobi Cash Burkina Faso         | `mobi_cash_bf`     |   XOF   |           BF           |
| Mobi Cash Mali                 | `mobi_cash_ml`     |   XOF   |           ML           |
| Airtel Niger                   | `airtel_ne`        |   XOF   |           NE           |
| MTN MoMo Guinée                | `mtn_gf`           |   GNF   |           GN           |
| Airtel/Tigo Ghana              | `airtel_gh`        |   GHS   |           GH           |
| Vodafone Ghana                 | `vodafone_gh`      |   GHS   |           GH           |
| Barter                         | `barter`           |   NGN   |           NG           |
| USSD NGN                       | `ussd_ngn`         |   NGN   |           NG           |
| QR Code Nigéria                | `qr_ngn`           |   NGN   |           NG           |
| Bank Transfer Nigéria          | `bank_transfer_ng` |   NGN   |           NG           |

Nous ajoutons constamment de nouvelles méthodes de paiement. Si vous ne trouvez pas votre mode de paiement préféré, veuillez [nous contacter](https://moneroo.io/contact).


# Tests

Tester votre intégration est une étape cruciale pour garantir une expérience de paiement transparente avec Moneroo. Moneroo met à votre disposition un environnement de test dédié, vous permettant de valider votre intégration avant de la mettre en ligne. Dans le mode sandbox, vous pouvez simuler des transactions réelles sans traiter de vrais paiements.

Pour effectuer des tests dans l'environnement sandbox, vous utiliserez des clés spécifiques appelées "clés sandbox" ou "clés de test". Ces clés sont distinctes des clés de production et sont destinées à des fins de test uniquement. Elles fournissent un environnement sécurisé et contrôlé pour expérimenter et valider votre intégration.

En utilisant les clés et l'environnement sandbox de Moneroo, vous pouvez tester en profondeur votre intégration, assurer la compatibilité et résoudre les problèmes éventuels avant de la déployer dans l'environnement de production réel.

Les données en sandbox sont automatiquement supprimées après 90 jours. Cela ne concerne que les transactions et les clients.

### Processeur de paiement par défaut : Passerelle de paiement Moneroo Test

Par défaut, votre application Moneroo inclut la "Passerelle de paiement test Moneroo" comme passerelle de paiement par défaut dans l'environnement sandbox. Cette passerelle de paiement vous permet de simuler différents scénarios de transaction et d'observer comment votre système réagit dans chaque cas.

Pour simuler différents scénarios de transactions de paiement et tester en profondeur votre intégration, Moneroo fournit des numéros de téléphone de test spécifiques. Ces numéros peuvent être utilisés pour simuler des transactions réussies ou échouées, ce qui vous permet d'évaluer la manière dont votre système gère chaque scénario. Au cours de votre processus de test, vous pouvez utiliser ces numéros de téléphone de test pour imiter le comportement des transactions réelles et observer les réponses de votre intégration en fonction de vos besoins.

{% hint style="info" %}

* Les numéros de téléphone de test ne sont disponibles que pour la passerelle de paiement de test Moneroo et ne peuvent pas être utilisés avec d'autres passerelles de paiement en mode sandbox.
* Ces numéros peuvent être utilisés pour simuler leurs scénarios respectifs pour toutes les méthodes de paiement associées à la passerelle de paiement Moneroo Test.
  {% endhint %}

<table><thead><tr><th width="230">Numéros de téléphone</th><th>Scénarios</th><th>Devises</th><th width="100">Pays</th></tr></thead><tbody><tr><td>4149518161</td><td>Transaction réussie</td><td>USD</td><td>US</td></tr><tr><td>4149518162</td><td>Transaction échouée</td><td>USD</td><td>US</td></tr><tr><td>4149518163</td><td>Transaction en attente</td><td>USD</td><td>US</td></tr></tbody></table>

### Test avec d'autres passerelles de paiement en mode Sandbox

Moneroo offre la possibilité d'intégrer d'autres passerelles de paiement en mode `sandbox`.

Pour chaque passerelle de paiement disponible dans en mode sandbox, vous devez consulter la documentation de la passerelle de paiement en question pour obtenir les instructions de test. Ces instructions vous fourniront les informations nécessaires sur la manière d'intégrer la passerelle de paiement, d'utiliser les clés de test ou les informations d'identification et de simuler différents scénarios de transaction spécifiques à cette passerelle de paiement.

Moneroo travaille continuellement à l'élargissement de la disponibilité des passerelles de paiement supportées dans en mode sandbox. Par conséquent, assurez-vous de rester informé des dernières annonces et mises à jour de Moneroo concernant les nouvelles intégrations et les options de test en sandbox. Voici un lien vers la documentation de chaque passerelle de paiement supportée en mode sandbox :

| Processeurs de paiement | Instructions de test                                                                                     |
| ----------------------- | -------------------------------------------------------------------------------------------------------- |
| KkiaPay (Sandbox)       | [Consulter les instructions](https://docs.kkiapay.me/v1/v/en-1.0.0/compte/kkiapay-sandbox-guide-de-test) |
| Flutterwave (Test)      | [Consulter les instructions](https://developer.flutterwave.com/docs/integration-guides/testing-helpers/) |
| Paydunya (Sandbox)      | [Consulter les instructions](https://developers.paydunya.com/doc/EN/introduction#section-3)              |
| Paystack (Sandbox)      | [Consulter les instructions](https://paystack.com/docs/payments/test-payments/)                          |
| Stripe (Sandbox)        | [Consulter les instructions](https://stripe.com/docs/testing)                                            |
| Fedapay (Sandbox)       | [Consulter les instructions](https://docs.fedapay.com/paiements/test)                                    |


# Initialiser un transfert

## Utilisation de l'API de Transfert Moneroo

Avec l'API de transfert Moneroo, vous pouvez envoyer de l'argent à vos clients. Cette API est utile pour les remboursements, les remises, les paiements de salaires, etc.

### Fonctionnement

1. Depuis votre serveur, envoyez une requête POST à l'API de transfert Moneroo avec les détails du transfert.
2. Moneroo traite la demande via la passerelle de paiement appropriée en fonction de la méthode de transfert définie.
3. Moneroo vous envoie une réponse indiquant l'état du transfert.

### Étape 1 : Collecte des données du transfert

Tout d'abord, vous devez collecter les détails du transfert qui seront envoyés à notre API sous la forme d'un objet JSON.

Voici les champs à collecter :

<table><thead><tr><th width="248">Nom du champ</th><th width="91" align="center">Type</th><th width="123" align="center">Obligatoire</th><th>Description</th></tr></thead><tbody><tr><td><code>amount</code></td><td align="center">integer</td><td align="center">Oui</td><td>Le montant du transfert.</td></tr><tr><td><code>currency</code></td><td align="center">string</td><td align="center">Oui</td><td>La devise du transfert. La devise doit être une devise prise en charge dans un format <a href="https://en.wikipedia.org/wiki/ISO_4217">ISO 4217</a> valide.</td></tr><tr><td><code>description</code></td><td align="center">string</td><td align="center">Oui</td><td>Description du transfert.</td></tr><tr><td><code>method</code></td><td align="center">string</td><td align="center">Oui</td><td>Méthode de transfert. Il doit s'agir d'une méthode de transfert valide et prise en charge. Veuillez consulter la <a href="/pages/C6lFHFDKooA66fHitaWu">liste des méthodes de transfert prises en charge.</a></td></tr><tr><td><code>customer</code></td><td align="center">object</td><td align="center">Oui</td><td>Détails sur les clients.</td></tr><tr><td><code>customer.email</code></td><td align="center">string</td><td align="center">Oui</td><td>Adresse e-mail du client.</td></tr><tr><td><code>customer.first_name</code></td><td align="center">string</td><td align="center">Oui</td><td>Prénom du client.</td></tr><tr><td><code>customer.last_name</code></td><td align="center">string</td><td align="center">Oui</td><td>Nom du client.</td></tr><tr><td><code>customer.phone</code></td><td align="center">integer</td><td align="center">Non</td><td>Numéro de téléphone du client dans le format <a href="https://en.wikipedia.org/wiki/E.164">E164</a>.</td></tr><tr><td><code>customer.address</code></td><td align="center">string</td><td align="center">Non</td><td>Adresse du client.</td></tr><tr><td><code>customer.city</code></td><td align="center">string</td><td align="center">Non</td><td>Ville du client.</td></tr><tr><td><code>customer.state</code></td><td align="center">string</td><td align="center">Non</td><td>État du client.</td></tr><tr><td><code>customer.country</code></td><td align="center">string</td><td align="center">Non</td><td>Pays du client. Il s'agir du code du pays au format <a href="https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2">ISO 3166-1 alpha-2</a> valide.</td></tr><tr><td><code>customer.zip</code></td><td align="center">string</td><td align="center">Non</td><td>Code postal du client.</td></tr><tr><td><code>metadata</code></td><td align="center">array</td><td align="center">Non</td><td>Données supplémentaires pour le transfert.</td></tr></tbody></table>

### Étape 2 : Ajouter des champs obligatoires pour des méthodes de transfert spécifiques

Chaque méthode de paiement a ses propres champs obligatoires. Veuillez consulter [la liste des méthodes de transfert](/fr/payments/methodes-disponibles) prises en charge pour connaître les champs requis pour chaque méthode de paiement.&#x20;

Par exemple, pour la méthode `mtn_bj` (MTN Mobile Money Bénin) , vous devez ajouter les champs suivants :

* `msisdn` : Le numéro de téléphone MTN Mobile Money Benin du client où l'argent sera envoyé.

### Étape 3 : Envoi de la demande de transfert

Ensuite, lancez le transfert en appelant notre API avec les détails du transfert collectés (n'oubliez pas d'autoriser la requête avec votre clé secrète).

#### Exemple de demande :

```bash
POST /v1/payouts/initialize
Host: https://api.moneroo.io
Authorization: Bearer YOUR_SECRET_KEY
Content-Type: application/json
Accept: application/json
{
    "amount": 1000,
    "currency": "XOF",
    "description": "Order refund",
    "customer": {
        "email": "john@example.com",
        "first_name": "John",
        "last_name": "Doe"
    },
    "phone": "22912345678",
    "metadata": {
        "payout_request": "123",
        "customer_id": "123"
    },
    "method": "mtn_bj"
}
```

#### Exemple de réponse :

```json
{
  "success": true,
  "message": "Payout transaction initialized successfully",
  "data": {
    "id": "5f7b1b2c-1b2c-5f7b-0000-000000000000"
  }
}
```

### Étape 4 : Après l'envoi de la demande de transfert

D'accord, voici le texte révisé :

***

Une fois le transfert effectué (avec ou sans succès), trois choses se produisent :

1. Nous vous enverrons un Webhook si vous l'avez activé. Pour plus d'informations sur les Webhooks et pour voir des exemples, consultez notre [guide sur les Webhooks](/fr/introduction/webhooks).
2. Nous vous enverrons un email (sauf si vous l'avez désactivé).
3. Côté serveur, vous pouvez vérifier la transaction en appelant notre API avec l'ID de la transaction.

Si vous avez activé les Webhooks, nous vous enverrons une notification pour chaque transfert échoué. C'est utile si vous souhaitez contacter les clients ultérieurement ou effectuer d'autres actions. Consultez notre guide sur les Webhooks pour un exemple.

### Exemple

{% hint style="warning" %}

* N'oubliez pas de remplacer `YOUR_SECRET_KEY` par votre véritable clé secrète.
* Tous les exemples suivants doivent être réalisés dans le backend, ne jamais exposer votre clé secrète au public.
  {% endhint %}

#### cURL

```bash
curl -X POST https://api.moneroo.io/v1/payments/initialize \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer YOUR_SECRET_KEY" \
     -H "Accept: application/json" \
     -d '{
         "amount": 100,
         "currency": "USD",
         "description": "Payment for order #123",
         "customer": {
             "email": "john@example.com",
             "first_name": "John",
             "last_name": "Doe"
         },
         "return_url": "https://example.com/payments/thank-you",
         "metadata": {
             "order_id": "123",
             "customer_id": "123"
         },
         "methods": ["qr_ngn", "bank_transfer_ngn"]
     }'
```


# Vérifier un transfert

Il existe trois façons de connaître le statut d'un transfert :

1. Confirmez que la référence de la transaction correspond à celle que vous avez générée.
2. Vérifiez l'exactitude du statut de la transaction. Le statut de la transaction doit être "success" pour les paiements réussis. Pour en savoir plus sur les statuts de transaction, consultez la section "Statut de transaction".
3. Vérifiez que la devise du transfert correspond à la devise attendue.

Assurez-vous que le montant payé est égal ou supérieur au montant prévu. Si le montant est supérieur, vous pouvez fournir au client la valeur correspondante et rembourser l'excédent.

Pour authentifier un paiement, utilisez la route de vérification d'une transaction `/v1/payments/{paymentId}/verify`, en spécifiant l'identifiant de la transaction dans l'URL. Vous pouvez obtenir l'ID de la transaction à partir du champ `data.id` dans la réponse après la création de la transaction, ainsi que dans le contenu du Webhook pour toute transaction.

### Requête

```bash
GET /v1/payments/{paymentId}/verify HTTP/1.1
Host: https://api.moneroo.io
Authorization: Bearer YOUR_SECRET_KEY
Content-Type: application/json
Accept: application/json
```

#### Paramètres

* Route: `/v1/payments/{paymentId}/verify`
* Méthode: `GET`

<table><thead><tr><th width="153">Nom</th><th width="140">Type</th><th width="94">Requis</th><th>Description</th></tr></thead><tbody><tr><td><code>paymentId</code></td><td>String</td><td>Oui</td><td>L'id de l'opération de transfert à vérifier.</td></tr></tbody></table>

### **Response Structure**

The response from this API endpoint will be in the standard Moneroo API response format. You'll get a response that looks like this:

```json
{
  "success": true,
  "message": "Payment transaction fetched successfully",
  "data": {
    // Details of the payment transaction
  }
}
```

En cas de requête réussie, la route de l'API retourne un code de statut HTTP 200 et les détails de la transaction de paiement dans le corps de la réponse.

S'il y a un problème avec votre requête, l'API renverra une réponse d'erreur. Le type de réponse d'erreur dépend de la nature du problème.

* **401 Unauthorized** : Cette erreur est renvoyée si vous n'avez pas fourni un jeton d'autorisation valide dans votre requête.
* **404 Not Found** : Cette erreur est renvoyée si l'ID de paiement fourni ne correspond à aucune transaction dans le système.
* **500 Internal Server Error** : Cette erreur indique un problème inattendu sur le serveur lors du traitement de votre requête.

### Considérations de sécurité

Cette route de l'API nécessite un jeton `Bearer` pour l'authentification. Le jeton `Bearer` doit être inclus dans l'en-tête Authorization de la requête. Assurez-vous que le jeton est gardé en sécurité et qu'il n'est ni partagé ni exposé de manière inappropriée.

### Exemple

{% hint style="warning" %}
Veuillez remplacer `payoutId` par l'identifiant de la transaction de paiement et `your_token` par votre jeton d'autorisation valide dans les extraits de code ci-dessous.
{% endhint %}

{% tabs %}
{% tab title="Curl" %}

```bash
curl --location --request GET 'https://api.moneroo.io/v1/payouts/{payoutId}/verify' \
--header 'Authorization: Bearer YOUR_TOKEN'
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php

$payoutId = 'your_payment_id';
$token = 'your_token';

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://api.moneroo.io/v1/payouts/{$payoutId}/verify",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer {$token}"
  ]
]);

$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ($httpCode === 200) {
  // Handle successful response
} else {
  // Handle error response
}

curl_close($curl);
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

payoutId = 'your_payment_id'
token = 'your_token'

headers = {
  'Authorization': f'Bearer {token}'
}

response = requests.get(f'https://api.moneroo.io/v1/payouts/{payoutId}/verify', headers=headers)

if response.status_code == 200:
  # Handle successful response
else:
  # Handle error response
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"fmt"
	"net/http"
)

func main() {
	payoutId := "your_payment_id"
	token := "your_token"

	url := fmt.Sprintf("https://api.moneroo.io/v1/payouts/%s/verify", paymentId)
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		// Handle error
	}

	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		// Handle error
	}
	defer resp.Body.Close()

	if resp.StatusCode == 200 {
		// Handle successful response
	} else {
		// Handle error response
	}
}
```

{% endtab %}

{% tab title="JavaScript (Node.js)" %}

```javascript
const axios = require("axios");

const paymentId = "your_payment_id";
const token = "your_token";

axios
  .get(`https://api.moneroo.io/v1/payouts/${payoutId}/verify`, {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  })
  .then((response) => {
    if (response.status === 200) {
      // Handle successful response
    } else {
      // Handle error response
    }
  })
  .catch((error) => {
    // Handle error
  });
```

{% endtab %}
{% endtabs %}

####

### Response example

You'll get a response that looks like this:

```json
{
  "success": true,
  "message": "Payout transaction fetched successfully",
  "data": {
    "id": "abc123",
    "status": "success",
    "is_processed": true,
    "processed_at": "2023-05-21T12:00:00Z",
    "amount": 100.0,
    "currency": "USD",
    "amount_formatted": "$100.00",
    "description": "Purchase of goods",
    "return_url": "https://example.com/return",
    "environment": "production",
    "initiated_at": "2023-05-21T11:00:00Z",
    "checkout_url": "https://example.com/checkout",
    "payment_phone_number": "+1234567890",
    "app": {
      "id": "app1",
      "name": "Example App",
      "icon_url": "https://example.com/icon.png"
    },
    "customer": {
      "id": "cust1",
      "first_name": "John",
      "last_name": "Doe",
      "email": "john.doe@example.com",
      "phone": "+1234567890",
      "address": "123 Main St",
      "city": "Springfield",
      "state": "IL",
      "country_code": "US",
      "country": "United States",
      "zip_code": "62701",
      "environment": "production",
      "created_at": "2023-01-01T00:00:00Z",
      "updated_at": "2023-05-21T00:00:00Z"
    },
    "method": {
      "name": "Credit Card",
      "code": "cc",
      "icon_url": "https://example.com/cc.png",
      "environment": "production"
    },
    "gateway": {
      "name": "Stripe",
      "account_name": "Acme Corp",
      "code": "stripe",
      "icon_url": "https://example.com/stripe.png",
      "environment": "production"
    },
    "metadata": {
      "custom_field1": "custom_value1",
      "custom_field2": "custom_value2"
    },
  }
}
```

The transaction details are contained in the data object. For instance:

* The status of the transaction is in `data.status`.
* The details of the customer are in the `data.customer` field.
* The data.amount field says how much the customer was charged.
* Some fields will vary depending on the type of transaction or state of the transaction.
* The data.method field contains the payment method used by the customer.
* The data.gateway field contains the payment gateway used to process the transaction.
* The data.metadata field contains any custom metadata you may have provided when creating the transaction.
* The data.context field contains the context of the transaction.
* The data.app field contains the app details.

| Field Name             | Description                                          |
| ---------------------- | ---------------------------------------------------- |
| `id`                   | The public ID of the transaction.                    |
| `status`               | The status of the transaction.                       |
| `is_processed`         | Indicates whether the transaction is processed.      |
| `processed_at`         | The time when the transaction was processed.         |
| `amount`               | The amount involved in the transaction.              |
| `currency`             | The currency used in the transaction.                |
| `amount_formatted`     | The formatted amount involved in the transaction.    |
| `description`          | The description of the transaction.                  |
| `return_url`           | The URL to return to after the transaction.          |
| `environment`          | The environment in which the transaction occurred.   |
| `initiated_at`         | The time when the transaction was initiated.         |
| `checkout_url`         | The URL to checkout the transaction.                 |
| `payment_phone_number` | The phone number associated with the payment method. |
| `app`                  | The app associated with the transaction.             |
| `customer`             | The customer associated with the transaction.        |
| `method`               | The payment method associated with the transaction.  |
| `gateway`              | The payment gateway associated with the transaction. |
| `metadata`             | The metadata associated with the transaction.        |
| `context`              | The context associated with the transaction.         |


# Récupérer un transfert

L'API de la plateforme Moneroo propose une route qui vous permet de récupérer les informations détaillées d'une transaction de transfert spécifique basée sur son identifiant unique de transaction.

\
Ce guide vous expliquera comment récupérer une transaction de reversement en utilisant l'API de Moneroo.

### Requête

```bash
GET /v1/payouts/{payoutId} HTTP/1.1
Host: https://api.moneroo.io
Authorization: Bearer YOUR_SECRET_KEY
Content-Type: application/json
Accept: application/json
```

#### Paramètres

* Route: `/v1/payouts/{payoutId}`
* Méthode: `GET`

<table><thead><tr><th width="200">Champ</th><th>Type</th><th>Requis</th><th>Description</th></tr></thead><tbody><tr><td><code>payoutId</code></td><td>String</td><td>Oui</td><td>Identifiant unique de transaction.sutr</td></tr></tbody></table>

### **Structure d'une réponse**

La réponse de cette route de l'API sera au format standard de réponse de l'API Moneroo.\
Vous recevrez une réponse qui ressemble à ceci :

```json
{
  "success": true,
  "message": "Payout transaction fetched successfully",
  "data": {
    // Details of the payout transaction
  }
}
```

**Réponse en cas de réussite** :\
En cas de récupération réussie, la route de l'API retourne un code de statut HTTP **200** et les détails de la transaction de paiement dans le corps de la réponse.

**Réponses en cas d'échec** :\
S'il y a un problème avec votre requête, l'API renverra une réponse d'erreur. Le type de réponse d'erreur dépend de la nature du problème. Consultez notre page sur le format des réponses pour plus d'informations.

### Considérations de sécurité

Cette route de l'API nécessite un *jeton Bearer* pour l'authentification. Le jeton Bearer doit être inclus dans l'en-tête `Authorization` de la requête. Assurez-vous que le jeton est gardé en sécurité et qu'il n'est ni partagé ni exposé de manière inappropriée.

### Exemple de requête

{% tabs %}
{% tab title="Curl" %}

```bash
curl --location --request GET 'https://api.moneroo.io/v1/payouts/{payoutId}' \
--header 'Authorization: Bearer YOUR_TOKEN'
```

{% endtab %}

{% tab title="JavaScript" %}

```javascript
const axios = require("axios");

const payoutId = "your_payout_public_id";
const token = "your_token";

axios
  .get(`https://api.moneroo.io/v1/payouts/${payoutId}`, {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  })
  .then((response) => {
    if (response.status === 200) {
      const data = response.data;
      // Handle successful response and retrieve the payout transaction details
    } else {
      // Handle error response
    }
  })
  .catch((error) => {
    // Handle error
  });
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

payout_public_id = 'your_payout_public_id'
token = 'your_token'

headers = {
  'Authorization': f'Bearer {token}'
}

response = requests.get(f'https://api.moneroo.io/v1/payouts/{payout_public_id}', headers=headers)

if response.status_code == 200:
  data = response.json()
  # Handle successful response and retrieve the payout transaction details
else:
  # Handle error response
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"fmt"
	"net/http"
	"io/ioutil"
)

func main() {
	payoutPublicID := "your_payout_public_id"
	token := "your_token"

	url := fmt.Sprintf("https://api.moneroo.io/v1/payouts/%s", payoutPublicID)
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		// Handle error
	}

	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		// Handle error
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		// Handle error
	}

	if resp.StatusCode == 200 {
		// Handle successful response and retrieve the payout transaction details
	} else {
		// Handle error response
	}
}
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php

$payoutId = 'your_payout_public_id';
$token = 'your_token';

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://api.moneroo.io/v1/payouts/{$payoutId}",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer {$token}"
  ]
]);

$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ($httpCode === 200) {
  $responseData = json_decode($response, true);
  // Handle successful response and retrieve the payout transaction details
} else {
  // Handle error response
}

curl_close($curl)
```

{% endtab %}
{% endtabs %}

Please replace `'payoutId'` with the actual payout transaction Id and `'your_token'` with your valid authorization token in the code snippets above.

### Exemple de réponse

Vous recevrez une réponse qui ressemble à ceci :

```json
{
  "success": true,
  "message": "Payout transaction fetched successfully",
  "data": {
    "id": "abc123",
    "status": "success",
    "is_processed": true,
    "processed_at": "2023-05-21T12:00:00Z",
    "amount": 100.0,
    "currency": "USD",
    "amount_formatted": "$100.00",
    "description": "Purchase of goods",
    "return_url": "https://example.com/return",
    "environment": "production",
    "initiated_at": "2023-05-21T11:00:00Z",
    "payout_phone_number": "+1234567890",
    "app": {
      "id": "app1",
      "name": "Example App",
      "icon_url": "https://example.com/icon.png"
    },
    "customer": {
      "id": "cust1",
      "first_name": "John",
      "last_name": "Doe",
      "email": "john.doe@example.com",
      "phone": "+1234567890",
      "address": "123 Main St",
      "city": "Springfield",
      "state": "IL",
      "country_code": "US",
      "country": "United States",
      "zip_code": "62701",
      "environment": "production",
      "created_at": "2023-01-01T00:00:00Z",
      "updated_at": "2023-05-21T00:00:00Z"
    },
    "method": {
      "name": "Credit Card",
      "code": "cc",
      "icon_url": "https://example.com/cc.png",
      "environment": "production"
    },
    "gateway": {
      "name": "Stripe",
      "account_name": "Acme Corp",
      "code": "stripe",
      "icon_url": "https://example.com/stripe.png",
      "environment": "production"
    },
    "metadata": {
      "custom_field1": "custom_value1",
      "custom_field2": "custom_value2"
    },
    "context": {
      "ip": "192.0.2.0",
      "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (HTML, like Gecko) Chrome/58.0.3029.110 Safari/537",
      "country": "US",
      "local": "en-US"
    }
  }
}
```

Le champ `data` contiendra les détails de la transaction. La structure et le contenu spécifiques de ce champ dépendent des détails de la transaction.


# Statut du transfert

Lorsqu'il s'agit de transfert, il est crucial de suivre leur progression. Pour ce faire efficacement, il est important de comprendre les différents statuts de transaction associés à chaque paiement. Chez Moneroo, nous avons catégorisé ces statuts en deux groupes : *transitoires* et *finaux*.

\
Vue simplifiée des statuts de transaction de reversement :

<figure><img src="/files/nkmQHwpywYQhREmbdkjy" alt=""><figcaption><p>Moneroo.io Payout Status</p></figcaption></figure>

| Statut      | Catégorie   | Description                                                                                                             |
| ----------- | ----------- | ----------------------------------------------------------------------------------------------------------------------- |
| `initiated` | Transitoire | La transaction de transfert a été initiée et est actuellement en file d'attente, en attente de traitement.              |
| `pending`   | Transitoire | La transaction de transfert a été traitée et est maintenant en attente d'un statut final de la passerelle ou du réseau. |
| `failed`    | Final       | La transaction a échoué, et c'est son statut final.                                                                     |
| `success`   | Final       | La transaction a été complétée avec succès, et c'est son statut final.                                                  |

En comprenant ces différents statuts de transaction de transfert, vous pourrez surveiller et gérer efficacement vos paiements avec facilité.


# Méthodes Disponibles

Vous trouverez ci-dessous une liste des méthodes de transfert que nous acceptons. Cette liste est en constante évolution, alors revenez nous voir pour des mises à jour.

Pour en savoir plus sur une méthode de transfert spécifique et sur la passerelle de transfert qui la prend en charge, veuillez consulter la section de votre [liste de connexions.](http://moneroo.io/connection)

{% hint style="info" %}
Vous pouvez obtenir une liste actualisée de toutes les méthodes de transfert disponibles en appelant la route [GET /utils/payout/methods](https://api.moneroo.io/utils/payout/methods).

{% code overflow="wrap" fullWidth="false" %}

```bash
GET /utils/payout/methods HTTP/1.1
Host: https://api.moneroo.io
Accept: application/json
```

{% endcode %}
{% endhint %}

***

### Méthodes de transfert

| Noms                       | Codes                 | Devises | Pays |
| -------------------------- | --------------------- | :-----: | :--: |
| MTN Mobile Money Bénin     | `mtn_bj`              |   XOF   |  BJ  |
| Moov Money Bénin           | `moov_bj`             |   XOF   |  BJ  |
| E-money Sénégal            | `e_money_sn`          |   XOF   |  SN  |
| Orange Money Sénégal       | `orange_sn`           |   XOF   |  SN  |
| Wave Sénégal               | `wave_sn`             |   XOF   |  SN  |
| Free Money Sénégal         | `freemoney_sn`        |   XOF   |  SN  |
| Orange Money Côte d'Ivoire | `orange_ci`           |   XOF   |  CI  |
| MTN MoMo Côte d'Ivoire     | `mtn_ci`              |   XOF   |  CI  |
| Moov Money Côte d'Ivoire   | `moov_ci`             |   XOF   |  CI  |
| Wave Côte d'Ivoire         | `wave_ci`             |   XOF   |  CI  |
| T-Money                    | `togocel`             |   XOF   |  TG  |
| Orange Money Mali          | `orange_ml`           |   XOF   |  ML  |
| Djamo Côte d'Ivoire        | `djamo_ci`            |   XOF   |  CI  |
| Djamo Sénégal              | `djamo_sn`            |   XOF   |  SN  |
| Transfert Demo Moneroo     | `moneroo_payout_demo` |   XOF   |  US  |

Nous ajoutons constamment de nouvelles méthodes de transfert. Si vous ne trouvez pas votre mode de transfert préféré, veuillez [nous contacter](https://moneroo.io/contact).

### Champs obligatoires

Chaque méthode de transfert a son propre ensemble de champs obligatoires, que vous devez fournir dans le corps de la demande lors de la création d'un transfert.

| Codes                 |      Champs      | Type    | Exemple      | Description                                                                               |
| --------------------- | :--------------: | ------- | ------------ | ----------------------------------------------------------------------------------------- |
| `mtn_bj`              |     `msisdn`     | integer | 22912345678  | MTN Mobile Money account phone number that will receive money in international format.    |
| `moov_bj`             |     `msisdn`     | integer | 22912345678  | MTN Mobile Money account phone number that will receive money in international format.    |
| `orange_sn`           |     `msisdn`     | integer | 22112345678  | Orange Money account phone number that will receive money in international format.        |
| `e_money_sn`          |     `msisdn`     | integer | 22112345678  | E-Money account phone number that will receive money in international format.             |
| `wave_sn`             |     `msisdn`     | integer | 22112345678  | Wave Senegal account phone number that will receive money in international format.        |
| `freemoney_sn`        |     `msisdn`     | integer | 22112345678  | FreeMoney account phone number that will receive money in international format.           |
| `orange_ci`           |     `msisdn`     | integer | 22512345678  | Orange Money account phone number that will receive money in international format.        |
| `mtn_ci`              |     `msisdn`     | integer | 22512345678  | MTN Mobile Money account phone number that will receive money in international format.    |
| `moov_ci`             |     `msisdn`     | integer | 22512345678  | Moov Money account phone number that will receive money in international format.          |
| `wave_ci`             |     `msisdn`     | integer | 22512345678  | Wave Ivory Coast account phone number that will receive money in international format.    |
| `togocel`             |     `msisdn`     | integer | 22812345678  | T-Money account phone number that will receive money in international format.             |
| `orange_ml`           |     `msisdn`     | integer | 22312345678  | Orange Money account phone number that will receive money in international format.        |
| `djamo_ci`            |     `msisdn`     | integer | 22512345678  | The msisdn of the Djamo client.                                                           |
| `djamo_sn`            |     `msisdn`     | integer | 22512345678  | The msisdn of the Djamo client.                                                           |
| `moneroo_payout_demo` | `account_number` | integer | 010101010101 | Moneroo Payout Demo account phone number that will receive money in international format. |


# Tests

Tester votre intégration est une étape cruciale pour garantir une expérience de transfert transparente avec Moneroo. Moneroo met à votre disposition un *environnement de test* dédié, vous permettant de valider votre intégration avant de la mettre en production. Dans le mode *sandbox*, vous pouvez simuler des transactions réelles sans traiter de vrais transferts.

Pour effectuer des tests dans l'environnement *sandbox*, vous utiliserez des clés spécifiques appelées **"clés sandbox"** ou **"clés de test"**. Ces clés sont distinctes des clés de production et sont destinées à des fins de test uniquement. Elles fournissent un environnement sécurisé et contrôlé pour expérimenter et valider votre intégration.

En utilisant les clés et l'environnement *sandbox* de Moneroo, vous pouvez tester en profondeur votre intégration, assurer la compatibilité et résoudre les problèmes éventuels avant de la déployer dans l'environnement de production réel.

> **Les données en&#x20;*****sandbox*****&#x20;sont automatiquement supprimées après&#x20;*****90 jours*****. Cela ne concerne que les transactions et les clients.**

### Processeur de transfert par défaut : Passerelle de transfert Moneroo Test

Par défaut, votre application Moneroo inclut la **"Passerelle de transfert test Moneroo"** comme passerelle de transfert par défaut dans l'environnement *sandbox*. Cette passerelle de transfert vous permet de simuler différents scénarios de transaction et d'observer comment votre système réagit dans chaque cas.

Pour simuler différents scénarios de transactions de transfert et tester en profondeur votre intégration, Moneroo fournit des *numéros de téléphone de test* spécifiques. Ces numéros peuvent être utilisés pour simuler des transactions réussies ou échouées, ce qui vous permet d'évaluer la manière dont votre système gère chaque scénario. Au cours de votre processus de test, vous pouvez utiliser ces numéros de téléphone de test pour imiter le comportement des transactions réelles et observer les réponses de votre intégration en fonction de vos besoins.

{% hint style="info" %}

* Les numéros de téléphone de test ne sont disponibles que pour la passerelle de transfert de test Moneroo et ne peuvent pas être utilisés avec d'autres passerelles de transfert en mode sandbox.
* Ces numéros peuvent être utilisés pour simuler leurs scénarios respectifs pour toutes les méthodes de transfert associées à la passerelle de transfert Moneroo Test.
  {% endhint %}

<table><thead><tr><th width="213">Numéro de téléphone</th><th>Scenario</th><th width="125">Devises</th><th>Pays</th></tr></thead><tbody><tr><td>4149518161</td><td>Transaction réussie</td><td>USD</td><td>US</td></tr><tr><td>4149518162</td><td>Transaction échouée</td><td>USD</td><td>US</td></tr><tr><td>4149518163</td><td>Transaction en attente</td><td>USD</td><td>US</td></tr></tbody></table>

### Test avec d'autres passerelles de transfert en mode Sandbox

Moneroo offre la possibilité d'intégrer d'autres passerelles de transfert en mode `sandbox`.

Pour chaque passerelle de transfert disponible dans en mode sandbox, vous devez consulter la documentation de la passerelle de transfert en question pour obtenir les instructions de test. Ces instructions vous fourniront les informations nécessaires sur la manière d'intégrer la passerelle de transfert, d'utiliser les clés de test ou les informations d'identification et de simuler différents scénarios de transaction spécifiques à cette passerelle de transfert.

Moneroo travaille continuellement à l'élargissement de la disponibilité des passerelles de transfert supportées dans en mode sandbox. Par conséquent, assurez-vous de rester informé des dernières annonces et mises à jour de Moneroo concernant les nouvelles intégrations et les options de test en sandbox.&#x20;

Voici des lien vers la documentation de chaque passerelle de transfert supportée en mode sandbox :

<table><thead><tr><th width="364">Payment Processor</th><th>Test Instructions</th></tr></thead><tbody><tr><td>KkiaPay (Sandbox)</td><td><a href="https://docs.kkiapay.me/v1/v/en-1.0.0/compte/kkiapay-sandbox-guide-de-test">View Instructions</a></td></tr><tr><td>Flutterwave (Test)</td><td><a href="https://developer.flutterwave.com/docs/integration-guides/testing-helpers">View Instructions</a></td></tr><tr><td>Paydunya (Sandbox)</td><td><a href="https://developers.paydunya.com/doc/EN/introduction#section-3">View Instructions</a></td></tr><tr><td>Paystack (Sandbox)</td><td><a href="https://paystack.com/docs/payments/test-payments/">View Instructions</a></td></tr><tr><td>Stripe (Sandbox)</td><td><a href="https://stripe.com/docs/testing">View Instructions</a></td></tr><tr><td>Fedapay (Sandbox)</td><td><a href="https://docs.fedapay.com/paiements/test">View Instructions</a></td></tr></tbody></table>


# PHP SDK

[![GitHub](https://img.shields.io/badge/GitHub-100000?style=for-the-badge\&logo=github\&logoColor=white)](https://github.com/MonerooHQ/moneroo-php) [![Star on GitHub](https://img.shields.io/badge/Star-GitHub-blue?style=for-the-badge\&logo=github)](https://github.com/MonerooHQ/moneroo-php/stargazers)\
[![PHP Version](https://img.shields.io/packagist/php-v/moneroo/moneroo-php.svg)](https://packagist.org/packages/moneroo/moneroo-php) [![Build Status](https://github.com/monerooHQ/moneroo-php/actions/workflows/run-tests.yml/badge.svg?branch=main)](https://github.com/moneroo/moneroo-php/actions?query=branch%3Amain) [![Latest Stable Version](https://poser.pugx.org/moneroo/moneroo-php/v/stable.svg)](https://packagist.org/packages/moneroo/moneroo-php) [![Total Downloads](https://poser.pugx.org/moneroo/moneroo-php/downloads.svg)](https://packagist.org/packages/moneroo/moneroo-php) [![License](https://poser.pugx.org/moneroo/moneroo-php/license.svg)](https://packagist.org/packages/moneroo/moneroo-php)

Le SDK Moneroo PHP est une bibliothèque complète qui permet aux développeurs PHP d'interagir avec le service d'orchestration des paiements Moneroo.

### Besoins

*PHP 7.4 et versions ultérieures.*

### Installation

Vous pouvez installer le paquet via `composer` :

```bash
composer require moneroo/moneroo-php
```

### Paiement

La classe `Moneroo\Payment` fournit des méthodes pour initialiser, vérifier, récupérer et marquer les paiements comme traités. Vous pouvez l'utiliser comme suit :

#### Initier le paiement

Pour créer un paiement, vous devez transmettre un tableau de données de paiement à la méthode de création. Le tableau doit contenir les clés suivantes :

Voici les champs obligatoires sous forme de tableau :

<table><thead><tr><th width="240">Nom des champs</th><th width="97">Type</th><th width="117">Obligatoire</th><th>Description</th></tr></thead><tbody><tr><td><code>amount</code></td><td>integer</td><td>Oui</td><td>Le montant du paiement.</td></tr><tr><td><code>currency</code></td><td>string</td><td>Oui</td><td>La devise du paiement.</td></tr><tr><td><code>description</code></td><td>string</td><td>Non</td><td>Description du paiement.</td></tr><tr><td><code>return_url</code></td><td>string</td><td>Oui</td><td>URL de retour où votre client sera redirigé après le paiement.</td></tr><tr><td><code>customer.email</code></td><td>string</td><td>Oui</td><td>Adresse e-mail du client.</td></tr><tr><td><code>customer.first_name</code></td><td>string</td><td>Oui</td><td>Prénom du client.</td></tr><tr><td><code>customer.last_name</code></td><td>string</td><td>Oui</td><td>Nom du client.</td></tr><tr><td><code>customer.phone</code></td><td>string</td><td>Non<strong>¹</strong></td><td>Numéro de téléphone du client dans le format <a href="https://en.wikipedia.org/wiki/E.164">E164</a>.</td></tr><tr><td><code>customer.address</code></td><td>string</td><td>Non<strong>¹</strong></td><td>Adresse du client.</td></tr><tr><td><code>customer.city</code></td><td>string</td><td>Non<strong>¹</strong></td><td>Ville du client.</td></tr><tr><td><code>customer.state</code></td><td>string</td><td>Non<strong>¹</strong></td><td>État du client.</td></tr><tr><td><code>customer.country</code></td><td>string</td><td>Non<strong>¹</strong></td><td>Pays du client. Il s'agir du code du pays au format <a href="https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2">ISO 3166-1 alpha-2</a> valide.</td></tr><tr><td><code>customer.zip</code></td><td>string</td><td>Non<strong>¹</strong></td><td>Code postal du client.</td></tr><tr><td><code>metadata</code></td><td>array</td><td>Non<strong>²</strong></td><td>Données supplémentaires pour le paiement.</td></tr><tr><td><code>methods</code></td><td>array</td><td>Non<strong>³</strong></td><td>Méthodes de paiement autorisées.</td></tr></tbody></table>

1. Si ces informations ne sont pas fournies, le client peut être invité à les saisir au cours de la procédure de paiement, en fonction de la méthode de paiement sélectionnée.
2. Il s'agit d'un tableau de paires clé-valeur. Seules les chaînes de caractères sont autorisées.
3. S'il n'est pas fourni, tous les modes de paiement disponibles seront autorisés. Le tableau ne doit contenir que les méthodes de paiement prises en charge.

**Exemple d'utilisation**

```php
$paymentData = [
    'amount' => 100,
    'currency' => 'USD',
    'customer' => [
        'email' => 'john.doe@example.com',
        'first_name' => 'John',
        'last_name' => 'Doe',
        'phone' => '123456789',
        'address' => '123 Main St',
        'city' => 'Los Angeles',
        'state' => 'CA',
        'country' => 'USA',
        'zip' => '90001',
    ],
    'description' => 'Payment for order #123',
    'return_url' => 'https://yourwebsite.com/thanks',
    'metadata' => [
        'order_id' => '123',
        'customer_id' => '456',
    ],
    'methods' => ['card', 'orange_ci'],
];
$monerooPayment = new \Moneroo\Payment($publicKey, $secretKey);
$payment = $monerooPayment->init($paymentData);

// Redirect the customer to the Checkout URL
header('Location: ' . $payment->checkout_url);

```

La méthode `create` renvoie un objet contenant les détails du paiement, y compris l'identifiant de la transaction et l'URL de paiement vers laquelle vous devez rediriger le client pour qu'il effectue le paiement. Vous pouvez utiliser cet identifiant de transaction pour vérifier le paiement ultérieurement.

#### Vérifier le paiement

Vous pouvez vérifier un paiement à l'aide de son `id`. Cette fonction est utile lorsque vous souhaitez vérifier l'état d'un paiement avant de traiter une commande de votre côté.

```php
$transactionId = 'your-payment-transaction-id';

$monerooPayment = new \Moneroo\Payment();
$payment = $monerooPayment->verify($transactionId);
```

#### Récupération du paiement

Pour obtenir les détails d'un paiement, utilisez la méthode `get` avec l'id de la transaction.

```php
$transactionId = 'your-payment-transaction-id';

$monerooPayment = new \Moneroo\Payment($publicKey, $secretKey);
$payment = $monerooPayment->get($transactionId);
```

#### Marquer le paiement comme traité

Il s'agit actuellement d'une fonctionnalité expérimentale. Veuillez l'utiliser avec prudence et signaler tout problème que vous rencontrez.

Cette méthode est utile lorsque vous souhaitez marquer un paiement comme étant traité après avoir reçu un rappel de l'API Moneroo et avoir traité la commande de votre côté. Cela vous permet également d'éviter les commandes en double ou de stocker les identifiants des transactions dans votre base de données pour référence ultérieure.

Pour marquer un paiement comme traité, utilisez la méthode `makeAsProcessed` avec l'id de la transaction.

Exemple d'usage :

```php
$transactionId = 'your-payment-transaction-id';

$monerooPayment = new \Moneroo\Payment($publicKey, $secretKey);
$payment = $monerooPayment->makeAsProcessed($transactionId);
```

### Transfert

La classe `Moneroo\Payout` fournit des méthodes d'initialisation, de vérification et de récupération des paiements.

#### Initier le paiement

Pour initialiser un tranfert, vous devez transmettre un tableau de données répondant aux règles de validation spécifiées. Le tableau doit contenir les clés suivantes :

Voici les champs obligatoires sous forme de tableau :

<table><thead><tr><th width="257">Nom des champs</th><th width="91">Type</th><th width="120">Obligatoire</th><th>Description</th></tr></thead><tbody><tr><td><code>amount</code></td><td>integer</td><td>Oui</td><td>Le montant du transfert.</td></tr><tr><td><code>currency</code></td><td>string</td><td>Oui</td><td>La devise du transfert. La devise doit être une devise prise en charge dans un format <a href="https://en.wikipedia.org/wiki/ISO_4217">ISO 4217</a> valide.</td></tr><tr><td><code>description</code></td><td>string</td><td>Oui</td><td>Description du transfert.</td></tr><tr><td><code>customer.email</code></td><td>string</td><td>Oui</td><td>Adresse e-mail du client.</td></tr><tr><td><code>customer.first_name</code></td><td>string</td><td>Oui</td><td>Prénom du client.</td></tr><tr><td><code>customer.last_name</code></td><td>string</td><td>Oui</td><td>Nom du client.</td></tr><tr><td><code>return_url</code></td><td>string</td><td>Oui</td><td>URL de retour où votre client sera redirigé après le transfert.</td></tr><tr><td><code>customer.phone</code></td><td>string</td><td>Non</td><td>Numéro de téléphone du client dans le format <a href="https://en.wikipedia.org/wiki/E.164">E164</a>.</td></tr><tr><td><code>customer.address</code></td><td>string</td><td>Non</td><td>Adresse du client.</td></tr><tr><td><code>customer.city</code></td><td>string</td><td>Non</td><td>Ville du client.</td></tr><tr><td><code>customer.state</code></td><td>string</td><td>Non</td><td>État du client.</td></tr><tr><td><code>customer.country</code></td><td>string</td><td>Non</td><td>Pays du client. Il s'agir du code du pays au format <a href="https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2">ISO 3166-1 alpha-2</a> valide.</td></tr><tr><td><code>customer.zip</code></td><td>string</td><td>Non</td><td>Code postal du client.</td></tr><tr><td><code>metadata</code></td><td>array</td><td>Non</td><td>Données supplémentaires pour le transfert.</td></tr><tr><td><code>method</code></td><td>string</td><td>Oui<strong>¹</strong></td><td>Méthodes de transfert autorisées </td></tr><tr><td><code>request_confirmation</code><strong>²</strong></td><td>bool</td><td>Non</td><td>Si vous souhaitez demander une confirmation au client.</td></tr></tbody></table>

{% hint style="info" %}

1. &#x20;Il s'agit d'une [méthode de transfert](/fr/payouts/methodes-disponibles) supportée par Moneroo
2. Cette fonctionnalité est actuellement en phase expérimentale et n'est pas disponible pour tous les utilisateurs/applications. Elle vous permet de demander une confirmation à un client avant de procéder au transfert. Moneroo enverra un e-mail au client contenant un code de confirmation. Le client est alors dirigé vers une page de confirmation où il peut vérifier le montant du paiement et les détails de son compte. Si les informations sont correctes, le client peut saisir le code de confirmation pour approuver ou rejeter la demande de paiement. Cette fonction est un outil précieux pour éviter les informations incorrectes ou les transactions frauduleuses. Si l'utilisateur ne répond pas dans les 15 minutes, la demande de paiement sera automatiquement annulée.
   {% endhint %}

En plus des informations ci-dessus, vous devez ajouter des champs obligatoires pour les méthodes de tranfert dans les détails du compte. Par exemple, si le mode de paiement est `mtn_bj`, vous devez fournir les champs `msisdn.`

Il s'agit d'une information différente de celle de l'utilisateur, qui indique où l'argent sera versé. Pour plus d'informations, veuillez consulter les champs obligatoires pour chaque méthode de transfert.

```php
$payoutData = [
    'amount' => 100,
    'currency' => 'USD',
    'customer' => [
        'email' => 'john.doe@example.com',
        'first_name' => 'John',
        'last_name' => 'Doe',
        // other customer details...
    ],
    'description' => 'Salary payment',
    'method' => 'mtn_bj',
    'msisdn' => '22912345678', // required field for mtn_bj payout method
    // other data...
];

$monerooPayout = new Moneroo\Payout($publicKey, $secretKey);
$payout = $monerooPayout->init($payoutData);
```

La méthode `create` renvoie un objet contenant les détails du paiement, y compris l'id de la transaction et le statut du paiement. Vous pouvez utiliser cet identifiant de transaction pour vérifier le paiement ultérieurement.

#### Vérifier le transfert

Vous pouvez vérifier un tranfert grâce à l'id de la transaction.

```php
$transactionId = 'your-payout-transaction-id';

$monerooPayout = new Moneroo\Payout($publicKey, $secretKey);
$payout = $monerooPayout->verify($transactionId);
```

#### Récupérer le tranfert

Pour obtenir les détails d'un tranfert, utilisez la méthode `get` avec l'id de la transaction.

```php
$transactionId = 'your-payout-transaction-id';

$payout = new \Moneroo\Payout($publicKey, $secretKey);
$payout = $payout->get($transactionId);
```

### Traitement des exceptions

Le SDK est livré avec un certain nombre d'exceptions personnalisées pour vous aider à gérer les erreurs potentielles qui peuvent survenir lors de l'utilisation de l'API Moneroo. Ces exceptions sont les suivantes :

* **InvalidPayloadException** : Cette exception est déclenchée lorsque la charge utile envoyée à l'API ne répond pas aux critères attendus.
* **ForbiddenException** : Cette exception est déclenchée lorsque l'utilisateur authentifié tente d'effectuer une action pour laquelle il ne dispose pas des autorisations nécessaires.
* **InvalidResourceException** : Cette exception est déclenchée lorsqu'une requête est adressée à une ressource inexistante ou invalide.
* **ServerErrorException** : Cette exception est déclenchée en cas d'erreur du côté du serveur.
* **NotAcceptableException** : Cette exception est déclenchée lorsque les caractéristiques du contenu de la demande du client ne sont pas acceptables selon les en-têtes Accept envoyés dans la demande.
* **ServiceUnavailableException** : Cette exception est déclenchée lorsque le service est actuellement indisponible, peut-être en raison de problèmes de maintenance ou de charge sur le serveur.
* **UnauthorizedException** : Cette exception est levée lorsque la demande ne comporte pas d'informations d'authentification valides pour la ressource cible.

Pour chaque exception, vous pouvez accéder au message d'erreur en appelant`$exception->getMessage()`, et au code d'erreur (s'il est disponible) en appelant`$exception->getCode()`.

### Support

Si vous avez des questions ou besoin d'aide, n'hésitez pas à [nous contacter](https://moneroo.io/contact). Nous sommes toujours heureux de répondre à vos questions.

### Vulnérabilités sécuritaires

Si vous découvrez une faille de sécurité dans le SDK PHP de Moneroo, veuillez envoyer un e-mail à Moneroo Security via <security@moneroo.io>. Toutes les failles de sécurité seront traitées rapidement.

### Licence

Le SDK Moneroo PHP est un logiciel libre sous licence MIT.


# Laravel SDK

[![PHP Version](https://img.shields.io/packagist/php-v/moneroo/moneroo-laravel.svg)](https://packagist.org/packages/moneroo/moneroo-laravel) [![Build Status](https://github.com/moneroohq/moneroo-laravel/actions/workflows/run-tests.yml/badge.svg?branch=main)](https://github.com/moneroohq/moneroo-laravel/actions?query=branch%3Amain) ![Latest Stable Version](https://poser.pugx.org/moneroohq/moneroo-laravel/v/stable.svg) [![Total Downloads](https://poser.pugx.org/moneroo/moneroo-laravel/downloads.svg)](https://packagist.org/packages/moneroo/moneroo-laravel) [![License](https://poser.pugx.org/moneroo/moneroo-laravel/license.svg)](https://packagist.org/packages/moneroo/moneroo-laravel)

Le SDK Moneroo Laravel est une bibliothèque complète qui permet aux développeurs Laravel d'interagir avec le service d'orchestration des paiements Moneroo.

### Besoins

Laravel 9.0 ou plus récent, PHP requise : PHP 8.1 et plus

### Installation

Vous pouvez installer le paquet via composer :

```bash
composer require moneroo/moneroo-laravel
```

#### Commande d'installation

Le paquetage fournit une commande pratique pour installer le SDK Moneroo Laravel et publier sa configuration dans votre projet Laravel. Après avoir installé le paquet via composer, vous pouvez exécuter cette commande :

```bash
php artisan moneroo:install
```

Cette commande va :

1. Publier un fichier `moneroo.php` dans votre répertoire de configuration
2. Ajoutez à votre fichier `.env` les variables `MONEROO_PUBLIC_KEY` et `MONEROO_SECRET_KEY` si elles n'existent pas déjà.

Vous devrez remplacer 'your-public-key' et 'your-secret-key' par votre clé publique et votre clé secrète Moneroo.

```env
MONEROO_PUBLIC_KEY=your-public-key
MONEROO_SECRET_KEY=your-secret-key
```

Gardez à l'esprit qu'il s'agit de clés sensibles et qu'elles ne doivent pas être exposées publiquement. Le fichier `.env` de Laravel est ignoré par Git, ce qui en fait un bon endroit pour stocker des informations sensibles.

### Paiement

La classe `Moneroo\Payment` fournit des méthodes pour initialiser, vérifier, récupérer et marquer les paiements comme traités. Vous pouvez l'utiliser comme suit :

#### Initier le paiement

Pour créer un paiement, vous devez transmettre un tableau de données de paiement à la méthode de création. Le tableau doit contenir les clés suivantes :

Voici les champs obligatoires sous forme de tableau :

<table><thead><tr><th width="241">Nom des champs</th><th width="98">Type</th><th width="130">Obligatoire</th><th>Description</th></tr></thead><tbody><tr><td><code>amount</code></td><td>integer</td><td>Oui</td><td>Le montant du paiement.</td></tr><tr><td><code>currency</code></td><td>string</td><td>Oui</td><td>La devise du paiement.</td></tr><tr><td><code>description</code></td><td>string</td><td>Non</td><td>Description du paiement.</td></tr><tr><td><code>return_url</code></td><td>string</td><td>Oui</td><td>URL de retour où votre client sera redirigé après le paiement.</td></tr><tr><td><code>customer.email</code></td><td>string</td><td>Oui</td><td>Adresse e-mail du client.</td></tr><tr><td><code>customer.first_name</code></td><td>string</td><td>Oui</td><td>Prénom du client.</td></tr><tr><td><code>customer.last_name</code></td><td>string</td><td>Oui</td><td>Nom du client.</td></tr><tr><td><code>customer.phone</code></td><td>string</td><td>Non<strong>¹</strong></td><td>Numéro de téléphone du client dans le format <a href="https://en.wikipedia.org/wiki/E.164">E164</a>.</td></tr><tr><td><code>customer.address</code></td><td>string</td><td>Non<strong>¹</strong></td><td>Adresse du client.</td></tr><tr><td><code>customer.city</code></td><td>string</td><td>Non<strong>¹</strong></td><td>Ville du client.</td></tr><tr><td><code>customer.state</code></td><td>string</td><td>Non<strong>¹</strong></td><td>État du client.</td></tr><tr><td><code>customer.country</code></td><td>string</td><td>Non<strong>¹</strong></td><td>Pays du client. Il s'agir du code du pays au format <a href="https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2">ISO 3166-1 alpha-2</a> valide.</td></tr><tr><td><code>customer.zip</code></td><td>string</td><td>Non<strong>¹</strong></td><td>Code postal du client.</td></tr><tr><td><code>metadata</code></td><td>array</td><td>Non<strong>²</strong></td><td>Données supplémentaires pour le paiement.</td></tr><tr><td><code>methods</code></td><td>array</td><td>Non<strong>³</strong></td><td>Méthodes de paiement autorisées.</td></tr></tbody></table>

1. Si ces informations ne sont pas fournies, le client peut être invité à les saisir au cours de la procédure de paiement, en fonction de la méthode de paiement sélectionnée.
2. Il s'agit d'un tableau de paires clé-valeur. Seules les chaînes de caractères sont autorisées.
3. S'il n'est pas fourni, tous les modes de paiement disponibles seront autorisés. Le tableau ne doit contenir que les méthodes de paiement prises en charge.

**Exemple d'utilisation**

```php
$paymentData = [
    'amount' => 100,
    'currency' => 'USD',
    'customer' => [
        'email' => 'john.doe@example.com',
        'first_name' => 'John',
        'last_name' => 'Doe',
        'phone' => '123456789',
        'address' => '123 Main St',
        'city' => 'Los Angeles',
        'state' => 'CA',
        'country' => 'USA',
        'zip' => '90001',
    ],
    'description' => 'Payment for order #123',
    'return_url' => 'https://yourwebsite.com/thanks',
    'metadata' => [
        'order_id' => '123',
        'customer_id' => '456',
    ],
    'methods' => ['card', 'orange_ci'],
];
$monerooPayment = new Moneroo\Payment();
$payment = $monerooPayment->init($paymentData);

// Redirect the customer to the Checkout URL
header('Location: ' . $payment->checkout_url);

```

La méthode `create` renvoie un objet contenant les détails du paiement, y compris l'identifiant de la transaction et l'URL de paiement vers laquelle vous devez rediriger le client pour qu'il effectue le paiement. Vous pouvez utiliser cet identifiant de transaction pour vérifier le paiement ultérieurement.

#### Vérifier le paiement

Vous pouvez vérifier un paiement à l'aide de son `id`. Cette fonction est utile lorsque vous souhaitez vérifier l'état d'un paiement avant de traiter une commande de votre côté.

```php
$transactionId = 'your-payment-transaction-id';

$monerooPayment = new Moneroo\Payment();
$payment = $monerooPayment->verify($transactionId);
```

#### Récupération du paiement

Pour obtenir les détails d'un paiement, utilisez la méthode `get` avec l'id de la transaction.

```php
$transactionId = 'your-payment-transaction-id';

$monerooPayment = new Moneroo\Payment();
$payment = $monerooPayment->get($transactionId);
```

#### Marquer le paiement comme traité

Il s'agit actuellement d'une *fonctionnalité expérimentale*. Veuillez l'utiliser avec prudence et signaler tout problème que vous rencontrez.

Cette méthode est utile lorsque vous souhaitez marquer un paiement comme étant traité après avoir reçu un rappel de l'API Moneroo et avoir traité la commande de votre côté. Cela vous permet également d'éviter les commandes en double ou de stocker les identifiants des transactions dans votre base de données pour référence ultérieure.

Pour marquer un paiement comme traité, utilisez la méthode `makeAsProcessed` avec l'id de la transaction.

Exemple :

```php
$transactionId = 'your-payment-transaction-id';

$monerooPayment = new Moneroo\Payment();
$payment = $monerooPayment->makeAsProcessed($transactionId);
```

### Transfert

La classe `Moneroo\Payout` fournit des méthodes d'initialisation, de vérification et de récupération des paiements.

#### Initier le tranfert

Pour initialiser un tranfert, vous devez transmettre un tableau de données répondant aux règles de validation spécifiées. Le tableau doit contenir les clés suivantes :

Voici les champs obligatoires sous forme de tableau :

1. Il s'agit d'une [méthode de transfert](/fr/payouts/methodes-disponibles) supportée par Moneroo
2. Cette fonctionnalité est actuellement en phase expérimentale et n'est pas disponible pour tous les utilisateurs/applications. Elle vous permet de demander une confirmation à un client avant de procéder au transfert. Moneroo enverra un e-mail au client contenant un code de confirmation. Le client est alors dirigé vers une page de confirmation où il peut vérifier le montant du paiement et les détails de son compte. Si les informations sont correctes, le client peut saisir le code de confirmation pour approuver ou rejeter la demande de paiement. Cette fonction est un outil précieux pour éviter les informations incorrectes ou les transactions frauduleuses. Si l'utilisateur ne répond pas dans les 15 minutes, la demande de paiement sera automatiquement annulée.

En plus des informations ci-dessus, vous devez ajouter des champs obligatoires pour les méthodes de tranfert dans les détails du compte. Par exemple, si le mode de paiement est`mtn_bj`, vous devez fournir des champs pour le`phone.`

Il s'agit d'une information différente de celle de l'utilisateur, qui indique où l'argent sera versé. Pour plus d'informations, veuillez consulter les champs obligatoires pour chaque méthode de transfert.

```php
$payoutData = [
    'amount' => 100,
    'currency' => 'USD',
    'customer' => [
        'email' => 'john.doe@example.com',
        'first_name' => 'John',
        'last_name' => 'Doe',
        // other customer details...
    ],
    'description' => 'Payout for order #123',
    'method' => 'bank_transfer',
    // other data...
];

$monerooPayout = new Moneroo\Payout();
$payout = Moneroo\Payout::init($payoutData);
```

La méthode `create` renvoie un objet contenant les détails du paiement, y compris l'id de la transaction et le statut du paiement. Vous pouvez utiliser cet identifiant de transaction pour vérifier le paiement ultérieurement.

#### Vérifier le transfert

Vous pouvez vérifier un tranfert grâce à l'id de la transaction.

```php
$transactionId = 'your-payout-transaction-id';

$payout = Moneroo\Payout::verify($transactionId);
```

#### Récupérer le paiement

Pour obtenir les détails d'un tranfert, utilisez la méthode `get` avec l'id de la transaction.

```php
$transactionId = 'your-payout-transaction-id';

$payout = Moneroo\Payout::get($transactionId);
```

Exemple d'usage:

```php
$payout = new Moneroo\Payout();
$response = $payout->get('your-payout-transaction-id');
```

### Traitement des exceptions

Le SDK est livré avec un certain nombre d'exceptions personnalisées pour vous aider à gérer les erreurs potentielles qui peuvent survenir lors de l'utilisation de l'API Moneroo. Ces exceptions sont les suivantes :

* **InvalidPayloadException** : Cette exception est déclenchée lorsque la charge utile envoyée à l'API ne répond pas aux critères attendus.
* **ForbiddenException** : Cette exception est déclenchée lorsque l'utilisateur authentifié tente d'effectuer une action pour laquelle il ne dispose pas des autorisations nécessaires.
* **InvalidResourceException** : Cette exception est déclenchée lorsqu'une requête est adressée à une ressource inexistante ou invalide.
* ServerErrorException : Cette exception est déclenchée en cas d'erreur du côté du serveur.
* **NotAcceptableException** : Cette exception est déclenchée lorsque les caractéristiques du contenu de la demande du client ne sont pas acceptables selon les en-têtes Accept envoyés dans la demande.
* **ServiceUnavailableException** : Cette exception est déclenchée lorsque le service est actuellement indisponible, peut-être en raison de problèmes de maintenance ou de charge sur le serveur.
* **UnauthorizedException** : Cette exception est levée lorsque la demande ne comporte pas d'informations d'authentification valides pour la ressource cible.

Pour chaque exception, vous pouvez accéder au message d'erreur en appelant`$exception->getMessage()`, et au code d'erreur (s'il est disponible) en appelant`$exception->getCode()`.

### Support

Si vous avez des questions ou besoin d'aide, n'hésitez pas à [nous contacter](https://moneroo.io/contact). Nous sommes toujours heureux de répondre à vos questions.

### Vulnérabilités sécuritaires

Si vous découvrez une faille de sécurité dans le SDK Laravel de Moneroo, veuillez envoyer un e-mail à Moneroo Security via <security@moneroo.io>. Toutes les failles de sécurité seront traitées rapidement.

### Licence

Le SDK Moneroo Laravel est un logiciel libre sous licence MIT.


# WooCommerce

### Vue d'ensemble

Moneroo est une plateforme d'orchestration de paiement polyvalente conçue pour rationaliser les transactions en ligne en fournissant un point d'intégration unique pour de multiples fournisseurs de paiement.&#x20;

Le plugin Moneroo WooCommerce apporte cette flexibilité et cette commodité à votre boutique WordPress eCommerce, vous permettant d'accepter une variété de méthodes de paiement avec facilité. Ce guide vous guide à travers les étapes d'installation et de configuration du plugin Moneroo pour votre boutique WooCommerce.

### Pré-requis

* Un site web WordPress avec WooCommerce installé et activé
* Accès au tableau de bord de WordPress.
* Fichier ZIP du plugin Moneroo ou accès via le dépôt de plugins WordPress.

### Étapes de l'installation

#### Méthode 1 : Installation via le dépôt de plugins WordPress

[Regardez cette vidéo ](https://www.youtube.com/watch?v=9QZ1f5XVj4M)pour apprendre comment installer le plugin Moneroo pour WooCommerce via le dépôt de plugins WordPress. Connectez-vous au tableau de bord de WordPress : Accédez au tableau de bord de l'administrateur de WordPress.

1. Naviguer vers Plugins: Cliquez sur Plugins > Ajouter un nouveau.
2. Rechercher Moneroo: Utilisez la barre de recherche pour trouver "Moneroo".
3. Installer et activer : Cliquez sur Installer maintenant à côté de Moneroo, puis cliquez sur Activer.

#### Méthode 2 : Installation manuelle via le fichier ZIP

{% hint style="info" %}
[Regardez cette vidéo](https://www.youtube.com/watch?v=9QZ1f5XVj4M) pour apprendre comment installer manuellement le plugin Moneroo pour WooCommerce via le fichier ZIP.
{% endhint %}

1. Télécharger le plugin : Téléchargez le fichier ZIP du plugin de la passerelle de paiement Moneroo. Télécharger le fichier ZIP du plugin [ici](https://cdn.moneroo.io/plugins/moneroo-woocommerce.zip)
2. Télécharger le plugin : **Allez dans Plugins** > **Ajouter un nouveau** > **Télécharger Plugin**. Sélectionnez le fichier ZIP et cliquez sur Installer maintenant.

<figure><img src="/files/xSKaBCwbyHp2L5QUF8JB" alt=""><figcaption></figcaption></figure>

1. Activez le plugin : Cliquez sur **Activer le plugin** une fois l'installation terminée. wordpress-activate.png

<figure><img src="/files/QKGucvhvAytPD6SAl7qX" alt=""><figcaption></figcaption></figure>

### Configuration

[Regardez cette vidéo](https://www.youtube.com/watch?v=9QZ1f5XVj4M) pour apprendre à configurer le plugin Moneroo pour WooCommerce.

#### Activer Moneroo

* Naviguez vers **WooCommerce** > **Paramètres**
* Cliquez sur l'onglet Paiements.&#x20;

<figure><img src="/files/XyeCyy5Vg9jRIbq0h9Un" alt=""><figcaption></figcaption></figure>

* Recherchez "Moneroo" et cliquez sur Gérer ou Configurer. Activez Moneroo en cochant la case "Activer Moneroo" et cliquez sur "Enregistrer les modifications".

<figure><img src="/files/iUVjbVdKlUgoWjSsUmAl" alt=""><figcaption></figcaption></figure>

#### Configuration des identifiants de l'API

1. Allez sur le [Tableau de bord Moneroo](https://app.moneroo.io/) > **Développeurs** > **API Keys** et créez une nouvelle clé API.
2. Créez une "clé publique" et une "clé secrète", et saisissez-les dans les champs correspondants.
3. Vous pouvez nommer la clé API comme vous le souhaitez (par exemple "Clé publique / clé secrète de ma boutique WooCommerce")

#### Configuration de Webhook

Moneroo utilise des Webhooks pour notifier à votre boutique le succès ou l'échec d'un paiement. Ceci est très utile pour mettre à jour le statut de la commande dans votre boutique lorsque les clients ne sont pas redirigés vers votre boutique après le paiement, comme c'est le cas avec certaines méthodes de paiement.

1. Dans les pages de configuration de Moneroo dans votre magasin, nous fournissons déjà une **URL de Webhook** et une clé secrète que vous pouvez utiliser.
2. Copiez l'URL du webhook et la clé secrète du webhook, et allez sur le [Tableau de bord Moneroo](https://app.moneroo.io/) > **Développeurs** > **Webhooks**.
3. Cliquez sur **Ajouter Webhook** et remplissez le formulaire avec les détails suivants :

* **URL**: l'URL du Webhook.
* **Secret**: La clé secrète utilisée pour signer le contenu du Webhook.

#### Enregistrer les configurations

Cliquez sur **Enregistrer les modifications** pour sauvegarder les configurations.

**Test du Paiement**

Testez le paiement en passant une commande dans votre boutique et en effectuant le paiement.&#x20;

C'est fait ! Vous avez installé et configuré avec succès le plugin Moneroo pour votre boutique WooCommerce.

### Autres réglages

Le plugin Moneroo pour WooCommerce dispose d'autres paramètres que vous pouvez configurer en fonction de vos besoins.

* **Titre**: Titre de la méthode de paiement affichée aux clients lors du paiement.
* **Description**: La description de la méthode de paiement affichée aux clients lors du paiement.
* Les champs **Titre** et **Description** sont facultatifs. Si vous les laissez vides, les valeurs par défaut seront utilisées.
* N'oubliez pas de cliquer sur **Enregistrer les modifications** après avoir modifié les paramètres.

### Support

Si vous avez des questions ou besoin d'aide, n'hésitez pas à [nous contacter](https://moneroo.io/contact). Nous sommes toujours heureux de répondre à vos questions.


