### Install myfatoorah-toolkit with yarn Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/getting-started.md Install the myfatoorah-toolkit package using yarn. ```bash yarn add myfatoorah-toolkit ``` -------------------------------- ### Install MyFatoorah Toolkit Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/README.md Install the myfatoorah-toolkit package using npm. This is the first step to integrate MyFatoorah payments into your application. ```bash npm install myfatoorah-toolkit ``` -------------------------------- ### Initiate Payment Response Example Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/endpoints.md Example JSON response for the Initiate Payment endpoint, showing a successful retrieval of available payment methods. ```json { "IsSuccess": true, "Message": "Executed successfully", "ValidationErrors": null, "Data": { "PaymentMethods": [ { "PaymentMethodId": 1, "PaymentMethodAr": "بطاقة الائتمان", "PaymentMethodEn": "Credit Card", "IsDirectPayment": false, "ServiceCharge": 0, "TotalAmount": 100, "CurrencyIso": "KWD", "ImageUrl": "https://..." } ] } } ``` -------------------------------- ### Initiate Payment Request Example Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/endpoints.md Example of a POST request to initiate a payment, specifying the invoice amount and currency. This request is typically made after calling MyFatoorah.initiatePayment(100, 'KWD'). ```http POST https://api.myfatoorah.com/v2/InitiatePayment Authorization: Bearer {apiKey} Content-Type: application/json { "InvoiceAmount": 100, "CurrencyIso": "KWD" } ``` -------------------------------- ### Example Request for Get Refund Status Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/endpoints.md Demonstrates how to make a POST request to the /v2/getRefundStatus endpoint. Ensure to include the Authorization header and Content-Type. ```http POST https://api.myfatoorah.com/v2/getRefundStatus Authorization: Bearer {apiKey} Content-Type: application/json { "Key": "614525", "KeyType": "InvoiceId" } ``` -------------------------------- ### Example POST Request for Get Payment Status Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/endpoints.md Demonstrates how to make a POST request to the /v2/getPaymentStatus endpoint with sample data. Ensure to include the Authorization header. ```http POST https://api.myfatoorah.com/v2/getPaymentStatus Authorization: Bearer {apiKey} Content-Type: application/json { "Key": "614525", "KeyType": "InvoiceId" } ``` -------------------------------- ### Make Refund Example Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/api-reference-myfatoorah.md Demonstrates how to initiate a refund using the `makeRefund` method with a sample request object and how to process the response. ```typescript const payment = new MyFatoorah('ARE', true); const refundResponse = await payment.makeRefund({ KeyType: 'InvoiceId', Key: '94272', RefundChargeOnCustomer: false, ServiceChargeOnCustomer: false, Amount: 210, Comment: 'Customer requested refund', AmountDeductedFromSupplier: 0 }); if (refundResponse.IsSuccess) { console.log('Refund ID:', refundResponse.Data.RefundId); console.log('Refund Reference:', refundResponse.Data.RefundReference); console.log('Refund Amount:', refundResponse.Data.Amount); } ``` -------------------------------- ### Execute Payment with Full Configuration Example Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/configuration.md Demonstrates how to send a payment request with comprehensive configuration options, including customer information, URLs, and invoice items. ```typescript const response = await payment.executePayment( 1000, paymentMethodId, { CustomerName: 'Ahmed Ali', CustomerEmail: 'ahmed@example.com', CustomerMobile: '1234567890', Language: 'ar', CustomerReference: 'ORD-2024-001', CallBackUrl: 'https://yoursite.com/payment/success', ErrorUrl: 'https://yoursite.com/payment/error', UserDefinedField: 'custom_data_here', InvoiceItems: [ { ItemName: 'Product A', Quantity: 2, UnitPrice: 400 }, { ItemName: 'Product B', Quantity: 1, UnitPrice: 200 } ], CustomerAdress: { Address: '123 Main Street', CityName: 'Cairo', PostalCode: '11111' } } ); ``` -------------------------------- ### Example Response for Get Refund Status Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/endpoints.md Provides an example of a successful response from the getRefundStatus endpoint, showing the details of a refunded item. ```json { "IsSuccess": true, "Message": "Refund status has been retrieved successfully", "ValidationErrors": null, "Data": { "RefundStatusResult": [ { "RefundId": 123456, "RefundStatus": "Refunded", "InvoiceId": 614525, "Amount": 1000, "RefundReference": "REF-614525-001", "RefundAmount": 1000 } ] } } ``` -------------------------------- ### Send Payment API Request Example Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/endpoints.md An example of how to construct a POST request to the Send Payment endpoint. It demonstrates the required headers and the JSON payload with sample data for initiating a payment. ```http // Initiated via MyFatoorah.sendPayment(500, 'Ahmed Ali', 'EML') POST https://api.myfatoorah.com/v2/SendPayment Authorization: Bearer {apiKey} Content-Type: application/json { "InvoiceValue": 500, "CustomerName": "Ahmed Ali", "DisplayCurrencyIso": "KWD", "MobileCountryCode": "+965", "NotificationOption": "EML", "CustomerEmail": "ahmed@example.com" } ``` -------------------------------- ### Example Response for Get Payment Status Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/endpoints.md Illustrates a successful response from the /v2/getPaymentStatus endpoint, showing the payment status and associated transaction details. ```json { "IsSuccess": true, "Message": "Invoice has been retrieved successfully", "ValidationErrors": null, "Data": { "InvoiceId": 614525, "InvoiceStatus": "Paid", "InvoiceReference": "INV-614525", "CustomerReference": "ORD-12345", "CreatedDate": "2024-01-15T10:30:00Z", "ExpiryDate": "2024-01-22T23:59:59Z", "InvoiceValue": 1000, "Comments": "", "CustomerName": "Fatima Hassan", "CustomerMobile": "1001234567", "CustomerEmail": "fatima@example.com", "UserDefinedField": "", "InvoiceDisplayValue": "1000.00", "DueDeposit": 0, "DepositStatus": "Completed", "InvoiceItems": [], "InvoiceTransactions": [], "Suppliers": [] } } ``` -------------------------------- ### Example Refund Request Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/endpoints.md Demonstrates a sample request to the Make Refund endpoint. This request should be sent via HTTPS with appropriate authorization. ```http POST https://api.myfatoorah.com/v2/MakeRefund Authorization: Bearer {apiKey} Content-Type: application/json { "KeyType": "InvoiceId", "Key": "614525", "RefundChargeOnCustomer": false, "ServiceChargeOnCustomer": false, "Amount": 1000, "Comment": "Customer requested refund" } ``` -------------------------------- ### Initiate and Execute a Payment Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/getting-started.md Get available payment methods and then execute a payment. Ensure you handle potential errors when fetching methods. ```typescript import { MyFatoorah } from 'myfatoorah-toolkit'; const payment = new MyFatoorah('EGY', true); // Step 1: Get available payment methods const methodsResponse = await payment.initiatePayment(1000, 'EGP'); if (!methodsResponse.IsSuccess) { console.error('Failed to get payment methods:', methodsResponse.Message); return; } // Step 2: Select a payment method (or let customer choose) const selectedMethod = methodsResponse.Data.PaymentMethods[0]; const methodId = selectedMethod.PaymentMethodId; // Step 3: Execute payment const paymentResponse = await payment.executePayment(1000, methodId, { CustomerName: 'Ahmed Hassan', CustomerEmail: 'ahmed@example.com', CustomerMobile: '1001234567', CallBackUrl: 'https://yourapp.com/payment/success', ErrorUrl: 'https://yourapp.com/payment/error' }); if (paymentResponse.IsSuccess) { console.log('Redirecting to:', paymentResponse.Data.PaymentURL); // Redirect customer to payment URL } else { console.error('Payment failed:', paymentResponse.Message); } ``` -------------------------------- ### Example Refund Response Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/endpoints.md Illustrates a successful response from the Make Refund endpoint, confirming the refund request creation. ```json { "IsSuccess": true, "Message": "Refund has been created successfully", "ValidationErrors": null, "Data": { "Key": "614525", "RefundId": 123456, "RefundReference": "REF-614525-001", "Amount": "1000.00", "Comment": "Customer requested refund" } } ``` -------------------------------- ### MyFatoorah API Error Response Example Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/errors.md This is an example of a typical error response structure from the MyFatoorah API when an operation fails. ```json { IsSuccess: false, Message: "Authorization failed", ValidationErrors: null, Data: {} } ``` -------------------------------- ### Example Execute Payment Request Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/endpoints.md Demonstrates how to call the ExecutePayment endpoint with sample data. Ensure the Authorization header includes your API key and the Content-Type is set to application/json. ```http POST https://api.myfatoorah.com/v2/ExecutePayment Authorization: Bearer {apiKey} Content-Type: application/json { "InvoiceValue": 1000, "PaymentMethodId": 11, "DisplayCurrencyIso": "EGP", "MobileCountryCode": "+20", "CustomerName": "Fatima Hassan", "CustomerEmail": "fatima@example.com", "CustomerMobile": "1001234567" } ``` -------------------------------- ### Environment-Based Configuration Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/configuration.md Configure the MyFatoorah SDK using environment variables for country, test mode, and API key. This allows for flexible setup across different deployment environments. ```typescript const config = { countryIso: process.env.MYFATOORAH_COUNTRY || 'EGY', testMode: process.env.NODE_ENV !== 'production', apiKey: process.env.MYFATOORAH_API_KEY }; const payment = new MyFatoorah(config.countryIso, config.testMode, config.apiKey); ``` -------------------------------- ### Example Execute Payment Response Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/endpoints.md Shows a successful response from the ExecutePayment endpoint, including the generated InvoiceId and the URL for payment processing. ```json { "IsSuccess": true, "Message": "Executed successfully", "ValidationErrors": null, "Data": { "InvoiceId": 614525, "IsDirectPayment": true, "PaymentURL": "https://checkout.myfatoorah.com/ar/?paymentId=614525", "CustomerReference": null, "UserDefinedField": null } } ``` -------------------------------- ### Basic MyFatoorah Payment Flow Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/README.md Initialize the MyFatoorah class with a country code and test mode status. Use `initiatePayment` to get available payment methods and `executePayment` to process the transaction. Ensure you have the correct `methodId` from the initiation step. ```typescript import { MyFatoorah } from 'myfatoorah-toolkit'; const payment = new MyFatoorah('EGY', true); // Test mode // Get payment methods const methods = await payment.initiatePayment(100); // Execute payment const result = await payment.executePayment(100, methodId); ``` -------------------------------- ### Send Payment API Response Example Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/endpoints.md Illustrates a typical successful response from the Send Payment endpoint. It shows the structure of the returned JSON, including the InvoiceId and the PaymentURL for the customer. ```json { "IsSuccess": true, "Message": "Executed successfully", "ValidationErrors": null, "Data": { "InvoiceId": 614523, "IsDirectPayment": false, "PaymentURL": "https://checkout.myfatoorah.com/en/?paymentId=614523", "CustomerReference": null, "UserDefinedField": null } } ``` -------------------------------- ### Initialize MyFatoorah with CommonJS Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/getting-started.md Set up the MyFatoorah client using CommonJS modules. Requires API keys and country code. ```javascript const { MyFatoorah, validateSignature } = require('myfatoorah-toolkit'); const payment = new MyFatoorah('EGY', true); ``` -------------------------------- ### Production .env Configuration Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/getting-started.md Set up your .env file for production deployment. Use your actual API keys and webhook secrets. ```bash # API Configuration NODE_ENV=production MYFATOORAH_COUNTRY=EGY MYFATOORAH_API_KEY=your_production_api_key MYFATOORAH_WEBHOOK_SECRET=your_production_webhook_secret # Application URLs APP_URL=https://yourdomain.com ``` -------------------------------- ### API Validation Error Response Example Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/errors.md An example of an API response indicating validation failures, including specific details for each invalid field in the ValidationErrors array. ```typescript { IsSuccess: false, Message: "Validation failed", ValidationErrors: [ { Name: "CustomerEmail", Error: "Invalid email format" }, { Name: "Amount", Error: "Amount must be greater than zero" } ], Data: {} } ``` -------------------------------- ### Initialize MyFatoorah with ES6 Modules Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/getting-started.md Set up the MyFatoorah client using ES6 modules. Requires API keys and country code. ```typescript import { MyFatoorah, validateSignature } from 'myfatoorah-toolkit'; const payment = new MyFatoorah('EGY', true); ``` -------------------------------- ### POST /v2/InitiatePayment Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/endpoints.md Retrieves a list of available payment methods for a specified amount and currency. This endpoint is called via the `MyFatoorah.initiatePayment` function. ```APIDOC ## POST /v2/InitiatePayment ### Description Retrieves a list of available payment methods for the specified amount and currency. ### Method POST ### Endpoint /v2/InitiatePayment ### Parameters #### Request Body - **InvoiceAmount** (number) - Required - The payment amount in the specified currency. - **CurrencyIso** (TCurrencyCodes) - Required - Currency code: 'KWD' | 'SAR' | 'BHD' | 'AED' | 'QAR' | 'OMR' | 'JOD' | 'EGP' ### Request Example ```json { "InvoiceAmount": 100, "CurrencyIso": "KWD" } ``` ### Response #### Success Response (200) - **IsSuccess** (boolean) - Indicates if the request was successful. - **Message** (string) - A message describing the outcome of the request. - **ValidationErrors** (null | Array<{ Name?: string; Error?: string }>) - An array of validation errors, if any. - **Data** (object) - Contains the payment methods information. - **PaymentMethods** (Array) - A list of available payment methods. - **PaymentMethodId** (number) - The ID of the payment method. - **PaymentMethodAr** (string) - The name of the payment method in Arabic. - **PaymentMethodEn** (string) - The name of the payment method in English. - **IsDirectPayment** (boolean) - Indicates if it's a direct payment method. - **ServiceCharge** (number) - The service charge for the payment method. - **TotalAmount** (number) - The total amount including service charge. - **CurrencyIso** (TCurrencyCodes) - The currency code. - **ImageUrl** (string) - URL for the payment method's image. #### Response Example ```json { "IsSuccess": true, "Message": "Executed successfully", "ValidationErrors": null, "Data": { "PaymentMethods": [ { "PaymentMethodId": 1, "PaymentMethodAr": "بطاقة الائتمان", "PaymentMethodEn": "Credit Card", "IsDirectPayment": false, "ServiceCharge": 0, "TotalAmount": 100, "CurrencyIso": "KWD", "ImageUrl": "https://..." } ] } } ``` ``` -------------------------------- ### MyFatoorah Class Methods Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/README.md Documentation for the main `MyFatoorah` class, including its constructor and all public methods for interacting with the MyFatoorah payment gateway. ```APIDOC ## Constructor ### Description Initializes the `MyFatoorah` class with necessary parameters and configuration. ### Method `constructor` ### Parameters - **apiKey** (string) - Required - Your MyFatoorah API key. - **countryCode** (string) - Required - The country code for the API endpoint (e.g., 'SA', 'AE'). - **isTest** (boolean) - Optional - Set to `true` for testing environment, `false` for production. ### Response An instance of the `MyFatoorah` class. ## getCountry ### Description Retrieves the country ISO code based on the provided country name or code. ### Method `getCountry(country: string): string` ### Parameters - **country** (string) - Required - The country name or code to look up. ### Response - **countryCode** (string) - The ISO country code. ## initiatePayment ### Description Retrieves a list of available payment methods for a given transaction. ### Method `initiatePayment(request: IInitiatePaymentRequest): Promise` ### Parameters - **request** (IInitiatePaymentRequest) - Required - Object containing payment initiation details. - **InvoiceAmount** (number) - Required - The total amount of the invoice. - **CurrencyIso** (string) - Required - The ISO currency code (e.g., 'SAR', 'AED'). ### Response - **Data** (Array) - List of available payment methods. ## sendPayment ### Description Generates an invoice and sends a payment link to the customer via email or SMS. ### Method `sendPayment(request: ISendPaymentRequest): Promise` ### Parameters - **request** (ISendPaymentRequest) - Required - Object containing payment details for sending a link. - **InvoiceAmount** (number) - Required - The total amount of the invoice. - **CurrencyIso** (string) - Required - The ISO currency code. - **CustomerName** (string) - Required - The customer's full name. - **CustomerEmail** (string) - Optional - The customer's email address. - **CustomerMobile** (string) - Optional - The customer's mobile number. - **CallBackUrl** (string) - Required - The URL to redirect the customer to after payment. - **ErrorUrl** (string) - Required - The URL to redirect the customer to in case of an error. - **Language** (string) - Optional - The preferred language for the payment page. - **DisplayCurrencyIso** (string) - Optional - The currency to display to the customer. ### Response - **Data** (object) - Contains invoice details and payment link. - **InvoiceId** (number) - The unique ID of the generated invoice. - **InvoiceURL** (string) - The URL for the customer to complete the payment. ## executePayment ### Description Executes a payment transaction using the selected payment method and provided details. ### Method `executePayment(request: IExecutePaymentRequest): Promise` ### Parameters - **request** (IExecutePaymentRequest) - Required - Object containing details for executing a payment. - **InvoiceId** (number) - Required - The ID of the invoice to execute. - **PaymentMethodId** (number) - Required - The ID of the payment method to use. ### Response - **Data** (object) - Contains payment execution results. ## getPaymentStatus ### Description Queries the status of a payment transaction using various key types. ### Method `getPaymentStatus(request: IPaymentInquiryRequest): Promise` ### Parameters - **request** (IPaymentInquiryRequest) - Required - Object containing details to query payment status. - **KeyType** (TKeyType) - Required - The type of key to use for the query (e.g., 'InvoiceId', 'TransactionId'). - **Key** (string) - Required - The value of the key to query. ### Response - **Data** (object) - Contains the payment transaction status and details. ## makeRefund ### Description Initiates a refund request for a previously completed payment transaction. ### Method `makeRefund(request: IPaymentRefundRequest): Promise` ### Parameters - **request** (IPaymentRefundRequest) - Required - Object containing details for initiating a refund. - **InvoiceId** (number) - Required - The ID of the invoice to refund. - **RefundAmount** (number) - Required - The amount to refund. - **Comment** (string) - Optional - A comment for the refund transaction. - **Language** (string) - Optional - The preferred language for the refund process. ### Response - **Data** (object) - Contains the result of the refund initiation. ## getRefundStatus ### Description Checks the status of a refund request. ### Method `getRefundStatus(request: IRefundInquiryRequest): Promise` ### Parameters - **request** (IRefundInquiryRequest) - Required - Object containing details to query refund status. - **RefundId** (string) - Required - The ID of the refund transaction. ### Response - **Data** (object) - Contains the status and details of the refund. ``` -------------------------------- ### Get Country Code Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/api-reference-myfatoorah.md Retrieves the ISO country code that was specified when initializing the MyFatoorah object. ```typescript get getCountry(): TCountryCodes ``` ```typescript const payment = new MyFatoorah('KWT', true); console.log(payment.getCountry); // Output: 'KWT' ``` -------------------------------- ### Development .env Configuration Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/getting-started.md Configure your .env file for local development. Ensure test mode is enabled and use placeholder secrets. ```bash # API Configuration NODE_ENV=development MYFATOORAH_COUNTRY=EGY MYFATOORAH_TEST_MODE=true # Webhook Configuration MYFATOORAH_WEBHOOK_SECRET=your_test_webhook_secret # Application URLs APP_URL=http://localhost:3000 ``` -------------------------------- ### Initialize MyFatoorah Client and Validate Webhooks Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/configuration.md Use environment variables to initialize the MyFatoorah client and validate incoming webhook signatures. Ensure the webhook secret is correctly set. ```typescript import { MyFatoorah, validateSignature } from 'myfatoorah-toolkit'; // Initialize payment client const payment = new MyFatoorah( process.env.MYFATOORAH_COUNTRY || 'EGY', process.env.MYFATOORAH_TEST_MODE === 'true' || process.env.NODE_ENV !== 'production', process.env.MYFATOORAH_API_KEY ); // Validate webhooks app.post('/webhook/payment', async (req, res) => { const secret = process.env.MYFATOORAH_WEBHOOK_SECRET; const signature = req.get('MyFatoorah-Signature'); try { await validateSignature(req.body, signature, secret); // Process webhook } catch (error) { res.status(401).json({ error: 'Invalid signature' }); } }); ``` -------------------------------- ### Get Refund Status Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/README.md Retrieves the status of a refund request to check if it has been refunded, rejected, or is still pending. ```APIDOC ## Get Refund Status ### Description Used to get the status of the refund to check if it is refunded, rejected, or still pending. ### Method `getRefundStatus(key, keyType)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **key** (string) - Required - The identifier for the refund. * **keyType** (string) - Required - The type of the key. Available options: 'InvoiceId', 'RefundReference', 'RefundId'. ### Request Example ```javascript payment.getRefundStatus('1647850', 'InvoiceId').then((data) => data).catch(err => err); ``` ### Response #### Success Response (200) Status details of the refund request. #### Response Example (Response structure depends on MyFatoorah API) ``` -------------------------------- ### MyFatoorah Constructor Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/api-reference-myfatoorah.md Initializes a new instance of the MyFatoorah class. This is the primary entry point for interacting with the MyFatoorah payment gateway. ```APIDOC ## MyFatoorah Constructor ### Description Initializes a new instance of the MyFatoorah class, setting up the connection to the MyFatoorah payment gateway based on country, mode, and API key. ### Parameters #### Path Parameters - **countryIso** (TCountryCodes) - Required - ISO code for the country. Supported values: 'KWT' | 'SAU' | 'BHR' | 'ARE' | 'QAT' | 'OMN' | 'JOD' | 'EGY'. Determines the default currency and API endpoint. - **testMode** (boolean) - Required - When `true`, uses testing API endpoint. When `false`, uses production API endpoint. - **apiKey** (string) - Optional - Your MyFatoorah API key for production. Required if `testMode` is `false`. If not provided in test mode, uses the embedded test token. ### Throws Throws an `Error` with message `'You must provide your own api key when test mode is disabled.'` if `testMode` is `false` and no `apiKey` is provided. ### Behavior - If `testMode` is `true`, sets API URL to `https://apitest.myfatoorah.com/` - If `testMode` is `false` and `countryIso` is `'SAU'`, sets API URL to `https://api-sa.myfatoorah.com/` - If `testMode` is `false` and `countryIso` is not `'SAU'`, sets API URL to `https://api.myfatoorah.com/` - Creates an Axios instance with Bearer token authorization and JSON content type ### Example ```typescript import { MyFatoorah } from 'myfatoorah-toolkit'; // Test mode instance const paymentTest = new MyFatoorah('EGY', true); // Production mode instance const paymentProd = new MyFatoorah('EGY', false, process.env.PAYMENT_API_KEY); ``` ``` -------------------------------- ### Get Payment Status Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/README.md Retrieves the status of a payment using either the Invoice ID or Payment ID. ```APIDOC ## Get Payment Status ### Description Returns the status of the payment using a provided key and key type. ### Method `getPaymentStatus(key, keyType)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **key** (string) - Required - The identifier for the payment (e.g., InvoiceId, PaymentId). * **keyType** (string) - Required - The type of the key. Available options: 'InvoiceId', 'PaymentId', 'CustomerReference'. ### Request Example ```javascript payment.getPaymentStatus('613842', 'InvoiceId').then((data) => data).catch(err => err); ``` ### Response #### Success Response (200) Status details of the payment. #### Response Example (Response structure depends on MyFatoorah API) ``` -------------------------------- ### Instantiate MyFatoorah in Production Mode Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/configuration.md Initializes the MyFatoorah payment gateway for live transactions using a specific country code, disabling test mode, and providing an API key from environment variables. ```typescript import { MyFatoorah } from 'myfatoorah-toolkit'; // Production mode const paymentProd = new MyFatoorah('EGY', false, process.env.MYFATOORAH_API_KEY); ``` -------------------------------- ### Instantiate MyFatoorah Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/README.md Create a new MyFatoorah instance by providing the country ISO code, a boolean for test mode, and optionally an API key. ```javascript const payment = new MyFatoorah(countryIso, testMode, apiKey?) ``` ```javascript const payment = new MyFatoorah('EGY', true); ``` ```javascript const payment = new MyFatoorah('EGY', false, process.env.PAYMENT_TOKEN); ``` -------------------------------- ### Get Payment Status Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/README.md Retrieve the status of a payment using either an Invoice ID or Payment ID. Specify the key type for the inquiry. ```javascript payment.getPaymentStatus(key, keyType) ``` ```javascript payment.getPaymentStatus('613842', 'InvoiceId').then((data) => data).catch(err => err); ``` -------------------------------- ### MyFatoorah API Server Error Response Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/errors.md Example of a typical server error response from the MyFatoorah API. This indicates an issue on MyFatoorah's end. ```typescript { IsSuccess: false, Message: "An unexpected error occurred", ValidationErrors: null, Data: {} } ``` -------------------------------- ### Initiate Payment Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/README.md Initiates a payment process by returning a list of available payment methods. This is the first step in executing a payment. ```APIDOC ## Initiate Payment ### Description Returns a list of Payment Methods that you need to Execute A Payment. ### Method `initiatePayment(amount, currencyISOCode?)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **amount** (number) - Required - The payment amount. * **currencyISOCode** (string) - Optional - The ISO code of the currency (e.g., 'SAR'). Defaults to the country's default currency if not provided. ### Request Example ```javascript payment.initiatePayment(100).then((data) => data).catch(err => err); payment.initiatePayment(100, 'SAR').then((data) => data).catch(err => err); ``` ### Response #### Success Response (200) Details of available payment methods. #### Response Example (Response structure depends on MyFatoorah API) ``` -------------------------------- ### Get Payment Status Response Schema Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/endpoints.md Outlines the structure of the response received after querying payment status. It includes transaction details and status information. ```typescript { IsSuccess: boolean; Message: string; ValidationErrors: null | Array<{ Name?: string; Error?: string }>; Data: { InvoiceId: number; InvoiceStatus: 'Pending' | 'Paid' | 'Canceled'; InvoiceReference: string; CustomerReference: string; CreatedDate: string; ExpiryDate: string; InvoiceValue: number; Comments: string; CustomerName: string; CustomerMobile: string; CustomerEmail: string; UserDefinedField: string; InvoiceDisplayValue: string; DueDeposit: number; DepositStatus: string; InvoiceItems: IInvoiceItem[]; InvoiceTransactions: []; Suppliers: []; }; } ``` -------------------------------- ### Get and Validate MyFatoorah Webhook Secret Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/configuration.md Retrieve the webhook secret from environment variables and ensure it is set. This is crucial for authenticating incoming webhook requests. ```typescript const secret = process.env.MYFATOORAH_WEBHOOK_SECRET; if (!secret) { throw new Error('MYFATOORAH_WEBHOOK_SECRET environment variable is required'); } ``` -------------------------------- ### Get Refund Status Request Body Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/endpoints.md Defines the structure for the request body when calling the getRefundStatus endpoint. Key and KeyType are required fields to identify the refund. ```typescript { Key: string; KeyType: TRefundKeyType; } ``` -------------------------------- ### Handle Payment Initiation Response Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/api-reference-myfatoorah.md Demonstrates how to process the response from the initiatePayment method, checking for success and logging available payment methods or error messages. ```typescript // Handle response if (response1.IsSuccess) { console.log('Available payment methods:', response1.Data.PaymentMethods); response1.Data.PaymentMethods.forEach(method => { console.log(`${method.PaymentMethodEn}: ID ${method.PaymentMethodId}`); }); } else { console.error('Error:', response1.Message); } ``` -------------------------------- ### Get Payment Status Request Body Schema Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/endpoints.md Defines the structure for the request body when querying payment status. It requires a 'Key' and 'KeyType' to identify the transaction. ```typescript { Key: string; KeyType: TKeyType; } ``` -------------------------------- ### Recommended Environment Variables for MyFatoorah Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/configuration.md Set these environment variables for API and webhook configuration. Ensure sensitive keys are kept secure. ```bash # API Configuration MYFATOORAH_API_KEY=your_api_key_here MYFATOORAH_COUNTRY=EGY MYFATOORAH_TEST_MODE=false # Webhook Configuration MYFATOORAH_WEBHOOK_SECRET=your_webhook_secret_here # Application Environment NODE_ENV=production ``` -------------------------------- ### Instantiate MyFatoorah in Test Mode Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/configuration.md Initializes the MyFatoorah payment gateway for testing purposes using a specific country code and enabling test mode. ```typescript import { MyFatoorah } from 'myfatoorah-toolkit'; // Test mode (development/testing) const paymentTest = new MyFatoorah('EGY', true); ``` -------------------------------- ### Get Refund Status Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/README.md Check the status of a refund request using the Invoice ID, Refund Reference, or Refund ID. The status can be refunded, rejected, or pending. ```javascript payment.getRefundStatus(key, keyType); ``` ```javascript payment.getRefundStatus('1647850', 'InvoiceId') .then((data) => data).catch(err => err); ``` -------------------------------- ### Instantiate MyFatoorah with Environment Detection Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/configuration.md Configures the MyFatoorah payment gateway by dynamically determining the environment (test/production), country code, and API key from environment variables. ```typescript import { MyFatoorah } from 'myfatoorah-toolkit'; // With environment detection const testMode = process.env.NODE_ENV !== 'production'; const payment = new MyFatoorah( process.env.MYFATOORAH_COUNTRY || 'EGY', testMode, process.env.MYFATOORAH_API_KEY ); ``` -------------------------------- ### Initiate Payment Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/README.md Initiate a payment by providing the amount and optionally the currency ISO code. Handles the retrieval of available payment methods. ```javascript payment.initiatePayment(amount, currencyISOCode) ``` ```javascript payment.initiatePayment(100).then((data) => data).catch(err => err); ``` ```javascript payment.initiatePayment(100, 'SAR').then((data) => data).catch(err => err); ``` -------------------------------- ### Handling MyFatoorah API Server Errors Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/errors.md Example of how to check for and handle server errors in your application's response from MyFatoorah. Consider implementing retry logic for transient errors. ```typescript const response = await payment.initiatePayment(100); if (!response.IsSuccess) { if (response.Message.includes('unexpected')) { console.error('MyFatoorah API is temporarily unavailable'); // Implement retry logic with exponential backoff setTimeout(() => retryRequest(), 5000); } } ``` -------------------------------- ### Get Refund Status by Different Keys Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/api-reference-myfatoorah.md Retrieves the current status of a refund request using various identifier types. Ensure the MyFatoorah client is initialized with the correct credentials and environment. ```typescript const payment = new MyFatoorah('QAT', true); // Query by invoice ID const response1 = await payment.getRefundStatus('1647850', 'InvoiceId'); // Query by refund ID const response2 = await payment.getRefundStatus('123456', 'RefundId'); // Query by refund reference const response3 = await payment.getRefundStatus('REF-2024-001', 'RefundReference'); if (response1.IsSuccess) { response1.Data.RefundStatusResult.forEach(refund => { console.log('Refund ID:', refund.RefundId); console.log('Status:', refund.RefundStatus); // 'Refunded', 'Canceled', or 'Pending' console.log('Amount:', refund.RefundAmount); }); } ``` -------------------------------- ### Import MyFatoorah Toolkit Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/README.md Import the MyFatoorah class into your project using either CommonJS or ES6 syntax. ```javascript // CommonJS version const { Myfatoorah } = require('myfatoorah-toolkit'); // ES6 version import { MyFatoorah } from 'myfatoorah-toolkit' ``` -------------------------------- ### Get Refund Status Response Schema Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/endpoints.md Outlines the structure of the response received from the getRefundStatus endpoint. It includes success status, messages, validation errors, and detailed refund status information. ```typescript { IsSuccess: boolean; Message: string; ValidationErrors: null | Array<{ Name?: string; Error?: string }>; Data: { RefundStatusResult: Array<{ RefundId: number; RefundStatus: 'Refunded' | 'Canceled' | 'Pending'; InvoiceId: number; Amount: number; RefundReference: string; RefundAmount: number; }>; }; } ``` -------------------------------- ### MyFatoorah Configuration Documentation Template Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/configuration.md A JSDoc template outlining the required and optional environment variables for configuring the MyFatoorah SDK. This serves as a reference for developers setting up the integration. ```typescript /** * MyFatoorah Configuration * * Required Environment Variables: * - MYFATOORAH_COUNTRY: Country ISO code (default: 'EGY') * - MYFATOORAH_API_KEY: API key for production (required if NODE_ENV=production) * - MYFATOORAH_WEBHOOK_SECRET: Webhook validation secret * - NODE_ENV: 'production' or 'development' (controls API endpoint) * * Optional Environment Variables: * - PAYMENT_CALLBACK_URL: Success redirect URL * - PAYMENT_ERROR_URL: Error redirect URL */ ``` -------------------------------- ### Handle Refund Amount Exceeding Invoice Amount Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/errors.md When making a refund, ensure the refund amount does not exceed the original invoice value. This code snippet demonstrates how to get the invoice status and cap the refund amount to the maximum allowed. ```typescript const invoiceStatus = await payment.getPaymentStatus('614525', 'InvoiceId'); if (invoiceStatus.IsSuccess) { const maxRefund = invoiceStatus.Data.InvoiceValue; const refundResponse = await payment.makeRefund({ KeyType: 'InvoiceId', Key: '614525', RefundChargeOnCustomer: false, ServiceChargeOnCustomer: false, Amount: Math.min(userRequestedAmount, maxRefund), Comment: 'Partial refund' }); } ``` -------------------------------- ### MyFatoorah Class Constructor Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/api-reference-myfatoorah.md Instantiate the MyFatoorah class for test or production environments. Provide the country ISO code, a boolean for test mode, and optionally your API key for production. ```typescript import { MyFatoorah } from 'myfatoorah-toolkit'; // Test mode instance const paymentTest = new MyFatoorah('EGY', true); // Production mode instance const paymentProd = new MyFatoorah('EGY', false, process.env.PAYMENT_API_KEY); ``` -------------------------------- ### Express.js Webhook Handler with Signature Validation Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/api-reference-validate-signature.md A complete Express.js example demonstrating how to set up a webhook endpoint, extract the signature from the request header, and validate it using `validateSignature` before processing the webhook data. Ensure your webhook secret is stored securely in environment variables. ```typescript import express from 'express'; import { validateSignature } from 'myfatoorah-toolkit'; const app = express(); app.use(express.json()); const MYFATOORAH_SECRET = process.env.MYFATOORAH_WEBHOOK_SECRET; app.post('/webhook/myfatoorah', async (req, res) => { try { // Extract signature from request header const signature = req.get('MyFatoorah-Signature'); if (!signature) { return res.status(400).json({ error: 'Missing signature header' }); } // Validate the signature const isValid = await validateSignature(req.body, signature, MYFATOORAH_SECRET); // Process webhook data const webhookData = req.body.Data; console.log('Webhook received:', webhookData); // Handle the webhook event if (webhookData.InvoiceStatus === 'Paid') { // Process successful payment console.log('Payment confirmed for invoice:', webhookData.InvoiceId); } res.status(200).json({ success: true }); } catch (error) { console.error('Invalid webhook signature:', error.message); res.status(401).json({ error: 'Signature validation failed' }); } }); app.listen(3000, () => { console.log('Webhook server running on port 3000'); }); ``` -------------------------------- ### IInitiatePaymentResponse Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/types.md Represents the response structure specifically for the `initiatePayment()` method. It includes details about available payment methods for initiating a transaction. ```APIDOC ## IInitiatePaymentResponse ### Description Response from the `initiatePayment()` method. Contains a list of available payment methods for initiating a transaction. ### Interface `IInitiatePaymentResponse` ### Fields - **IsSuccess** (`boolean`) - Indicates whether the request was successful (`true`) or failed (`false`). - **Message** (`string`) - Human-readable message describing the response. - **ValidationErrors** (`IValidationError[] | null`) - Array of validation errors if any, otherwise `null`. - **Data** (`object`) - Contains payment method details. - **PaymentMethods** (`IInitiatePayment[]`) - An array of available payment methods. - **PaymentMethodId** (`number`) - Unique identifier for the payment method. Use this in `executePayment()`. - **PaymentMethodAr** (`string`) - Payment method name in Arabic. - **PaymentMethodEn** (`string`) - Payment method name in English. - **IsDirectPayment** (`boolean`) - Whether the payment method supports direct payment flow. - **ServiceCharge** (`number`) - Additional service charge amount. - **TotalAmount** (`number`) - Total amount including service charge. - **CurrencyIso** (`TCurrencyCodes`) - Currency code for the amounts. - **ImageUrl** (`string`) - URL to payment method icon/logo. ### Returned By `initiatePayment()` ``` -------------------------------- ### Switch to Production Mode Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/configuration.md Use this snippet to transition from test mode to production mode. Ensure you set `testMode` to `false` and provide your production API key via an environment variable. ```typescript // Before (test mode) const payment = new MyFatoorah('EGY', true); // After (production mode) const payment = new MyFatoorah( 'EGY', false, process.env.MYFATOORAH_API_KEY ); ``` -------------------------------- ### Execute Payment Endpoint Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/getting-started.md Handles POST requests to initiate a payment. It requires amount, methodId, customerName, and customerEmail in the request body. Ensure MYFATOORAH_API_KEY and APP_URL environment variables are set. ```typescript import express from 'express'; import { MyFatoorah } from 'myfatoorah-toolkit'; const app = express(); app.use(express.json()); const payment = new MyFatoorah('EGY', false, process.env.MYFATOORAH_API_KEY); // POST /api/payments/execute app.post('/api/payments/execute', async (req, res) => { try { const { amount, methodId, customerName, customerEmail } = req.body; const response = await payment.executePayment(amount, methodId, { CustomerName: customerName, CustomerEmail: customerEmail, CallBackUrl: `${process.env.APP_URL}/payment/callback` }); if (response.IsSuccess) { res.json({ success: true, invoiceId: response.Data.InvoiceId, paymentUrl: response.Data.PaymentURL }); } else { res.status(400).json({ success: false, error: response.Message }); } } catch (error) { res.status(500).json({ success: false, error: 'Payment processing failed' }); } }); app.listen(3000); ``` -------------------------------- ### Query Payment Status with MyFatoorah SDK Source: https://github.com/kareemwezza/myfatoorah-payment/blob/main/_autodocs/api-reference-myfatoorah.md Demonstrates how to use the getPaymentStatus method to retrieve payment status by InvoiceId, PaymentId, or CustomerReference. Ensure the MyFatoorah class is initialized with the correct country code and gateway settings. ```typescript const payment = new MyFatoorah('SAU', true); // Query by invoice ID const response1 = await payment.getPaymentStatus('613842', 'InvoiceId'); // Query by payment ID const response2 = await payment.getPaymentStatus('PAY-12345', 'PaymentId'); // Query by customer reference const response3 = await payment.getPaymentStatus('CUST-98765', 'CustomerReference'); if (response1.IsSuccess) { const invoice = response1.Data; console.log('Status:', invoice.InvoiceStatus); // 'Pending', 'Paid', or 'Canceled' console.log('Amount:', invoice.InvoiceValue); console.log('Customer:', invoice.CustomerName); } ```