An open API service indexing awesome lists of open source software.

https://github.com/ainsleydev/mondu-trade-woocommerce

Wordpress Plugin for integrating Digital Trade Accounts into WooCommerce via the Mondu API
https://github.com/ainsleydev/mondu-trade-woocommerce

ecommerce mondu php woocommerce wordpress

Last synced: about 1 month ago
JSON representation

Wordpress Plugin for integrating Digital Trade Accounts into WooCommerce via the Mondu API

Awesome Lists containing this project

README

          


Errors Logo

Mondu Trade Account - WooCommerce

![GitHub Release](https://img.shields.io/github/v/release/ainsleydev/mondu-trade-woocommerce?display_name=release&style=flat&cacheSeconds=3600)
[![GNU General Public License 3.0](https://img.shields.io/github/license/ainsleyclark/squidge.svg)](https://www.gnu.org/licenses/gpl-3.0.en.html)
[![WP CS Check](https://github.com/ainsleydev/mondu-trade-woocommerce/actions/workflows/lint.yaml/badge.svg?branch=main)](https://github.com/ainsleydev/mondu-trade-woocommerce/actions/workflows/lint.yaml)
[![Security](https://github.com/ainsleydev/mondu-trade-woocommerce/actions/workflows/security.yaml/badge.svg)](https://github.com/ainsleydev/mondu-trade-woocommerce/actions/workflows/security.yaml)
[![ainsley.dev](https://img.shields.io/badge/-ainsley.dev-black?style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QA/wD/AP+gvaeTAAAAB3RJTUUH5wEYDzUGL1b35AAABA1JREFUWMPtlttvFVUUxn977ZnZu+W0tLalqRovBAUvQag0xNQbpSIosSSIJC198YknJfHJxDf9A/DBJ0x8MbFACjVqvCASq6FYFLFBvJAaAomkFCmhHGpLO+PDzOmZzpn2nKP4pCs5ycmevb7vW99as/fA//FfD1XO5p1nzuA3NWJHx5T8cVkRBPHHQfRjd0tzyZhOOQIy27bAxET9zCuvvhY0r2kC/OiRABeAN4BL/4oDr9+3lGszPs7UVNfUE23v3Nj5koszR/8N4EXg3XJckF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UFdACNKRsHgZMA6v0j5ZpAlPtNyvqSiJO/AKik60y0ALlUAAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDIzLTAxLTI0VDE1OjUzOjA2KzAwOjAwm5vntAAAACV0RVh0ZGF0ZTptb2RpZnkAMjAyMy0wMS0yNFQxNTo1MzowNiswMDowMOrGXwgAAABXelRYdFJhdyBwcm9maWxlIHR5cGUgaXB0YwAAeJzj8gwIcVYoKMpPy8xJ5VIAAyMLLmMLEyMTS5MUAxMgRIA0w2QDI7NUIMvY1MjEzMQcxAfLgEigSi4A6hcRdPJCNZUAAAAASUVORK5CYII=)](https://ainsley.dev)
[![Twitter](https://img.shields.io/twitter/follow/ainsleydev)](https://twitter.com/ainsleydev)

## Overview

The Mondu Trade Account - WooCommerce plugin integrates Mondu's Digital Trade Account functionality into your
WooCommerce store, allowing your customers to apply for and manage trade accounts directly during checkout.

- ✅ **Trade Account Applications**: Let customers apply for a trade account while completing their order.
- ✅ **Webhook Integration**: Automatically update customer statuses (e.g., accepted, pending, declined) when a customer
has applied for a Digital Trade Account.
- ✅ **Custom Styling and Actions**: Easily extend and customize the checkout experience with hooks and filters. Allowing
you to run actions when a buyer has been accepted or declined.
- ✅ **Admin Management Tools**: Access customer trade account information, logs, and webhook settings from the WordPress
admin panel.
- ✅ **Secure and Compliant**: Fully supports WooCommerce standards and uses secure connections for API communication.

## Installation

You can either download a the zip file from the releases section or locate it on the WordPress Plugin install page.

## Prerequisites

Before installing and using the Mondu Trade Account - WooCommerce plugin, ensure your environment meets the following
requirements:

- **WordPress**: Requires at least version `6.7`
- **PHP**: Requires at least version `7.4`
- **WooCommerce**: Requires at least version `9.4`
- **Mondu Plugin** Needs to be installed, tested version `3.0.3`

## Backwards Compatibility

This plugin has direct dependency on the `Mondu Plugin`. Before updating both plugins, always test the new version on a
staging environment to ensure compatibility with your customizations, integrations, and WooCommerce setup.

Useful Links:

- [Official GitHub Repository](https://github.com/mondu-ai/bnpl-checkout-woocommerce)
- [Changelog](https://github.com/mondu-ai/bnpl-checkout-woocommerce/blob/main/changelog.txt)

## Buyer States

There are a total of 6 buyer states that a user can be in. If you are admin of the WordPress install, you can change
these states, but it's recommended not to.

| State | Explanation |
|:------------|:-------------------------------------------------------------------------------------------------|
| `unknown` | The default status, when no the customer hasn't signed up yet. |
| `applied` | Customer has tried to apply for a Trade Account, but the webhook hasn't been triggered. |
| `accepted` | Customer has been approved a Trade Account and should have a buyer limit. |
| `pending` | Customer is waiting to hear from Mondu if their account has been accepted (Maximum of 48 hours). |
| `declined` | Customer has been flat-out refused credit from Mondu. |
| `cancelled` | Customer exited out of the Mondu Trade Application form. |

## Sandbox

If you have sandbox mode set on the `Mondu` plugin, you can test the following states with the email addresses listed
below. Note that if an email does not follow this convention, the trade application will fail.

- **`Accepted`**: accepted.good.{random-string}@example.com
- **`Pending`**: pending.pending-brc.{random-string}@example.com
- **`Declined`**: declined.bad.{random-string}@example.com

Note that emails are sent via the Mondu internal inbox in sandbox mode, in order to see them, it's best to reach out to
Mondu.

## Webhooks

Mondu send buyer webhooks when a user has applied for a Trade Account. The following payload will be provided via this
webhook once buyer onboarding requested is processed. See [here](https://docs.mondu.ai/reference/webhooks-overview) for
more details.

If the webhook failed, Mondu will send the webhook in increasing intervals until the `WebhookController` returns an `OK`
response. Mondu will send `6` attempts every minute for all `buyer` and `order` topics until the handler responses with
a OK status code.

**Example Payload**:

```json
{
"topic": "buyer/{TOPIC_NAME}",
"buyer": {
"uuid": "66e8d234-23b5-1125-9592-d7390f20g01c",
"state": "accepted",
"external_reference_id": "DE-1-1000745773",
"company_name": "2023-02-07T15:14:22.301Z",
"first_name": "John",
"last_name": "Smith"
}
}
```

## FAQs

### Is the plugin compatible with the WP block editor?

The Payment Gateway is not compatible, but the form is, see below for more details.

### How do I allow for signups outside the checkout?

This plugin adds native support for allowing users to sign up to a Trade Account outside of the checkout. Perfect for
CTA's or banners.

**Note**: The user must be logged in to perform this action, this is because when Mondu responds to the Trade Account
request, a customer ID is required. Before displaying the form below, ensure your users are logged in by using the
WordPress `is_user_logged_in()` function.

**Block**:

You can add the `Mondu Trade Account Form Block` to the block editor, which will output a dynamic form the user can use
to sign up to the Trade Account.

**Shortcode**:

If you want to programmatically output the shortcode, you can do so by placing the following code in your page template.

```php
echo do_shortcode('[mondu_trade_account_form]');
```

---

### How do I know what the status is of a customer?

Simply go to the user's account on WordPress by navigating to `Users` and click on a customer. From there, you should
see the following fields:

- `uuid` -> The external UUID that's been assigned from Mondu.
- `status` -> The buyer status which can be one of `unknown`, `accepted`, pending` or `declined`.

---

### When will Mondu send emails to the customer?

- After the buyer authorises the onboarding process in hosted checkout page.
- Status change to accepted triggers webhook attempt buyer accepted and the email communication.
- Status change to declined on webhook buyer declined is sent out.

**It's recommended you still add email triggers for webhooks**, this is described below.

---

### How do I add custom styling to the payment gateway?

There may be times you want to style the checkout gateway with your own styles. To do this, you can either latch onto
the default class name `mondu-trade` or provide your own using a filter.

An example of this is below:

```php
/**
* Adds a custom class to the Mondu Trade Account checkout gateway.
*
* @param string $class The existing CSS class for the Mondu Trade Account checkout gateway.
* @return string The modified CSS class with the custom class name appended.
*/
function add_custom_mondu_trade_account_class($class) {
return $class . ' my-class-name';
}

add_filter('mondu_trade_account_checkout_class', 'add_custom_mondu_trade_account_class');
```

---

### How can I get a buyer status of a user?

You can use the `mondu_trade_get_buyer_status` function to fetch the current status of a customer. This function will
throw a `MonduTradeException` if the provided customer ID is invalid. Ensure to handle exceptions properly when calling
this function.

**Parameters:**

- `$customer_id (int)`: The ID of the customer whose status you want to retrieve.

**Returns**:

- `string`: The current Mondu Trade Account status of the customer, see above for possible values.

**Throws**:

- `MonduTradeException`: If the customer ID is not valid.

**Example**:

Here’s an example of how to call the `mondu_trade_get_buyer_status` function and handle possible exceptions:

```php
try {
$customer_id = 123; // Replace with the actual customer ID
$status = mondu_trade_get_buyer_status($customer_id);

echo "Customer Status: " . $status;
} catch (MonduTradeException $e) {
echo "Error: " . $e->getMessage();
}
```

---

### How can I get a buyer limit of a user?

You can use the `mondu_trade_get_buyer_limit` function to fetch the buyer limit for a customer. This function will
throw a `MonduTradeException` if the provided customer ID is invalid or if the buyer status is not `accepted`. Ensure to
handle exceptions properly when calling this function.

**Parameters:**

- `$customer_id (int)`: The ID of the customer whose buyer limit you want to retrieve.

**Returns**:

- `array`: An associative array containing the buyer limit details (see sample below).

**Throws**:

- `MonduTradeException`: If the customer ID is not valid or the buyer status is not `accepted`.

**Example**:

Here’s an example of how to call the `mondu_trade_get_buyer_limit` function and handle possible exceptions:

```php
try {
$customer_id = 123; // Replace with the actual customer ID
$buyer_limit = mondu_trade_get_buyer_limit($customer_id);

print_r($buyer_limit);
} catch (MonduTradeException $e) {
echo "Error: " . $e->getMessage();
}
````

**Sample Output**:

```php
Array (
[purchasing_limit] => Array (
[purchasing_limit_cents] => 100000
[balance_cents] => 10000
[max_purchase_value_cents] => 90000
[max_collections_state] => no
)
)
```

---

### How can I run actions when a buyer status has changed?

There are 4 different actions you can latch onto when Mondu replies with an update after a customer has applied for a
Digital Trade Account. Below is a list of available actions.

**Example Payload**

Below is an example of a buyer and topic sent via the actions, see
the [Mondu Webhooks Overview](https://docs.mondu.ai/reference/webhooks-overview) for more information

```json
{
"topic": "buyer/{TOPIC_NAME}",
"buyer": {
"uuid": "66e8d234-23b5-1125-9592-d7390f20g01c",
"state": "accepted",
"external_reference_id": "DE-1-1000745773",
"company_name": "2023-02-07T15:14:22.301Z",
"first_name": "John",
"last_name": "Smith"
}
}
```

### General Webhook Action

`mondu_trade_buyer_webhook_received`

Triggered when a webhook related to a buyer is received from Mondu.

**Parameters:**

- `$state (string)`: The current state of the buyer (e.g. `accepted`, `pending`, `declined`).
- `$customer_id (int)`: The WooCommerce customer ID.
- `$buyer (array)`: The buyer object, see above for an example.

**Example**:

```php
/**
* Handles general webhook actions when a buyer webhook is received from Mondu.
*
* @param string $state The current state of the buyer (e.g., accepted, pending, declined).
* @param int $customer_id The WooCommerce customer ID.
* @param array $buyer The buyer object containing buyer details.
* @return void
*/
function handle_mondu_trade_buyer_webhook($state, $customer_id, $buyer) {
print_r([
'state' => $state,
'customer_id' => $customer_id,
'buyer' => $buyer,
]);
}

add_action('mondu_trade_buyer_webhook_received', 'handle_mondu_trade_buyer_webhook', 10, 3);
```

### Accepted

`mondu_trade_buyer_accepted`

Triggered when a buyer has been accepted for a Trade Account.

**Parameters:**

- `$customer_id (int)`: The WooCommerce customer ID.
- `$buyer (array)`: The buyer object, see above for an example.

**Example**:

```php
/**
* Handles the "accepted" webhook when a buyer is approved for a Trade Account.
*
* @param int $customer_id The WooCommerce customer ID.
* @param array $buyer The buyer object containing buyer details.
* @return void
*/
function handle_mondu_trade_buyer_accepted($customer_id, $buyer) {
print_r([
'customer_id' => $customer_id,
'buyer' => $buyer,
]);

// You can now retrieve the buyer limit by using the
// mondu_trade_get_buyer_limit($customer_id) function.
}

add_action('mondu_trade_buyer_accepted', 'handle_mondu_trade_buyer_accepted', 10, 2);
```

### Pending

`mondu_trade_buyer_pending`

Triggered when a buyer is in a pending state (maximum 48 hours).

**Parameters:**

- `$customer_id (int)`: The WooCommerce customer ID.
- `$buyer (array)`: The buyer object, see above for an example.

**Example**:

```php
/**
* Handles the "pending" webhook when a buyer is in a pending state.
*
* @param int $customer_id The WooCommerce customer ID.
* @param array $buyer The buyer object containing buyer details.
* @return void
*/
function handle_mondu_trade_buyer_pending($customer_id, $buyer) {
print_r([
'customer_id' => $customer_id,
'buyer' => $buyer,
]);
}

add_action('mondu_trade_buyer_pending', 'handle_mondu_trade_buyer_pending', 10, 2);
```

### Declined

`mondu_trade_buyer_declined`

Triggered when a buyer has been declined for a Trade Account.

**Parameters:**

- `$customer_id (int)`: The WooCommerce customer ID.
- `$buyer (array)`: The buyer object, see above for an example.

**Example**:

```php
/**
* Handles the "declined" webhook when a buyer is declined for a Trade Account.
*
* @param int $customer_id The WooCommerce customer ID.
* @param array $buyer The buyer object containing buyer details.
* @return void
*/
function handle_mondu_trade_buyer_declined($customer_id, $buyer) {
print_r([
'customer_id' => $customer_id,
'buyer' => $buyer,
]);
}

add_action('mondu_trade_buyer_declined', 'handle_mondu_trade_buyer_declined', 10, 2);
```

---

### How can I email a customer after their status has changed?

In some circumstances, Mondu don't send emails to customers to update them. If you would like to send emails from
WooCommerce, you can latch onto the `mondu_trade_buyer_webhook_received` webhook and use the `WC` mailer instance.

An example of how you might do this is below.

```php
/**
* Sends an email to the customer when their status changes.
*
* @param string $state The buyer state, e.g., "accepted", "pending", or "declined".
* @param int $customer_id The WooCommerce customer ID.
* @param array $buyer The buyer object containing buyer details.
*/
function send_email_on_status_change($state, $customer_id, $buyer) {
// Retrieve customer data.
$customer = new WC_Customer($customer_id);
$email = $customer->get_email();

// Set email subject and email heading.
$subject = sprintf(__('Your Trade Account Status: %s', 'mondu-digital-trade-account'), ucfirst($state));
$email_heading = __('Trade Account Status Update', 'mondu-digital-trade-account');

// Prepare email content.
ob_start();
?>


get_first_name())); ?>











mailer();
$email_content = $mailer->wrap_message($email_heading, $email_body);

// Send the email.
$mailer->send($email, $subject, $email_content);
}

add_action('mondu_trade_buyer_webhook_received', 'send_email_on_status_change', 10, 3);
```

## Development

Below are the steps to install the plugin on your local machine for development.

### Setup

To get setup with plugin, follow the steps listed below.

**1. Clone the Repository**

Clone the repository into your `/wp-content/plugins` folder.

```shell
git clone https://github.com/ainsleydev/mondu-trade-woocommerce
cd mondu-trade-woocommerce
```

**2. Install Dependencies**

Ensure you have Composer and the WP CLI installed on your system. Run the following command to install PHP dependencies.
The `make setup` command will install `localtunnel` and `concurrently` on the system to run WordPress with webhook
functionality.

```shell
composer install
make setup
```

**3. Setup Environment**

Create a `.env` file by copying `.env.example`:

```dotenv
MONDU_TRADE_ENV=dev
MONDU_WEBHOOKS_URL=https://mondu-digital-trade-account-woocommerce-ainsleydev.loca.lt
```

### Running WordPress

The make file exposes a handy `serve` function which runs Wordpress, a local tunnel and tails the WordPress logs. Feel
free to edit this script to suit your needs.

```shell
make serve
```

## Release

To create a new release, follow the following steps:

1. **Bump Version**

- Run the following command to choose the type of release (patch, minor, or major) and update the version
in `mondu-digital-trade-account.php`. You should merge this into `main` before creating a release.

```shell
make version-bump
```

2. **Release**

- Run this command to compare the local version with the remote version and create a new tag if they differ. It will
then create a new tag which will trigger the pipeline which creates a new zip file on GitHub.

```shell
make release
```

These steps will bump the version locally, and then create and push a new release tag to GitHub.

## Copyright

All rights reserved. This plugin and its code are proprietary to ainsley.dev LTD. Unauthorized copying, distribution,
transmission, or storage of this plugin, its code, or content, in whole or in part, in any form or by any means, is
strictly prohibited without prior written permission.

This plugin is licensed for use by end-users on their WordPress sites but may not be copied, shared, modified, or
redistributed in any form, except with explicit written permission from ainsley.dev LTD.

## Licence

Code Copyright 2024 ainsley.dev LTD. Code released under the [GPL-3.0](LICENSE).