# Create Payment Intent Source: https://docs.fenanpay.com/api-reference/endpoint/create-payment-link POST /api/v1/payment/intent # Create Payment Intent Source: https://docs.fenanpay.com/api-reference/endpoint/create-payment-link-sandbox POST /api/v1/payment/sandbox/intent # Express Checkout Source: https://docs.fenanpay.com/api-reference/endpoint/express-pay POST /api/v1/payment/express/pay # Express Checkout Source: https://docs.fenanpay.com/api-reference/endpoint/express-pay-sandbox POST /api/v1/payment/express/sandbox/pay # Get Payment Intent Source: https://docs.fenanpay.com/api-reference/endpoint/get-payment-intent GET /api/v1/payment/checkout/{paymentIntentId} # Get Payment Intent Source: https://docs.fenanpay.com/api-reference/endpoint/get-payment-intent-sandbox GET /api/v1/payment/sandbox/checkout/{paymentIntentId} # Introduction Source: https://docs.fenanpay.com/api-reference/introduction API endpoints Playground ## API Reference Welcome to the Fenan Pay API Reference and Playground. This section provides detailed information about the available API endpoints, request and response formats, and other essential details to help you integrate Fenan Pay into your application. ### Base URL The base URL for all API requests is: ``` https://api.fenanpay.com ``` ### Authentication All API requests require authentication. Authentication is done using an API key, which is passed in the header of the request. # Get Started Source: https://docs.fenanpay.com/introduction Selam Developers, Welcome to FenanPay. Here you will find all the resources you need to get started with our payment gateway. Please feel free to contact us for any questions or concerns. Also you can join our community to get the latest news and updates. Hero Light Start with the quickstart guide to get you up and running in no time. Get started quickly with our payment integration guide Explore our comprehensive API documentation Learn how to implement our seamless checkout process Discover our fast and convenient payment solution Understand our robust security measures and best practices # API and Authentication Source: https://docs.fenanpay.com/payment/apikey How to use API Key ## API Key To interact with the Fenan Pay API, you need to provide an API key. This key is used to authenticate your requests to the API. You can create and manage your API keys in the Fenan Pay dashboard. ### Creating API Keys To create an API key, follow these steps: 1. Log in to your [Fenan Pay dashboard](https://dashboard.fenanpay.com). 2. Navigate to the API Management section. 3. Create a new API key for your environment (test or live). For detailed instructions, refer to the [API Key Creation Guide](https://dashboard.fenanpay.com/merchant/dashboard/apimanagement). ### Passing the API Key When making requests to the Fenan Pay API, you need to include the API key in the request headers. The header should be named `apiKey` and its value should be your API key. # null Source: https://docs.fenanpay.com/payment/checkout If you need a modern, standard, intuitive checkout for your platform, Fenan offers a hosted checkout solution. The general flow is that the customer will be redirected to the Fenan checkout page, and after the payment is completed, the customer will be redirected back to your platform. You do this by creating a payment intent first, for which you will get a checkout URL for that specific transaction, and you need to redirect the user to that page. After the payment is done, the customer is redirected back, and a webhook is sent to your server. ## Authentication Setting API Key in Headers. Learn more about API Key [here](/payment/apikey). ```javascript theme={null} const headers = { 'apiKey': 'YOUR_API_KEY' // Replace with your actual API key }; ``` ## How to Create Payment Intent To create a payment intent, all you need to do is send a POST HTTP call to the appropriate endpoint based on your environment. Include the `apiKey` in the request headers and provide the required parameters in the body as described in the [Parameters](#parameters) section. `https://api.fenanpay.com/api/v1/payment/sandbox/intent` `https://api.fenanpay.com/api/v1/payment/intent` ### Parameters The following tables describe the fields required for creating a payment intent. All validations apply unless otherwise specified. #### Payment Intent Request | Field | Type | Description | Required | | ------------------------ | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | amount | number | The total amount for the payment. Must be a positive number with up to two decimal places. Must be greater than or equal to 1.00. | true\* | | items | array of objects | List of items included in the payment. Total calculated amount must equal the amount field if both are provided. Must sum to at least 1.00. | false\* | | currency | string | The currency for the payment (ETB, USD). | true | | paymentIntentUniqueId | string | Unique identifier for the payment intent. | true | | paymentLinkUniqueId | string | Unique identifier for the payment link. | false | | methods | array of strings | List of payment methods to be accepted (TELE\_BIRR, TELE\_BIRR\_USSD, CBE, ETS\_SWITCH, M\_PESA). If empty array is passed, all enabled methods will be selected. | true | | splitPayment | array of objects | Details for splitting the payment among multiple beneficiaries. | false | | returnUrl | string | URL to redirect the user after payment completion. Must be a valid URL format. | true | | expireIn | integer | Time in seconds before the payment intent expires. Minimum 5 seconds. | true | | callbackUrl | string | URL to notify the merchant system of the payment status. Must be a valid URL format. | false | | commissionPaidByCustomer | boolean | Indicates if the commission is paid by the customer. | true | | customerInfo | object | Information about the customer. | false | \* Either amount or items must be provided. If both are provided, they must match. #### Payment Item | Field | Type | Description | Required | | ----------- | ------- | --------------------------------------------------------------------------- | -------- | | name | string | Name of the item. | true | | description | string | Description of the item. | false | | image | string | URL of the item's image. | false | | quantity | integer | Quantity of the item. Minimum value of 1. | true | | type | string | Type of the item (SERVICE, DIGITAL\_PRODUCT, PHYSICAL\_PRODUCT). | true | | price | number | Price of the item. Must be a positive number with up to two decimal places. | true | #### Split Payment Details | Field | Type | Description | Required | | ------------- | ------ | ---------------------------------------------------------------------------- | -------- | | amount | number | Amount to be split. Must be a positive number with up to two decimal places. | true | | bank | string | Bank for the split payment. | true | | splitType | string | Type of split (PERCENTAGE, NUMBER). | true | | creditAccount | string | Credit account for the split payment. | true | ### Important Validation Rules #### Customer Info | Field | Type | Description | Required | | ---------------- | ------- | --------------------------------------------------------------------------------------------- | -------- | | email | string | Email of the customer. | false | | phone | string | Phone number of the customer. Must start with 9 and be followed by 8 digits (9 digits total). | false | | name | string | Name of the customer. | false | | isPhoneUpdatable | boolean | Determines if the phone number can be edited by the user during checkout. | false | ### Interface Explanation The `PaymentIntentRequest` interface is used to create a payment intent with Fenan Pay. Below is an explanation of each field: * **amount**: The total amount for the payment. This is a required field. * **items**: An array of objects representing the items included in the payment. This field is optional and can be null or empty if the amount is set. If both `items` and `amount` are specified, the sum of `items.price` must equal the `amount`. * **PaymentItem**: * **name**: The name of the item. (required) * **description**: A description of the item. (optional) * **image**: URL of the item's image. (optional) * **quantity**: The quantity of the item. Must be an integer with a minimum value of 1. (required) * **type**: The type of the item. Can be one of `SERVICE`, `DIGITAL_PRODUCT`, or `PHYSICAL_PRODUCT`. (required) * **price**: The price of the item. (required) * **currency**: The currency for the payment. Supported values are `ETB` and `USD`. This is a required field. * **paymentIntentUniqueId**: A unique identifier for the payment intent. This idempotent key is used to identify a unique payment intent shared between Fenan Pay and the merchant system. It must be unique for every payment intent. (required) * **methods**: An array of strings representing the payment methods to be accepted. If this field is empty, all enabled payment methods will be selected. Supported values include `TELE_BIRR_USSD`, `CBE`, `ETS_SWITCH`, and `M_PESA`. (required). If empty array is passed, all enabled methods will be selected. * **splitPayment**: An array of objects detailing the split payment among multiple beneficiaries. This field is optional and can be null. * **SplitPaymentDetails**: * **amount**: The amount to be split. Can be a percentage or a number. (required) * **bank**: The bank for the split payment. Ensure the bank supports withdrawal to avoid errors. (required) * **splitType**: The type of split. Can be `PERCENTAGE` or `NUMBER`. (required) * **creditAccount**: The credit account for the split payment. (required) * **returnUrl**: The URL to redirect the user after payment completion. This should be a valid URL. (required) * **expireIn**: The time in seconds before the payment intent expires. Once expired, the user can no longer make a purchase, and an Expire event will be sent as a webhook. (required) * **callbackUrl**: The URL to notify the merchant system of the payment status. If null, it defaults to the webhook settings on the dashboard. This URL will notify the merchant system of events such as failure, timeout/expired, and success. (optional) * **commissionPaidByCustomer**: Indicates if the commission is paid by the customer. (required) * **customerInfo**: An object containing information about the customer. This field is optional but can be used to take advantage of Fenan Pay's analytics service. * **CustomerInfoRequestDto**: * **email**: The email of the customer. (optional) * **phone**: The phone number of the customer. Must start with 9 and be followed by 8 digits (9 digits total). (optional) * **name**: The name of the customer. (optional) * **isPhoneUpdatable**: Determines if the phone number can be edited by the user during checkout. When set to `false`, the phone number field will be read-only in the checkout interface. (optional) 1. **Amount or Items Required**: * You must provide either an amount or a non-empty list of items * If both are provided, the sum of item prices must equal the amount field * The total amount must be greater than or equal to 1.00 2. **URL Requirements**: * returnUrl must be provided and must be a valid URL format * callbackUrl, if provided, must be a valid URL format 3. **Payment Items**: * Each item must have a name, quantity (minimum 1), type, and price * Price must be a positive number with up to two decimal places 4. **Split Payment**: * If provided, each split payment must include amount, bank, splitType, and creditAccount * Amount must be a positive number with up to two decimal places 5. **Phone Number**: * If provided, phone number must start with 9 and be followed by exactly 8 digits (9 digits total) * Example: "944142029" ### Example Request ```json theme={null} { "amount": 1, "items": [ { "name": "Product 1", "description": "Description of Product 1", "image": "https://example.shop/storage/app/public/product/thumbnail/2024-01-27-65b55b6b622aa.png", "quantity": 1, "type": "PHYSICAL_PRODUCT", "price": 0.5 }, { "name": "Product 2", "description": "Description of Product 2", "image": "https://example.shop/storage/app/public/product/thumbnail/2024-05-09-663c84d4ba7af.png", "quantity": 1, "type": "DIGITAL_PRODUCT", "price": 0.5 } ], "currency": "ETB", "paymentIntentUniqueId": "95s5wfr000d39s33d01dlhs2521s8", "methods": ["TELE_BIRR_USSD", "CBE", "ETS_SWITCH"], "returnUrl": "https://fenanpay.com", "expireIn": 36000, "callbackUrl": "https://webhook.site/d3c8694f-6bc5-4375-b4df-ef3d923d0ab7", "commissionPaidByCustomer": false, "customerInfo": { "email": "customer@example.com", "phone": "944142029", "isPhoneUpdatable": false, "name": "Customer Name" } } ``` ### Response of the Request When you make a request to the Fenan Pay API, you will receive a response indicating the status of your request. Below are examples of both a successful response and an error response. #### Successful Response Successful response will have a status code of 200. ```json theme={null} { "status": 200, "message": "Payment intent saved successfully.", "content": "https://checkout.fenanpay.com/payment/checkout/ad882d19-e58a-435f-9a31-fb74ed60bdb5" } ``` #### Error Response Error response will have a status code of 4xx. ```json theme={null} { "status": 409, "message": "Duplicate key violation: Key (unique_id)=(95s5wfr000d39s33d01dsslhs2521sshj81) already exists." } ``` | Field | Description | | ------- | ----------------------------------------- | | status | Status of the response | | message | Message indicating success or error | | content | Checkout URL if the request is successful | ## Making payment Checkout Image After the payment is done, the customer will be redirected back to your platform. You will receive a webhook notification of the payment status. Learn more about webhooks [here](./webhooks). # null Source: https://docs.fenanpay.com/payment/expresspay ## ExpressPay: Direct Payment Processing Ideal for applications with a predefined payment flow or a single preferred payment method. ExpressPay offers a streamlined approach to payment processing. This integration method is designed for scenarios where: * You have already implemented a checkout process in your application. * A specific payment method has been pre-selected or is preferred. * You aim to minimize the number of steps in the payment flow. With ExpressPay, you can initiate payment requests directly, bypassing the need for a separate checkout page. This results in a more efficient and focused payment experience for your customers. If you need a modern, standard, intuitive checkout for your platform, Fenan offers a hosted checkout solution. The general flow is that the customer will be redirected to the Fenan checkout page, and after the payment is completed, the customer will be redirected back to your platform. You do this by creating a payment intent first, for which you will get a checkout URL for that specific transaction, and you need to redirect the user to that page. After the payment is done, the customer is redirected back, and a webhook is sent to your server. ## Authentication Setting API Key in Headers. Learn more about API Key [here](/payment/apikey). ```javascript theme={null} const headers = { 'apiKey': 'YOUR_API_KEY' // Replace with your actual API key }; ``` ## How to Create Express payment If you are coming from the checkout process, everything remains the same except for the `baseUrl`, `method` parameter and the Response. You will need to specify one payment method in the `method` parameter. Every other parameter remains the same. Here method is string only accepting one payment type. To create a payment intent, all you need to do is send a POST HTTP call to the appropriate endpoint based on your environment. Include the `apiKey` in the request headers and provide the required parameters in the body as described in the [Parameters](#parameters) section. `https://api.fenanpay.com/api/v1/payment/express/sandbox/pay` `https://api.fenanpay.com/api/v1/payment/express/pay` ### Parameters The following tables describe the fields required for creating an express payment. #### Express Payment Request | Field | Type | Description | Required | | ------------------------ | ---------------- | ------------------------------------------------------------------------------------------ | -------- | | amount | number | The total amount for the payment. Must be a positive number with up to two decimal places. | true\* | | items | array of objects | List of items included in the payment. | false | | currency | string | The currency for the payment. | true | | paymentIntentUniqueId | string | Unique identifier for the payment intent. | true | | paymentLinkUniqueId | string | Unique identifier for the payment link. | false | | phoneNumber | string | Phone number for the payment (required for M-PESA). | false | | debitAccount | string | Debit account for the payment. | false | | description | string | Description of the payment. | false | | method | string | Payment method code (TELE\_BIRR\_USSD, CBE, ETS\_SWITCH, M\_PESA). | true | | splitPayment | array of objects | Details for splitting the payment among multiple beneficiaries. | false | | returnUrl | string | URL to redirect the user after payment completion (required for non-M-PESA). | true\* | | expireIn | integer | Time in seconds before the payment intent expires. | true | | callbackUrl | string | URL to notify the merchant system of the payment status. Must be a valid URL format. | false | | commissionPaidByCustomer | boolean | Indicates if the commission is paid by the customer. | true | | customerInfo | object | Information about the customer. | false | | testMode | object | Test mode configuration (only for sandbox environment). | true\* | \* returnUrl is required for all payment methods except M-PESA\ \* testMode is only required in sandbox environment \* Either amount or items must be provided #### Payment Item | Field | Type | Description | Required | | ----------- | ------- | ---------------------------------------------------------------- | -------- | | name | string | Name of the item. | true | | description | string | Description of the item. | false | | image | string | URL of the item's image. | false | | quantity | integer | Quantity of the item. | true | | type | string | Type of the item (SERVICE, DIGITAL\_PRODUCT, PHYSICAL\_PRODUCT). | true | | price | number | Price of the item. | true | #### Split Payment Details | Field | Type | Description | Required | | ------------- | ------ | ------------------------------------- | -------- | | amount | number | Amount to be split. | true | | bank | string | Bank for the split payment. | true | | splitType | string | Type of split (PERCENTAGE, NUMBER). | true | | creditAccount | string | Credit account for the split payment. | true | #### Customer Info Request | Field | Type | Description | Required | | ----- | ------ | ----------------------------- | -------- | | email | string | Email of the customer. | false | | phone | string | Phone number of the customer. | false | | name | string | Name of the customer. | false | #### Test Mode (Sandbox Only) | Field | Type | Description | Required | | ---------------- | ------ | ----------------------------------------------------------------------------------------- | ----------- | | testModeType | string | Type of test mode (ACTUAL\_TEST, SIMULATED\_TEST). | true | | simulationStatus | string | Simulation status (SUCCESS, FAILED, etc.). Required when testModeType is SIMULATED\_TEST. | conditional | ### Interface Explanation The `ExpressPaymentRequestDto` interface is used to create an express payment with Fenan Pay. Below is an explanation of each field: * **amount**: The total amount for the payment. This is a required field with a positive number and up to two decimal places. * **items**: An array of objects representing the items included in the payment. This field is optional, but either `items` or `amount` must be provided. * **PaymentItem**: * **name**: The name of the item. (required) * **description**: A description of the item. (optional) * **image**: URL of the item's image. (optional) * **quantity**: The quantity of the item. Must be an integer with a minimum value of 1. (required) * **type**: The type of the item. Can be one of `SERVICE`, `DIGITAL_PRODUCT`, or `PHYSICAL_PRODUCT`. (required) * **price**: The price of the item. (required) * **currency**: The currency for the payment. Supported values are `ETB` and `USD`. This is a required field. * **paymentIntentUniqueId**: A unique identifier for the payment intent. This idempotent key is used to identify a unique payment intent shared between Fenan Pay and the merchant system. It must be unique for every payment intent. (required) * **paymentLinkUniqueId**: A unique identifier for the payment link. (optional) * **phoneNumber**: Phone number for the payment. Required for M-PESA payments if not provided in customerInfo. (optional) * **debitAccount**: Debit account for the payment. (optional) * **description**: Description of the payment. (optional) * **method**: A string representing the payment method code. Supported values include `TELE_BIRR_USSD`, `CBE`, `ETS_SWITCH`, and `M_PESA`. (required) * **splitPayment**: An array of objects detailing the split payment among multiple beneficiaries. This field is optional. * **SplitPaymentDetails**: * **amount**: The amount to be split. Can be a percentage or a number. (required) * **bank**: The bank for the split payment. Ensure the bank supports withdrawal to avoid errors. (required) * **splitType**: The type of split. Can be `PERCENTAGE` or `NUMBER`. (required) * **creditAccount**: The credit account for the split payment. (required) * **returnUrl**: The URL to redirect the user after payment completion. This should be a valid URL. Required for all payment methods except M-PESA. * **expireIn**: The time in seconds before the payment intent expires. Must be at least 5 seconds. Once expired, the user can no longer make a purchase, and an Expire event will be sent as a webhook. (required) * **callbackUrl**: The URL to notify the merchant system of the payment status. If null, it defaults to the webhook settings on the dashboard. This URL will notify the merchant system of events such as failure, timeout/expired, and success. (optional) * **commissionPaidByCustomer**: Indicates if the commission is paid by the customer. (required) * **customerInfo**: An object containing information about the customer. This field is optional but can be used to take advantage of Fenan Pay's analytics service. * **CustomerInfoRequestDto**: * **email**: The email of the customer. (optional) * **phone**: The phone number of the customer. Required for M-PESA if not provided in the phoneNumber field. (optional) * **name**: The name of the customer. (optional) * **testMode**: An object containing test mode configuration. Required only in sandbox environment. * **TestModeDto**: * **testModeType**: The type of test mode. Can be `ACTUAL_TEST` or `SIMULATED_TEST`. (required) * **simulationStatus**: The simulation status. Required when testModeType is `SIMULATED_TEST`. (conditional) ### Example Request ```json theme={null} { "amount": 1, "items": [ { "name": "Product 1", "description": "Description of Product 1", "image": "https://example.shop/storage/app/public/product/thumbnail/2024-01-27-65b55b6b622aa.png", "quantity": 1, "type": "PHYSICAL_PRODUCT", "price": 0.5 }, { "name": "Product 2", "description": "Description of Product 2", "image": "https://example.shop/storage/app/public/product/thumbnail/2024-05-09-663c84d4ba7af.png", "quantity": 1, "type": "DIGITAL_PRODUCT", "price": 0.5 } ], "currency": "ETB", "paymentIntentUniqueId": "91dhsd52aaadssaaaaaaagaqwa", "method": "TELE_BIRR_USSD", "returnUrl": "http://cbe.com", "expireIn": 36000, "callbackUrl": "https://webhook.site/644fdd21-885e-4c51-a2bd-1926e4c30c3b", "commissionPaidByCustomer": false, "customerInfo": { "email": "test@gmail.com", "phone": "251710214707", "name": "customer name" }, "testMode": { "testModeType": "ACTUAL_TEST", "simulationStatus": "FAILED" } } ``` ### M-PESA Payment Example ```json theme={null} { "amount": 1, "currency": "ETB", "paymentIntentUniqueId": "91dhsd52aaadssaaaaaaagaqwa", "method": "M_PESA", "phoneNumber": "251710214707", "expireIn": 36000, "callbackUrl": "https://webhook.site/644fdd21-885e-4c51-a2bd-1926e4c30c3b", "commissionPaidByCustomer": false, "customerInfo": { "email": "test@gmail.com", "name": "customer name" }, "testMode": { "testModeType": "ACTUAL_TEST" } } ``` ### Response of the Request When you make a request to the Fenan Pay API, you will receive a response indicating the status of your request. Below are examples of both a successful response and an error response. #### Successful Response Successful response will have a status code of 200. ```json theme={null} { "status": 200, "message": "Payment intent saved successfully.", "content": { "paymentUrl": "https://ethiotelecom.com/payment/checkout/ad882d19-e58a-435f-9a31-fb74ed60bdb5", "transactionId": "ad882d19-e58a-435f-9a31-fb74ed60bdb5", "status": "SUCCESS", "message": "Payment initialized successfully." } } ``` #### Error Response Error response will have a status code of 4xx. ```json theme={null} { "status": 409, "message": "Duplicate key violation: Key (unique_id)=(95s5wfr000d39s33d01dsslhs2521sshj81) already exists." } ``` | Field | Description | | ------- | -------------------------------------------------------- | | status | Status of the response | | message | Message indicating success or error | | content | Checkout is object [Payment Response](#payment-response) | #### Payment Response The `Payment Response` object contains the details of the response from the payment service provider. Below is a table describing the fields in the `PspPaymentResponseDto` object. | Field | Type | Description | Required | | ------------- | ------------- | ------------------------------------------------ | -------- | | paymentUrl | String | URL to redirect the user for completing payment. | false | | transactionId | String | Unique identifier for the transaction. | false | | status | PaymentStatus | Status of the payment. | true | | message | String | Message indicating success or error. | false | `PaymentStatus` is an enumeration that represents the possible statuses of a payment. The possible values are: * `SUCCESS` * `FAILURE` ## Making payment After the payment is done, the customer will be redirected back to your platform. You will receive a webhook notification of the payment status. Learn more about webhooks [here](./webhooks). ### Important Validation Rules 1. **Amount or Items Required**: You must provide either an amount or a non-empty list of items. 2. **Return URL Requirement**: A valid returnUrl is required for all payment methods except M\_PESA, TELE\_BIRR\_USSD, E\_BIRR and CBE. 3. **On M\_PESA, TELE\_BIRR\_USSD, E\_BIRR and CBE Phone Number Requirement**: For phone number must be provided either in the `phoneNumber` field or in the `customerInfo.phone` field. # Payment Overview Source: https://docs.fenanpay.com/payment/overview Fenan Pay integration options Fenan Pay offers two robust payment integration options to cater to diverse business needs and user experiences. Each option provides unique advantages, allowing you to choose the most suitable solution for your application. Streamlined payment processing for pre-selected methods Comprehensive, hosted payment page with multiple options ## Choosing the Right Option Both ExpressPay and Checkout are designed to provide secure, efficient payment processing. Your choice depends on your specific business requirements and desired user experience. Consider the following when making your decision: * **User Experience**: Do you want a streamlined, direct payment process (ExpressPay) or a full-featured checkout page with multiple options (Checkout)? * **Integration Complexity**: Are you looking for a quick, straightforward integration (ExpressPay) or a more comprehensive but managed solution (Checkout)? * **Payment Method Variety**: Do you need to offer multiple payment methods (Checkout)? Regardless of your choice, Fenan Pay ensures a secure, reliable payment experience for both you and your customers. # Quickstart Source: https://docs.fenanpay.com/quickstart Get started with Fenan Pay in just 4 easy steps Fenan Pay is a powerful payment solution designed to streamline your online transactions. This quickstart guide will help you integrate Fenan Pay into your application in no time, with just 4 easy steps. Begin your journey with Fenan Pay by [creating an account](https://dashboard.fenanpay.com/signup) on our platform. Create Account Screenshot Make sure to verify your email address after registration to activate your account. Once your account is set up, you'll need to [create API keys](https://dashboard.fenanpay.com/merchant/dashboard/apimanagement) for integration. Start by creating a test API key to use in your development environment. This allows you to integrate and test Fenan Pay without processing real transactions. You can not collect real money with test API keys Create API Keys Screenshot Always keep your API keys secure and never share them publicly. Choose between ExpressPay or Checkout based on your needs, and integrate using our REST API or one of our SDKs. Use ExpressPay if you already have a checkout page and want to reduce number of clicks. Read more about [ExpressPay](/payment/expresspay) Use our Checkout solution if you don't have a checkout page and want a fully hosted payment experience. Read more about [Checkout](/payment/checkout) Don't forget to handle webhook events to keep your system in sync with payment statuses. Read more about [Webhooks](/payment/webhooks) When you're ready to accept real payments, switch to live mode by completing these steps: 1. Fill out the KYC (Know Your Customer) form in your Fenan Pay [dashboard](https://dashboard.fenanpay.com/merchant/dashboard). 2. Create a live API key once your KYC is approved. Ensure all your integration tests pass in the test environment before switching to live mode. Congratulations! You've successfully set up Fenan Pay. For more detailed information on each step, please refer to our comprehensive documentation. # null Source: https://docs.fenanpay.com/transaction/payment-intent-object Here is a table describing the structure of the `PaymentIntent` class and its related objects: #### PaymentIntent | **Field Name** | **Data Type** | **Description** | | -------------------------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------- | | `paymentIntentId` | `long` | Unique ID of the payment intent. | | `callbackUrl` | `String` | URL to send callback responses. | | `returnUrl` | `String` | URL to redirect users after completing the payment. | | `uniqueId` | `String` | Unique identifier for the payment session. | | `paymentLinkUniqueId` | `String` | Unique ID for payment link. | | `uuid` | `String` | Universally unique identifier (UUID). | | `test` | `boolean` | Specifies if the payment is in test mode. | | `commissionPaidByCustomer` | `boolean` | Indicates if the commission is paid by the customer. | | `creationDate` | `Timestamp` | Timestamp of when the payment intent was created. | | `lastUpdateDate` | `Timestamp` | Timestamp of the last update made to the payment intent. | | `expireDate` | `Timestamp` | Timestamp when the payment intent expires. | | `totalAmount` | `Long` | Total payment amount in cents. | | `currency` | `Currency (Enum)` | The currency of the payment (USD or ETB). | | `checkoutBeneficiaries` | `List` | List of split payment beneficiaries. See [`CheckoutSplitPayment`](#checkoutsplitpayment) object below. | | `productItems` | `List` | List of product items associated with the payment intent. See [`ProductItems`](#productitems) object below. | | `transaction` | `Transaction` | Transaction associated with the payment intent. See [`Transaction`](#transaction) object below. | | `merchantCustomer` | `MerchantCustomer` | The merchant's customer details. See [`MerchantCustomer`](#merchantcustomer) object below. | | `paymentMethodTypes` | `Set` | Set of payment methods used in the checkout session. eg: `TELE_BIRR_USSD`, `ETS_SWITCH`, `CBE` or `M_PESA` etc. | ### Related Objects #### CheckoutSplitPayment | **Field Name** | **Data Type** | **Description** | | --------------- | ------------------ | ------------------------------------------- | | `id` | `long` | Unique ID for the split payment. | | `accountNumber` | `String` | Account number for the split payment. | | `amount` | `Long` | Amount for the split payment. | | `splitType` | `SplitType (Enum)` | The type of split `PERCENTAGE` and `NUMBER` | #### ProductItems | **Field Name** | **Data Type** | **Description** | | ---------------- | -------------------- | ---------------------------------------------------------------------------------- | | `id` | `long` | Unique ID for the product item. | | `name` | `String` | Name of the product item. | | `image` | `String` | URL or reference to the product image. | | `quantity` | `int` | Quantity of the product purchased. | | `description` | `String` | Description of the product item. | | `productId` | `String` | Unique product identifier. | | `price` | `Long` | Price of the product in cents. | | `type` | `ProductType (Enum)` | The type/category of the product. `SERVICE`,`DIGITAL_PRODUCT` & `PHYSICAL_PRODUCT` | | `paymentIntent` | `CheckoutSession` | Reference to the payment intent session. | | `creationDate` | `Timestamp` | Creation date of the product item record. | | `lastUpdateDate` | `Timestamp` | Last update date of the product item record. | #### Transaction | **Field Name** | **Data Type** | **Description** | | ----------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------- | | `id` | `long` | Unique ID for the transaction. | | `message` | `String` | Message or note for the transaction. | | `debitAccount` | `String` | The debit account for the transaction. | | `phoneNumber` | `String` | Phone number related to the transaction. | | `trac2` | `String` | Trace information related to the transaction. | | `test` | `boolean` | Indicates if the transaction is in test mode. | | `referenceId` | `String` | Reference ID for the transaction. | | **`transactionStatus`** | **`TransactionStatus`** | **Status of the transaction. `PROCESSING`, `FAILED`, `SUCCESS`, `EXPIRED`** | | `paymentType` | `PaymentMethodType` | Payment method type for the transaction. | | `merchantNet` | `long` | Merchant's net amount. | | `adminNet` | `long` | Admin's net amount. | | `totalAmount` | `long` | Total amount of the transaction in cents. | | `pspTxId` | `String` | Transaction ID from the payment service provider. | | `virtualAccountId` | `Long` | ID of the virtual account used in the transaction. | | `virtualCardId` | `Long` | ID of the virtual card used in the transaction. | | `creationDate` | `Timestamp` | Creation date of the transaction record. | | `lastUpdateDate` | `Timestamp` | Last update date of the transaction record. | | `merchantCustomer` | `MerchantCustomer` | The merchant's customer related to the transaction. See [`MerchantCustomer`](#MerchantCustomer) object below. | #### MerchantCustomer | **Field Name** | **Data Type** | **Description** | | -------------- | ------------- | -------------------------------------- | | `id` | `Long` | Unique ID for the merchant customer. | | `name` | `String` | Name of the merchant customer. | | `email` | `String` | Email of the merchant customer. | | `phone` | `String` | Phone number of the merchant customer. | # null Source: https://docs.fenanpay.com/transaction/single-payment-intent ### Check Transaction Status To check the status of a payment intent, use the `paymentIntentUniqueId`. This allows you to check the status of the payment intent, specifically the `transaction.transactionStatus`. ### Endpoint **POST Request** `https://api.fenanpay.com/api/v1/payment/intent/api/status` **Headers** ``` apikey: YOUR_API_KEY ``` **Request Body** ```json theme={null} { "paymentIntentUniqueId": "2404542451810305" } ``` This endpoint returns a [Payment Intent object](/transaction/payment-intent-object). # Generate Key Pairs Source: https://docs.fenanpay.com/webhook/generate-keys This guide explains how to generate RSA public and private key pairs using both **OpenSSL** (via Bash) and **Node.js**, and how to set them in the Payment Settings section of the dashboard. ## RSA Key Pair Generation RSA is a public-key cryptosystem used for encrypting and signing data. The signature mechanism uses **SHA-256** with RSA, a combination of the RSA public-key algorithm and the SHA-256 hash function. ### Algorithm Breakdown * **RSA**: A public-key cryptosystem. * **SHA-256**: A cryptographic hash function producing a 256-bit hash value. * **Signature Algorithm**: `SHA256withRSA`, which hashes the data using SHA-256 and then signs the hash with the RSA private key. ### Algorithm Parameters * **Key Size**: 2048 bits * **Exponent**: RSA usually uses a standard exponent (65537), though not explicitly mentioned. *** ## Option 1: Generating Public and Private Keys Using OpenSSL (Bash) You can generate RSA key pairs using OpenSSL with the following commands: ```bash theme={null} # Generate the private key (AES-256 encrypted) openssl genpkey -algorithm RSA -out private_key.pem -aes256 # Extract the public key from the private key openssl pkey -in private_key.pem -out public_key.pem -pubout ``` These commands will generate two files: * **private\_key.pem**: The private key (encrypted using AES-256). * **public\_key.pem**: The public key derived from the private key. *** ## Option 2: Generating Public and Private Keys in Node.js You can also generate RSA key pairs programmatically in **Node.js** using the `crypto` module. Here's how: ```javascript theme={null} const crypto = require('crypto'); // Generate RSA key pair crypto.generateKeyPair('rsa', { modulusLength: 2048, // Key size publicKeyEncoding: { type: 'pkcs1', // Key type format: 'pem' // Output format }, privateKeyEncoding: { type: 'pkcs1', // Key type format: 'pem', // Output format cipher: 'aes-256-cbc', // Optional encryption passphrase: 'your-passphrase' // Optional passphrase for private key encryption } }, (err, publicKey, privateKey) => { if (err) { console.error('Error generating keys:', err); } else { console.log('Public Key:\n', publicKey); console.log('Private Key:\n', privateKey); } }); ``` ### Key Encoding Options: * **modulusLength**: The length of the key (2048 bits). * **publicKeyEncoding** and **privateKeyEncoding**: These specify the output format and encryption details. * **PEM format**: The most common format for public/private keys, but you can also use **DER** for binary output. *** ## Step 3: Setting Keys in Payment Settings Once you've generated the keys, you need to upload the **public key** to the Payment Settings section of your dashboard. ### Test and Production Keys: * **Test Environment**: You can upload your public key via the dashboard under `Settings > Webhook Settings > webhook_pubk_test`. * **Production Environment**: For production, go to `Settings > Webhook Settings > webhook_pubk_prod`. ### Next Steps: Verifying Webhooks After setting up your keys, you'll need to implement webhook signature verification in your application. For detailed instructions on how to verify webhook signatures, please refer to our [Verifying Webhook Signatures](/webhook/verifying-webhook) guide. ### Setting up the keys in the dashboard: Dashboard Settings Example *** By following these steps, you will have successfully generated and configured your RSA keys for webhook signature verification in your payment system. \` # Handling Webhooks Source: https://docs.fenanpay.com/webhook/handling-webhook Learn how to securely process Fenan Pay webhook notifications Webhooks are a crucial component of the Fenan Pay system, allowing real-time notifications of transaction events to be sent directly to your server. This guide will walk you through the process of handling these webhook notifications securely and efficiently. Webhooks are POST requests sent from Fenan Pay to your server, containing important transaction status updates. ### Event Types Fenan Pay sends different types of webhook events based on the transaction status: #### Payment Events * `PAYMENT_SUCCESS` * `PAYMENT_FAILED` * `PAYMENT_EXPIRED` #### Withdrawal Events * `WITHDRAWAL_SUCCESS` * `WITHDRAWAL_FAILED` ## Webhook Payload Structure The webhook payload contains a transaction event object with the following key components: ```json theme={null} { "webHookEvent": "PAYMENT_SUCCESS", "signature": "...", "body": "{\"paymentIntentId\":246283,...}" // JSON string that needs to be parsed } ``` | Field | Type | Description | | -------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `webHookEvent` | string | Specifies the type of webhook notification (e.g., PAYMENT\_SUCCESS). | | `signature` | string | A cryptographic signature to verify the payload's authenticity. | | `body` | string | A JSON string containing either a [PaymentIntent](/transaction/payment-intent-object#paymentintent) or [WithdrawalIntent](/api-reference/transaction) object, depending on the event type. You need to parse this string to get the actual object. | Always verify the webhook signature to ensure the body's integrity and authenticity. Read more about [verifying webhook signatures](/webhook/verifying-webhook). ## Example Webhook Events ### Success Transaction ```json theme={null} { "webHookEvent": "PAYMENT_SUCCESS", "signature": "vDXK9SOK3WEPYvktTFODPj+bjLPPAzcSQRsYpx17+QF04aaqFrqNQQAzlwDItwERkRelH1vlQLaioZxGBDZhAgj3JN5qaTUptWBPhZTORXV8yxNnBhjKJMvKhtVlAynePyTdZDeW8xkNqzmzWZY4bxdMXCbVAzKzgRgL1fFORBH4s78sLhWGOip8SCqvLw70k2/KXs5fT2Q8tWZA+Wqek2WbWzJ4Vc0oBJbkemm69DWuSS1QYXz0Muv6bzjcaSFEQYqjmmZ4n20QfNLRLhHkn26aUCWk8i/fUYR3/zmzLMgEuX9es8YIO9hOIdF5MCZdhzJKqH6DWbJ6f2o7uVcTmQ==", "body": "{\"paymentIntentId\":246283,\"callbackUrl\":\"https://webhook.site/3fb1bdfb-6689-4a69-90a7-90cdd550c1f6\",\"returnUrl\":\"https://google.com\",\"uniqueId\":\"004-a6da72074f127195242of\",\"paymentLinkUniqueId\":null,\"uuid\":\"96aa5069-7360-49b0-8d1d-56c797252fdd\",\"test\":false,\"commissionPaidByCustomer\":false,\"creationDate\":1745918318670,\"lastUpdateDate\":1745918318670,\"expireDate\":1746004718669,\"totalAmount\":1.00,\"currency\":\"ETB\",\"checkoutBeneficiaries\":[],\"productItems\":[],\"transaction\":{\"id\":245060,\"message\":\"Process service request successfully.\",\"debitAccount\":null,\"phoneNumber\":\"251961186323\",\"trac2\":null,\"test\":false,\"referenceId\":\"96aa5069-7360-49b0-8d1d-56c797252fdd\",\"transactionStatus\":\"SUCCESS\",\"paymentType\":{\"paymentTypeId\":7,\"name\":\"Telebirr USSD\",\"description\":\"Telebirr USSD Payment\",\"type\":\"type\",\"options\":\"zf81i8SD/J901G+wILmy4rR7UnFYconop/aosio3hf1vhGf08DnNtHiPIYGeNhZObWz0Hg2WE5oWWoOrDxKFH3HiV0oiGR+TySt08xW2jCO6LtIYrBnB6mpHDKZiFBgIrB5ds4QZd9OwahO6BkYrXcBnYA2mrhOOoM7POTcrGhfoUK/aL+OhP5X4j6q0GGBT/cfD8fp4rRM89qyv6C/IOuWnfzp0cyTgxmpUhpso4N5nlKPSG3mzZYvXntgCxw0GjM+/6iIpqcLnw3g82y7HON53RBJdQEi1SvJLCGhK/KptQb6drYJ/nLyNgOxBfbq2\",\"currency\":\"ETB\",\"code\":\"TELE_BIRR_USSD\"},\"merchantNet\":0.94,\"adminNet\":0.06,\"totalAmount\":1.00,\"pspTxId\":\"CDT51S5XAD\",\"virtualAccountId\":null,\"virtualCardId\":null,\"creationDate\":1745918318674,\"lastUpdateDate\":1745918329174},\"merchantCustomer\":{\"id\":null,\"name\":null,\"email\":null,\"phone\":null},\"paymentMethodTypes\":[\"TELE_BIRR_USSD\"]}" } ``` ### Withdrawal Success Example ```json theme={null} { "webHookEvent": "WITHDRAWAL_SUCCESS", "signature": "...", "body": "{\"withdrawalIntentId\":12345,\"amount\":500.00,\"currency\":\"ETB\",...}" } ``` ## Acknowledging Webhooks To properly acknowledge receipt of a webhook, your server must respond with: 200 text/plain SUCCESS Fenan Pay will retry the webhook up to 3 times at 2-minute intervals if not properly acknowledged. ## Best Practices 1. **Verify signatures**: Always verify the webhook signature before processing the payload. 2. **Parse the body**: Remember that the `body` field is a JSON string that needs to be parsed. 3. **Process asynchronously**: Handle webhook processing in the background to respond quickly. 4. **Idempotency**: Design your webhook handler to be idempotent to safely handle potential duplicate events. 5. **Logging**: Maintain detailed logs of received webhooks for troubleshooting and auditing. ## Example Webhook Handler Here's a basic example of a webhook handler in Node.js: ```javascript theme={null} const express = require('express'); const app = express(); app.post('/webhook', express.json(), (req, res) => { const { webHookEvent, signature, body } = req.body; // Verify the signature if (verifySignature(body, signature, PUBLIC_KEY)) { // Parse the body string into a JavaScript object const payloadData = JSON.parse(body); // Process the webhook asynchronously processWebhookAsync(webHookEvent, payloadData); // Acknowledge receipt res.status(200).contentType('text/plain').send('SUCCESS'); } else { res.status(400).send('Invalid signature'); } }); async function processWebhookAsync(event, data) { // Implement your webhook processing logic here console.log('Processing webhook:', event); // Update your database, trigger notifications, etc. switch(event) { case 'PAYMENT_SUCCESS': // Handle successful payment break; case 'PAYMENT_FAILED': // Handle failed payment break; // Handle other event types } } ``` ## Webhook Log You can track how your server is handling webhooks in the Fenan Pay dashboard. This is very important for debugging and ensuring that your webhook processing is functioning correctly. Webhook Log in Dashboard By following these guidelines, you'll ensure robust and secure handling of Fenan Pay webhooks, keeping your system in sync with the latest transaction statuses. # Webhook Overview Source: https://docs.fenanpay.com/webhook/overview How to handle webhooks the right way Webhooks are a critical component of the payment process, serving as a real-time notification system for transaction outcomes. They provide immediate updates on payment statuses, allowing your application to respond promptly to successful, failed, or expired transactions. Webhooks ensure that your system stays synchronized with the payment process, enabling you to take appropriate actions based on transaction results. ## Setting Up Webhooks You have two options for configuring your webhook URL: 1. **Per-Transaction Basis**: Specify the `callback_url` parameter when creating a payment intent using either ExpressPay or Checkout. Set callback URL for ExpressPay transactions Configure callback URL for Checkout payments 2. **Global Setting**: Configure a default webhook URL in your Fenan Pay dashboard settings. Webhook Settings in Dashboard If you don't specify a `callback_url` in your payment intent request, Fenan Pay will use the URL set in your dashboard settings. Ensure this URL is always up-to-date to avoid missing critical notifications. By leveraging webhooks effectively, you can create a robust, responsive payment system that enhances the overall user experience and maintains data integrity across your application. # null Source: https://docs.fenanpay.com/webhook/verifying-webhook ## Verifying Webhook Signatures Always verify the webhook signature to ensure the payload's integrity and authenticity. Fenan Pay signs the webhook payload using a private key. To ensure that the webhook you receive is from Fenan Pay and hasn't been tampered with, verify the signature using the corresponding public key: * Test environment: `on dashboard: settings > webhook settings > webhook_pubk_test` * Production environment: `on dashboard: settings > webhook settings > webhook_pubk_prod` ### How Webhook Signatures Work Fenan Pay signs the **body** using private key speified in setting. The signature is sent in the webhook's `signature` field. You should verify the integrity of the payload by comparing the provided signature with the one generated using your webhook's public key. Make sure to verify the body **as a string** (unmodified) because any changes could invalidate the signature. The cryptographic algorithm and signing mechanism used is `SHA256withRSA` with a key length of `2048 bits`. ### Webhook Payload Structure | Field | Type | Description | | ------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `event` | string | Specifies the type of webhook notification. | | `body` | string | Contains either a [PaymentIntent](/transaction/payment-intent-object#paymentintent) or [WithdrawalIntent](/api-reference/transaction) as a JSON string, depending on the event type. | | `event` | string | Specifies the type of webhook notification. which will be found inside the body object. | ### Key Points to Remember * **Signature Field**: The `signature` field contains the cryptographic signature to verify the authenticity of the webhook body. * **body**: Ensure you verify the body **as a string**, as any modifications can lead to a failed verification. ### Example Implementations for Verifying Webhook Signatures ```javascript theme={null} const crypto = require('crypto'); function verifySignature(payload, signature, publicKey) { const verify = crypto.createVerify('SHA256'); // Convert the payload body into a string and update the verify object verify.update(payload.body); verify.end(); // Verify the signature using the provided public key return verify.verify(publicKey, signature, 'base64'); } // Example usage const payload = { signature: 'example-signature', body: { event: 'payment_intent.succeeded', ...paymentIntentObject } }; const publicKey = '-----BEGIN PUBLIC KEY-----\nyour-public-key-here\n-----END PUBLIC KEY-----'; // should be the public key from the webhook settings including the Header and Footer const isVerified = verifySignature(payload, signature, publicKey); console.log('Signature verified:', isVerified); ``` ```python theme={null} import base64 from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives.serialization import load_pem_public_key def verify_signature(payload, signature, public_key): try: # Load the public key key = load_pem_public_key(public_key.encode()) # Verify the signature key.verify( base64.b64decode(signature), payload['body'].encode(), padding.PKCS1v15(), hashes.SHA256() ) return True except: return False # Example usage payload = {'signature': 'example-signature', 'body': '{"event": "payment_intent.succeeded", ...}'} public_key = '-----BEGIN PUBLIC KEY-----\nyour-public-key-here\n-----END PUBLIC KEY-----' is_verified = verify_signature(payload, payload['signature'], public_key) print('Signature verified:', is_verified) ``` ```java theme={null} import java.security.*; import java.util.Base64; public class WebhookVerifier { public static boolean verifySignature(String payload, String signature, String publicKey) { try { Signature verifier = Signature.getInstance("SHA256withRSA"); // Load the public key byte[] publicKeyBytes = publicKey.getBytes(); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyBytes)); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey pubKey = keyFactory.generatePublic(keySpec); verifier.initVerify(pubKey); verifier.update(payload.getBytes()); return verifier.verify(Base64.getDecoder().decode(signature)); } catch (Exception e) { e.printStackTrace(); return false; } } public static void main(String[] args) { String payload = "{\"event\": \"payment_intent.succeeded\", ...}"; String signature = "example-signature"; String publicKey = "-----BEGIN PUBLIC KEY-----\nyour-public-key-here\n-----END PUBLIC KEY-----"; boolean isVerified = verifySignature(payload, signature, publicKey); System.out.println("Signature verified: " + isVerified); } } ``` ```go theme={null} package main import ( "crypto" "crypto/rsa" "crypto/sha256" "crypto/x509" "encoding/base64" "encoding/pem" "fmt" ) func verifySignature(payload, signature, publicKey string) bool { // Decode the base64 signature sig, _ := base64.StdEncoding.DecodeString(signature) // Parse the public key block, _ := pem.Decode([]byte(publicKey)) if block == nil { return false } pubKey, err := x509.ParsePKIXPublicKey(block.Bytes) if err != nil { return false } rsaPublicKey, ok := pubKey.(*rsa.PublicKey) if !ok { return false } // Create a SHA256 hash of the payload hashed := sha256.Sum256([]byte(payload)) // Verify the signature err = rsa.VerifyPKCS1v15(rsaPublicKey, crypto.SHA256, hashed[:], sig) return err == nil } func main() { payload := `{"event": "payment_intent.succeeded", ...}` signature := "example-signature" publicKey := `-----BEGIN PUBLIC KEY----- your-public-key-here -----END PUBLIC KEY-----` isVerified := verifySignature(payload, signature, publicKey) fmt.Printf("Signature verified: %v\n", isVerified) } ``` ```php theme={null} 'payment_intent.succeeded', /* ... */]); $signature = 'example-signature'; $publicKey = "-----BEGIN PUBLIC KEY-----\nyour-public-key-here\n-----END PUBLIC KEY-----"; $isVerified = verifySignature($payload, $signature, $publicKey); echo "Signature verified: " . ($isVerified ? 'true' : 'false'); ?> ```