Skip to content

Commit

Permalink
better explain
Browse files Browse the repository at this point in the history
  • Loading branch information
Yaya12085 committed Nov 3, 2024
1 parent a3b852c commit a7ec029
Show file tree
Hide file tree
Showing 9 changed files with 389 additions and 309 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ npm-debug.log
.DS_Store
node_modules
tmp
example
example
dist
4 changes: 3 additions & 1 deletion .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,6 @@ npm-debug.log
.DS_Store
node_modules
tmp
example
example
src
.github
194 changes: 140 additions & 54 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,95 +1,181 @@
# FusionPay

FusionPay is a JavaScript library for handling payment operations, providing a simple and intuitive API to facilitate online payments for moneyfusion.net.
FusionPay is a TypeScript/JavaScript library for handling payment operations with the MoneyFusion payment gateway, providing a simple and intuitive API to facilitate online payments.

## Installation

You can install FusionPay via npm or yarn.:
Install FusionPay using npm or yarn:

```bash
npm install fusionpay
```

```bash
# or
yarn add fusionpay
```

## Usage

Initializing FusionPay
To start using FusionPay, you need to initialize a new instance with your API URL:
### Initializing FusionPay

```javascript
const { FusionPay } = require("fusionpay");
//OR import { FusionPay } from "fusionpay";
```typescript
import { FusionPay } from "fusionpay";

// Basic initialization
const fusionPay = new FusionPay("https://your-api-url.com");
```

## Setting Payment Data
// With custom data type
interface OrderData {
orderId: string;
customerEmail: string;
}
const typedFusionPay = new FusionPay<OrderData>("https://your-api-url.com");
```

You can set the payment data using the various methods provided by FusionPay:
### Setting Payment Data

```javascript
```typescript
fusionPay
.totalPrice(200)
.addArticle("Sac", 100)
.addArticle("Veste", 200)
.addInfo({ userId: "1245d858sf8f95f9ff", token: "dffqsyyyysfs56556sjsjh" })
.addArticle("Veste", 100)
.addInfo({
orderId: "12345",
customerEmail: "[email protected]",
})
.clientName("M. Yaya")
.clientNumber("0574801791")
.returnUrl("https://my_call_back_link.com");
.clientNumber("01010101")
.returnUrl("https://my_callback_url.com");
```

## Making a Payment
### Making a Payment

To make a payment, use the makePayment() method:
```typescript
try {
const response = await fusionPay.makePayment();
console.log("Payment initiated:", response);
// Redirect user to payment URL or send url to client
} catch (error) {
console.error("Payment initiation failed:", error);
}
```

```javascript
fusionPay
.makePayment()
.then((response) => {
console.log("Payment successful:", response);
})
.catch((error) => {
console.error("Payment failed:", error);
});
#### Payment Response Structure

```typescript
{
statut: boolean; // Payment initiation status
token: string; // Token for payment verification
message: string; // Status message
url: string; // Payment gateway URL for user redirection
}
```

### Handling Payment Callback

When the payment is completed, the user will be redirected to your return URL with a token parameter:

```
https://my_callback_url.com?token=payment_token_here
```

## Checking Payment Status
### Checking Payment Status

To check the payment status, use the checkPaymentStatus() method:
```typescript
//extract token in your url
//eg: Nodejs -> const {token} = req.query

```javascript
const paymentToken = "your_payment_token_here";
try {
// Verify payment status

fusionPay
.checkPaymentStatus(paymentToken)
.then((status) => {
console.log("Payment status:", status);
})
.catch((error) => {
console.error("Failed to check payment status:", error);
});
const status = await fusionPay.checkPaymentStatus(token);
if (status.statut && status.data.statut === "paid") {
// Payment successful
const customData = status.data.personal_Info[0];
// Handle success...
}
} catch (error) {
console.error("Status check failed:", error);
}
```

#### Payment Verification Response Structure

```typescript
{
statut: boolean; // Verification request status
message: string; // Status message
data: {
_id: string; // Payment record ID
tokenPay: string; // Payment token
numeroSend: string; // Customer phone number
nomclient: string; // Customer name
personal_Info: T[]; // Your custom data array
numeroTransaction: string; // Transaction reference
Montant: number; // Payment amount
frais: number; // Transaction fees
statut: "pending" | "paid" | "failed"; // Payment status
moyen: string; // Payment method used
return_url: string; // Callback URL
createdAt: string; // Transaction timestamp
}
}
```

## Custom Data Examples

Here are some examples of custom data you might want to store:

```typescript
// E-commerce order
interface OrderData {
orderId: string;
customerEmail: string;
}

// Subscription
interface SubscriptionData {
planId: string;
subscriberId: string;
period: "monthly" | "yearly";
}

// Event ticket
interface TicketData {
eventId: string;
ticketType: string;
quantity: number;
}

