{"id":20607552,"url":"https://github.com/monei/monei-node-sdk","last_synced_at":"2025-04-15T03:55:53.972Z","repository":{"id":57127893,"uuid":"297638764","full_name":"MONEI/monei-node-sdk","owner":"MONEI","description":"MONEI Node.js SDK","archived":false,"fork":false,"pushed_at":"2025-03-25T18:27:21.000Z","size":2798,"stargazers_count":7,"open_issues_count":0,"forks_count":2,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-15T03:55:47.598Z","etag":null,"topics":["monei-api","monei-node-sdk","monei-payments","payment-gateway","payments","sdk"],"latest_commit_sha":null,"homepage":"https://docs.monei.com","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/MONEI.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-09-22T12:17:05.000Z","updated_at":"2025-03-25T18:27:24.000Z","dependencies_parsed_at":"2023-11-09T16:24:31.527Z","dependency_job_id":"375fea22-7b82-456a-8425-175e926b3bce","html_url":"https://github.com/MONEI/monei-node-sdk","commit_stats":{"total_commits":64,"total_committers":1,"mean_commits":64.0,"dds":0.0,"last_synced_commit":"d0dd31b19358bcd73d5ce5bb24d8fe77e84cfe7b"},"previous_names":[],"tags_count":39,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MONEI%2Fmonei-node-sdk","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MONEI%2Fmonei-node-sdk/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MONEI%2Fmonei-node-sdk/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MONEI%2Fmonei-node-sdk/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MONEI","download_url":"https://codeload.github.com/MONEI/monei-node-sdk/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249003951,"owners_count":21196794,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["monei-api","monei-node-sdk","monei-payments","payment-gateway","payments","sdk"],"created_at":"2024-11-16T10:07:49.981Z","updated_at":"2025-04-15T03:55:53.962Z","avatar_url":"https://github.com/MONEI.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# MONEI Node.js SDK\n\nThe MONEI Node.js SDK provides convenient access to the [MONEI](https://monei.com/) API from applications written in server-side JavaScript.\n\nFor collecting customer and payment information in the browser, use [monei.js](https://docs.monei.com/docs/monei-js-overview)\n\n[![npm version](https://img.shields.io/npm/v/@monei-js/node-sdk.svg)](https://www.npmjs.com/package/@monei-js/node-sdk)\n[![License](https://img.shields.io/npm/l/@monei-js/node-sdk.svg)](https://github.com/MONEI/monei-node-sdk/blob/master/LICENSE)\n[![Downloads](https://img.shields.io/npm/dm/@monei-js/node-sdk.svg)](https://www.npmjs.com/package/@monei-js/node-sdk)\n[![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)\n[![GitHub stars](https://img.shields.io/github/stars/MONEI/monei-node-sdk.svg?style=social\u0026label=Star)](https://github.com/MONEI/monei-node-sdk)\n\n## Table of Contents\n\n- [MONEI Node.js SDK](#monei-nodejs-sdk)\n  - [Table of Contents](#table-of-contents)\n  - [Requirements](#requirements)\n  - [Installation](#installation)\n  - [Basic Usage](#basic-usage)\n    - [API Keys](#api-keys)\n      - [Types of API Keys](#types-of-api-keys)\n      - [API Key Security](#api-key-security)\n    - [Test Mode](#test-mode)\n    - [Basic Client Usage](#basic-client-usage)\n  - [Payment Operations](#payment-operations)\n    - [Creating a Payment](#creating-a-payment)\n    - [Retrieving a Payment](#retrieving-a-payment)\n    - [Refunding a Payment](#refunding-a-payment)\n  - [Integration Methods](#integration-methods)\n    - [Using the Prebuilt Payment Page](#using-the-prebuilt-payment-page)\n      - [Features](#features)\n      - [Integration Flow](#integration-flow)\n  - [Webhooks](#webhooks)\n    - [Signature Verification](#signature-verification)\n    - [Handling Payment Callbacks](#handling-payment-callbacks)\n      - [Important Notes About Webhooks](#important-notes-about-webhooks)\n  - [MONEI Connect for Partners](#monei-connect-for-partners)\n    - [Account ID](#account-id)\n      - [Setting Account ID in the constructor](#setting-account-id-in-the-constructor)\n      - [Setting Account ID after initialization](#setting-account-id-after-initialization)\n    - [Custom User-Agent](#custom-user-agent)\n      - [Examples with Proper User-Agent Format](#examples-with-proper-user-agent-format)\n    - [Managing Multiple Merchant Accounts](#managing-multiple-merchant-accounts)\n  - [Documentation](#documentation)\n\n## Requirements\n\n- Node.js 12 or later\n\n## Installation\n\nInstall the package using npm or yarn:\n\n```bash\n# Using npm\nnpm install @monei-js/node-sdk --save\n\n# Using yarn\nyarn add @monei-js/node-sdk\n```\n\n## Basic Usage\n\n### API Keys\n\nThe MONEI API uses API keys for authentication. You can obtain and manage your API keys in the [MONEI Dashboard](https://dashboard.monei.com/settings/api).\n\n#### Types of API Keys\n\nMONEI provides two types of API keys:\n\n- **Test API Keys**: Use these for development and testing. Transactions made with test API keys are not processed by real payment providers.\n- **Live API Keys**: Use these in production environments. Transactions made with live API keys are processed by real payment providers and will move actual money.\n\nEach API key has a distinct prefix that indicates its environment:\n\n- Test API keys start with `pk_test_` (e.g., `pk_test_12345abcdef`)\n- Live API keys start with `pk_live_` (e.g., `pk_live_12345abcdef`)\n\nBy checking the prefix of an API key, you can quickly determine which environment you're working in. This is especially useful when you're managing multiple projects or environments.\n\n#### API Key Security\n\nYour API keys carry significant privileges, so be sure to keep them secure:\n\n- Keep your API keys confidential and never share them in publicly accessible areas such as GitHub, client-side code, or in your frontend application.\n- Use environment variables or a secure vault to store your API keys.\n- Restrict API key access to only the IP addresses that need them.\n- Regularly rotate your API keys, especially if you suspect they may have been compromised.\n\n```js\n// Example of loading API key from environment variable (recommended)\nconst apiKey = process.env.MONEI_API_KEY;\nconst monei = new Monei(apiKey);\n```\n\n### Test Mode\n\nTo test your integration with MONEI, you need to switch to **test mode** using the toggle in the header of your MONEI Dashboard. When in test mode:\n\n1. Generate your test API key in [MONEI Dashboard → Settings → API Access](https://dashboard.monei.com/settings/api)\n2. Configure your payment methods in [MONEI Dashboard → Settings → Payment Methods](https://dashboard.monei.com/settings/payment-methods)\n\n**Important:** Account ID and API key generated in test mode are different from those in live (production) mode and can only be used for testing purposes.\n\nWhen using test mode, you can simulate various payment scenarios using test card numbers, Bizum phone numbers, and PayPal accounts provided in the [MONEI Testing documentation](https://docs.monei.com/docs/testing/).\n\n### Basic Client Usage\n\n```js\nimport {Monei} from '@monei-js/node-sdk';\n\n// Instantiate the client using the API key\nconst monei = new Monei('YOUR_API_KEY');\n\ntry {\n  // Create a simple payment\n  monei.payments.create({\n    amount: 1250, // 12.50€\n    orderId: '100100000001',\n    currency: 'EUR',\n    description: 'Items description',\n    customer: {\n      email: 'john.doe@monei.com',\n      name: 'John Doe'\n    }\n  })\n  .then(result =\u003e {\n    console.log(result);\n  });\n} catch (error) {\n  console.error('Error while creating payment:', error.message);\n}\n```\n\n## Payment Operations\n\n### Creating a Payment\n\nCreate a payment with customer information:\n\n```js\nimport {Monei} from '@monei-js/node-sdk';\n\nconst monei = new Monei('YOUR_API_KEY');\n\nmonei.payments\n  .create({\n    orderId: '12345',\n    amount: 1999, // Amount in cents (19.99)\n    currency: 'EUR',\n    description: 'Order #12345',\n    customer: {\n      email: 'customer@example.com',\n      name: 'John Doe',\n      phone: '+34600000000'\n    },\n    billingDetails: {\n      address: {\n        line1: '123 Main St',\n        city: 'Barcelona',\n        country: 'ES',\n        postalCode: '08001'\n      }\n    },\n    completeUrl: 'https://example.com/success',\n    cancelUrl: 'https://example.com/failure',\n    callbackUrl: 'https://example.com/webhook'\n  })\n  .then((result) =\u003e {\n    console.log(result);\n  })\n  .catch((error) =\u003e {\n    console.error('Error while creating payment:', error.message);\n  });\n```\n\n### Retrieving a Payment\n\nRetrieve an existing payment by ID:\n\n```js\nimport {Monei} from '@monei-js/node-sdk';\n\nconst monei = new Monei('YOUR_API_KEY');\n\nmonei.payments.get('pay_123456789')\n  .then((payment) =\u003e {\n    console.log('Payment status:', payment.status);\n  })\n  .catch((error) =\u003e {\n    console.error('Error retrieving payment:', error.message);\n  });\n```\n\n### Refunding a Payment\n\nProcess a full or partial refund:\n\n```js\nimport {Monei} from '@monei-js/node-sdk';\n\nconst monei = new Monei('YOUR_API_KEY');\n\nmonei.refunds\n  .create({\n    paymentId: 'pay_123456789',\n    amount: 500, // Partial refund of 5.00\n    reason: 'customer_request'\n  })\n  .then((refund) =\u003e {\n    console.log('Refund created with ID:', refund.id);\n  })\n  .catch((error) =\u003e {\n    console.error('Error refunding payment:', error.message);\n  });\n```\n\n## Integration Methods\n\n### Using the Prebuilt Payment Page\n\nMONEI Hosted Payment Page is the simplest way to securely collect payments from your customers without building your own payment form.\n\n#### Features\n\n- **Designed to remove friction** — Real-time card validation with built-in error messaging\n- **Mobile-ready** — Fully responsive design\n- **International** — Supports 13 languages\n- **Multiple payment methods** — Supports multiple payment methods including Cards, PayPal, Bizum, GooglePay, Apple Pay \u0026 Click to Pay\n- **Customization and branding** — Customizable logo, buttons and background color\n- **3D Secure** — Supports 3D Secure - SCA verification process\n- **Fraud and compliance** — Simplified PCI compliance and SCA-ready\n\nYou can customize the appearance in your MONEI Dashboard → Settings → Branding.\n\n#### Integration Flow\n\n1. **Create a payment on your server**\n\n```js\nimport {Monei} from '@monei-js/node-sdk';\n\nconst monei = new Monei('YOUR_API_KEY');\n\nmonei.payments.create({\n  amount: 110, // Amount in cents (1.10)\n  currency: 'EUR',\n  orderId: '14379133960355',\n  description: 'Test Shop - #14379133960355',\n  customer: {\n    email: 'customer@example.com'\n  },\n  callbackUrl: 'https://example.com/checkout/callback', // For asynchronous notifications\n  completeUrl: 'https://example.com/checkout/complete', // Redirect after payment\n  cancelUrl: 'https://example.com/checkout/cancel' // Redirect if customer cancels\n})\n.then(payment =\u003e {\n  // Redirect the customer to the payment page\n  if (payment.nextAction \u0026\u0026 payment.nextAction.redirectUrl) {\n    // In a browser environment:\n    // window.location.href = payment.nextAction.redirectUrl;\n    console.log('Redirect URL:', payment.nextAction.redirectUrl);\n  }\n})\n.catch(error =\u003e {\n  console.error('Error while creating payment:', error.message);\n});\n```\n\n2. **Redirect the customer to the payment page**\n\nAfter creating a payment, you'll receive a response with a `nextAction.redirectUrl`. Redirect your customer to this URL to show them the MONEI Hosted payment page.\n\n3. **Customer completes the payment**\n\nThe customer enters their payment information and completes any required verification steps (like 3D Secure).\n\n4. **Customer is redirected back to your website**\n\n- If the customer completes the payment, they are redirected to the `completeUrl` with a `payment_id` query parameter\n- If the customer cancels, they are redirected to the `cancelUrl`\n\n5. **Receive asynchronous notification**\n\nMONEI sends an HTTP POST request to your `callbackUrl` with the payment result. This ensures you receive the payment status even if the customer closes their browser during the redirect.\n\nFor more information about the hosted payment page, visit the [MONEI Hosted Payment Page documentation](https://docs.monei.com/docs/integrations/use-prebuilt-payment-page).\n\n## Webhooks\n\nWebhooks can be configured in the [MONEI Dashboard → Settings → Webhooks](https://dashboard.monei.com/settings/webhooks).\n\n### Signature Verification\n\nWhen receiving webhooks from MONEI, you should verify the signature to ensure the request is authentic:\n\n```js\nimport {Monei, PaymentStatus} from '@monei-js/node-sdk';\nimport express from 'express';\n\nconst app = express();\nconst monei = new Monei('YOUR_API_KEY');\n\n// Parse raw body for signature verification\napp.use('/webhook', express.raw({type: 'application/json'}));\n\napp.post('/webhook', (req, res) =\u003e {\n  try {\n    // Get the signature from the headers\n    const signature = req.headers['monei-signature'];\n    \n    // Verify the signature and get the decoded payload\n    const payload = monei.verifySignature(req.body.toString(), signature);\n    \n    // Process the webhook\n    const eventType = payload.type;\n    \n    // The data field contains the Payment object\n    const payment = payload.object;\n    \n    // Access Payment object properties directly\n    const paymentId = payment.id;\n    const amount = payment.amount;\n    const currency = payment.currency;\n    const status = payment.status;\n    \n    // Handle the event based on its type\n    switch (eventType) {\n      case 'payment.succeeded':\n        // Handle successful payment\n        console.log(`Payment ${paymentId} succeeded: ${amount/100} ${currency}`);\n        break;\n      case 'payment.failed':\n        // Handle failed payment\n        console.log(`Payment ${paymentId} failed with status: ${status}`);\n        break;\n      // Handle other event types\n    }\n    \n    res.status(200).json({received: true});\n  } catch (error) {\n    console.error('Webhook signature verification failed:', error.message);\n    res.status(401).json({error: 'Invalid signature'});\n  }\n});\n\napp.listen(3000, () =\u003e {\n  console.log('Server listening on port 3000');\n});\n```\n\n### Handling Payment Callbacks\n\nMONEI sends an HTTP POST request to your `callbackUrl` with the payment result. This ensures you receive the payment status even if the customer closes their browser during the redirect.\n\nExample of handling the callback in an Express.js server:\n\n```js\napp.post('/checkout/callback', express.raw({type: 'application/json'}), (req, res) =\u003e {\n  const signature = req.headers['monei-signature'];\n  \n  try {\n    // Verify the signature\n    const payment = monei.verifySignature(req.body.toString(), signature);\n    \n    // Update your order status based on the payment status\n    if (payment.status === PaymentStatus.SUCCEEDED) {\n      // Payment successful - fulfill the order\n      // Update your database, send confirmation email, etc.\n    } else if (payment.status === PaymentStatus.FAILED) {\n      // Payment failed - notify the customer\n      // Log the failure, update your database, etc.\n    } else if (payment.status === PaymentStatus.AUTHORIZED) {\n      // Payment is authorized but not yet captured\n      // You can capture it later\n    } else if (payment.status === PaymentStatus.CANCELED) {\n      // Payment was canceled\n    }\n    \n    // Acknowledge receipt of the webhook\n    res.status(200).json({received: true});\n  } catch (error) {\n    console.error('Invalid webhook signature:', error);\n    res.status(401).json({error: 'Invalid signature'});\n  }\n});\n```\n\n#### Important Notes About Webhooks\n\n1. Always verify the signature to ensure the webhook is coming from MONEI\n2. Use the raw request body for signature verification\n3. Return a 2xx status code to acknowledge receipt of the webhook\n4. Process webhooks asynchronously for time-consuming operations\n5. Implement idempotency to handle duplicate webhook events\n\n## MONEI Connect for Partners\n\nIf you're a partner or platform integrating with MONEI, you can act on behalf of your merchants by providing their Account ID. This is part of [MONEI Connect](https://docs.monei.com/docs/monei-connect/), which allows platforms to manage multiple merchant accounts.\n\n**Important:** When using Account ID functionality, you must:\n\n1. Use a partner API key (not a regular merchant API key)\n2. Provide a custom User-Agent to identify your platform\n\nFor more information about MONEI Connect and becoming a partner, visit the [MONEI Connect documentation](https://docs.monei.com/docs/monei-connect/).\n\n### Account ID\n\n#### Setting Account ID in the constructor\n\n```js\nimport {Monei} from '@monei-js/node-sdk';\n\n// Initialize with Account ID and User-Agent using a partner API key\nconst monei = new Monei('pk_partner_test_...', {\n  accountId: 'merchant_account_id',\n  userAgent: 'MONEI/YourPlatform/1.0.0'\n});\n\n// Make API calls on behalf of the merchant\nmonei.payments.create({orderId: '12345', amount: 110})\n  .then((result) =\u003e {\n    console.log(result);\n  })\n  .catch((error) =\u003e {\n    console.error('Error while creating payment:', error.message);\n  });\n```\n\n#### Setting Account ID after initialization\n\n```js\nimport {Monei} from '@monei-js/node-sdk';\n\n// Initialize with a partner API key\nconst monei = new Monei('pk_partner_test_...');\n\n// Set User-Agent for your platform (required before setting Account ID)\nmonei.setUserAgent('MONEI/YourPlatform/1.0.0');\n\n// Set Account ID to act on behalf of a merchant\nmonei.setAccountId('merchant_account_id');\n\n// Make API calls on behalf of the merchant\nmonei.payments.create({orderId: '12345', amount: 110})\n  .then((result) =\u003e {\n    console.log(result);\n  })\n  .catch((error) =\u003e {\n    console.error('Error while creating payment:', error.message);\n  });\n\n// Remove Account ID to stop acting on behalf of the merchant\nmonei.setAccountId(undefined);\n```\n\n### Custom User-Agent\n\nYou can set a custom User-Agent to identify your application or platform. This is required when using Account ID.\n\nWhen integrating as a MONEI Connect partner, your User-Agent should follow this format:\n\n```\nMONEI/\u003cPARTNER_NAME\u003e/\u003cVERSION\u003e\n```\n\nFor example: `MONEI/YourPlatform/1.0.0`\n\nThis format helps MONEI identify your platform in API requests and is required when using the Partner API Key.\n\n```js\nimport {Monei} from '@monei-js/node-sdk';\n\n// Set User-Agent in constructor with proper format\nconst monei = new Monei('pk_partner_test_...', {\n  userAgent: 'MONEI/YourPlatform/1.0.0'\n});\n\n// Or set it after initialization\nmonei.setUserAgent('MONEI/YourPlatform/1.0.0');\n```\n\n#### Examples with Proper User-Agent Format\n\n```js\nimport {Monei} from '@monei-js/node-sdk';\n\n// For a platform named \"ShopManager\" with version 2.1.0\nconst monei = new Monei('pk_partner_test_...', {\n  accountId: 'merchant_account_id',\n  userAgent: 'MONEI/ShopManager/2.1.0'\n});\n\n// For a platform named \"PaymentHub\" with version 3.0.1\nmonei.setUserAgent('MONEI/PaymentHub/3.0.1');\n```\n\n\u003e **Note:** When using Account ID, you must set a custom User-Agent before making any API calls. The User-Agent is validated when making API requests.\n\u003e\n\u003e **Important:** To use this feature, you need to be registered as a MONEI partner and use your partner API key. Please contact connect@monei.com to register as a partner.\n\n### Managing Multiple Merchant Accounts\n\n```js\nimport {Monei} from '@monei-js/node-sdk';\n\n// Initialize with a partner API key\nconst monei = new Monei('pk_partner_test_...', {\n  userAgent: 'MONEI/YourPlatform/1.0.0'\n});\n\n// Function to process payments for multiple merchants\nasync function processPaymentsForMerchants(merchantAccounts) {\n  const results = {};\n\n  for (const merchantId of merchantAccounts) {\n    // Set the current merchant account\n    monei.setAccountId(merchantId);\n\n    // Process payment for this merchant\n    try {\n      const payment = await monei.payments.create({\n        orderId: `order-${merchantId}-${Date.now()}`,\n        amount: 1000,\n        currency: 'EUR'\n      });\n\n      results[merchantId] = {success: true, payment};\n    } catch (error) {\n      results[merchantId] = {success: false, error: error.message};\n    }\n  }\n\n  return results;\n}\n\n// Example usage\nconst merchantAccounts = ['merchant_1', 'merchant_2', 'merchant_3'];\nprocessPaymentsForMerchants(merchantAccounts)\n  .then(results =\u003e console.log(results))\n  .catch(error =\u003e console.error('Error processing merchant payments:', error.message));\n```\n\n## Documentation\n\nFor the full documentation, check our [Documentation portal](https://docs.monei.com/).\n\nFor a comprehensive overview of all MONEI features and integration options, visit our [main documentation portal](https://docs.monei.com/). There you can explore guides for:\n\n- Using a prebuilt payment page with MONEI Hosted payment page\n- Building a custom checkout with MONEI UI components\n- Integrating with multiple e-commerce platforms\n- Connecting with business platforms and marketplaces","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmonei%2Fmonei-node-sdk","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmonei%2Fmonei-node-sdk","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmonei%2Fmonei-node-sdk/lists"}