// Usage
const payment = new FusionPay<OrderData>(apiUrl);
payment.addInfo({
orderId: "ORD-123",
customerEmail: "[email protected]",
});
```

## API
## API Reference

### Constructor

- `new FusionPay<T = CustomPaymentData>(apiUrl: string)`

### Methods

`FusionPay(apiUrl: string)`
All methods (except `makePayment` and `checkPaymentStatus`) support method chaining.

- `apiUrl: The API URL for payment.`
- `totalPrice(amount: number): this`
- `addArticle(name: string, value: number): this`
- `addInfo(data: T): this`
- `clientName(name: string): this`
- `clientNumber(number: string): this`
- `returnUrl(url: string): this`
- `makePayment(): Promise<PaymentResponse>`
- `checkPaymentStatus(token: string): Promise<PaymentVerificationResponse<T>>`

## Methods
## Error Handling

- `totalPrice(amount: number): FusionPay`
- `addArticle(name: string, value: number): FusionPay`
- `addInfo(info: Record<string, string>): FusionPay`
- `clientName(name: string): FusionPay`
- `clientNumber(number: string): FusionPay`
- `returnUrl(url: string): FusionPay`
- `makePayment(): Promise<AxiosResponse>`
- `checkPaymentStatus(token: string): Promise<AxiosResponse>`
The library throws errors for failed API calls and invalid parameters. Always wrap API calls in try-catch blocks for proper error handling.

## License

This project is licensed under the MIT License. See the LICENSE file for details.
This project is licensed under the MIT License - see the LICENSE file for details.
63 changes: 24 additions & 39 deletions dist/FusionPay.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,27 @@
Object.defineProperty(exports, "__esModule", { value: true });
exports.FusionPay = void 0;
/**
* FusionPay class for handling payment operations.
* FusionPay class for handling payment operations with MoneyFusion payment gateway.
* @template T Type of custom data to be stored in personal_Info
*/
class FusionPay {
/**
* Initializes a new instance of the FusionPay class.
* @param apiUrl - The API URL for payment.
* @param apiUrl - The API URL for payment processing.
*/
constructor(apiUrl) {
this.paymentData = {
article: [],
personal_Info: [],
};
this.apiUrl = apiUrl;
this.headers = {
"Content-Type": "application/json",
};
this.paymentData = {
article: [],
personal_Info: [],
};
}
/**
* Sets the total price for the payment.
* @param amount - The total price amount.
* @returns The FusionPay instance for method chaining.
* @example
* fusionPay.totalPrice(200);
*/
totalPrice(amount) {
this.paymentData.totalPrice = amount;
Expand All @@ -34,53 +32,38 @@ class FusionPay {
* Adds an article to the payment data.
* @param name - The name of the article.
* @param value - The price of the article.
* @returns The FusionPay instance for method chaining.
* @example
* fusionPay.addArticle('sac', 100);
*/
addArticle(name, value) {
this.paymentData.article.push({ [name]: value });
return this;
}
/**
* Adds personal info to the payment data.
* @param info - The personal info object.
* @returns The FusionPay instance for method chaining.
* @example
* fusionPay.addInfo({ userId: '1245d858sf8f95f9ff', token: 'dffqsyyyysfs56556sjsjh' });
* Adds custom data to personal_Info that will be returned after payment processing.
* @param data - Custom data object to store with the payment
*/
addInfo(info) {
this.paymentData.personal_Info.push(info);
addInfo(data) {
this.paymentData.personal_Info.push(data);
return this;
}
/**
* Sets the client name for the payment.
* @param name - The client name.
* @returns The FusionPay instance for method chaining.
* @example
* fusionPay.clientName('M. Yaya Mohamed');
*/
clientName(name) {
this.paymentData.nomclient = name;
return this;
}
/**
* Sets the client number for the payment.
* @param number - The client number.
* @returns The FusionPay instance for method chaining.
* @example
* fusionPay.clientNumber('0574801791');
* @param number - The client phone number.
*/
clientNumber(number) {
this.paymentData.numeroSend = number;
return this;
}
/**
* Sets the return URL for the payment.
* @param url - The return URL.
* @returns The FusionPay instance for method chaining.
* @example
* fusionPay.returnUrl('https://mon_lien_de_callback.com');
* Sets the return URL for the payment callback.
* @param url - The return URL where payment token will be appended.
*/
returnUrl(url) {
this.paymentData.return_url = url;
Expand All @@ -89,8 +72,7 @@ class FusionPay {
/**
* Makes a payment using the configured payment data.
* @returns A promise that resolves with the payment response.
* @example
* fusionPay.makePayment().then(response => { console.log(response); });
* @throws Error if the payment request fails.
*/
async makePayment() {
try {
Expand All @@ -105,15 +87,16 @@ class FusionPay {
return await response.json();
}
catch (error) {
throw new Error(error.message);
throw error instanceof Error
? error
: new Error("An unknown error occurred during payment");
}
}
/**
* Checks the payment status using a token.
* @param token - The payment token.
* @returns A promise that resolves with the payment status.
* @example
* fusionPay.checkPaymentStatus('your_payment_token_here').then(status => { console.log(status); });
* @param token - The payment token received as URL query parameter.
* @returns A promise that resolves with the payment verification response.
* @throws Error if the status check fails.
*/
async checkPaymentStatus(token) {
const url = `https://www.pay.moneyfusion.net/paiementNotif/${token}`;
Expand All @@ -125,7 +108,9 @@ class FusionPay {
return await response.json();
}
catch (error) {
throw new Error(error.message);
throw error instanceof Error
? error
: new Error("An unknown error occurred while checking payment status");
}
}
}
Expand Down
Loading

0 comments on commit a7ec029

Please sign in to comment.