mypos-api-gateway
v0.1.2
Published
TypeScript SDK for the myPOS API Gateway — Banking, Ecommerce, and ePOS APIs with automatic OAuth + Session token management.
Downloads
56
Maintainers
Readme
myPOS API Gateway TypeScript SDK
A TypeScript SDK for the myPOS API Gateway, designed for server-side use in Node.js applications.
It handles the dual-token authentication flow (OAuth Bearer + Session), automatic token refresh, and provides typed wrappers for all public Banking, Ecommerce, and ePOS endpoints — so you can integrate myPOS APIs without managing HTTP headers or token lifecycle manually.
Features
- Banking — list accounts, query transactions, generate account statements
- Ecommerce — payment links, payment buttons, payment requests, common reference data
- ePOS — create POS payments, manage terminals, query transactions, process refunds
- Multi-merchant support — one gateway instance serves many merchants; OAuth token is shared, sessions are per-merchant
- Automatic authentication — OAuth token (1 h) and session token (5 min) are cached and refreshed transparently
- Auto-retry on 401 — tokens are refreshed and the request is retried once
- Fully typed — comprehensive TypeScript types for every request, response, and enum
- Result-based errors — API methods return
{ success, ...data }, never throw on API errors - Dual ESM/CJS build — works with
importandrequire, ships full.d.tstypes - Zero dependencies — uses native Node.js
fetch(Node 18+)
Requirements
- Node.js >= 18
- A myPOS Partner Portal account with API Gateway access
- Integration credentials (
client_id/client_secret) for OAuth - Merchant credentials (
client_id/client_secret) for session creation - Partner ID and Application ID from the Partner Portal
Server-only. All methods use your credentials and must only run in server-side code. Never expose credentials to the browser.
Installation
npm install mypos-api-gatewaySetup
1. Get your credentials
From the myPOS Partner Portal (or the Demo Partner Portal for testing), obtain:
- Integration credentials —
client_id(prefixedclient_) andclient_secret(prefixedsecret_) - Merchant credentials —
client_id(prefixedcli_) andclient_secret(prefixedsec_) - Partner ID — format:
mps-p-XXXXXXXX - Application ID — format:
mps-app-XXXXXXXX
Store the partner-level credentials as environment variables. Merchant credentials typically come from your database at runtime (one set per merchant).
MYPOS_GATEWAY_URL=https://demo-api-gateway.mypos.com
MYPOS_INTEGRATION_CLIENT_ID=client_5c8bfaa75f87482caa475669491af1d4
MYPOS_INTEGRATION_CLIENT_SECRET=secret_0a5c3bbfe050...
MYPOS_PARTNER_ID=mps-p-10000214
MYPOS_APPLICATION_ID=mps-app-300012022. Create the gateway (once, at startup)
import { MyPOSGateway, DEMO_GATEWAY_URL } from 'mypos-api-gateway';
const gateway = new MyPOSGateway({
gatewayUrl: DEMO_GATEWAY_URL,
integration: {
clientId: process.env.MYPOS_INTEGRATION_CLIENT_ID!,
clientSecret: process.env.MYPOS_INTEGRATION_CLIENT_SECRET!,
},
partnerId: process.env.MYPOS_PARTNER_ID!,
applicationId: process.env.MYPOS_APPLICATION_ID!,
});The gateway holds your partner credentials and manages the shared OAuth token (1 h TTL). Create it once and reuse it across your application.
For production, use PRODUCTION_GATEWAY_URL instead of DEMO_GATEWAY_URL.
3. Create merchant-scoped clients (on demand)
// Merchant credentials typically come from your database
const client = gateway.createClient({
clientId: merchantRow.myposClientId,
clientSecret: merchantRow.myposClientSecret,
});
// Each client manages its own session (5 min TTL) and calls the API
// on behalf of that specific merchant
const accounts = await client.banking.getAccounts();You can create as many merchant clients as you need — they all share the same OAuth token. This supports multi-tenant scenarios where one partner application serves many merchants (e.g. a cloud POS system, an invoicing SaaS, etc.).
Authentication Flow
The SDK manages this automatically, but here's what happens under the hood:
- OAuth Token (partner-level, shared) —
POST /api/v1/oauth/tokenwith integration credentials. Returns a Bearer token valid for 1 hour. Shared across all merchant clients. - Session Token (per-merchant) —
POST /api/v1/auth/sessionwith merchant credentials + Bearer token. Returns a session token valid for 5 minutes. Each merchant client has its own. - API Calls — Every request includes four headers:
Authorization: Bearer <oauth_token>(shared)X-Session: <session_token>(per-merchant)X-Partner-Id: <partner_id>X-Application-Id: <application_id>
- Auto-refresh — Tokens are refreshed 60s (OAuth) / 30s (session) before expiry.
- 401 Retry — If an API call returns 401, both tokens are force-refreshed and the request is retried once.
Methods
Banking
Accounts
// List merchant accounts
const accounts = await client.banking.getAccounts({ page: 1, size: 20 });
if (accounts.success) {
for (const acct of accounts.items) {
console.log(acct.iban, acct.currency, acct.name);
}
}
// Generate account statement
const statement = await client.banking.generateStatement({
accountNumber: '40012345678',
documentType: 'MT940MultiCash',
date: '2025-03-15',
});Transactions
// List transactions with filters
const txns = await client.banking.getTransactions({
fromDate: '2025-01-01',
toDate: '2025-03-31',
sign: 'Credit',
order: 'Descending',
page: 1,
size: 50,
});
// Get single transaction details
const detail = await client.banking.getTransaction('REF123456');
// Get multiple transactions at once
const multi = await client.banking.getMultipleTransactions([
'REF123', 'REF456', 'REF789',
]);Ecommerce
Payment Links
// Create a payment link
const link = await client.ecommerce.paymentLinks.create({
itemName: 'Invoice #1234',
itemPrice: 29.99,
quantity: 1,
currency: 'EUR',
hideQuantity: false,
askForCustomerName: true,
askForShippingAddress: false,
askForCustomerEmail: true,
askForCustomerPhoneNumber: false,
askForCustomerId: false,
sendSms: false,
sendEmail: true,
});
if (link.success) {
console.log('Payment link URL:', link.url);
}
// List payment links
const links = await client.ecommerce.paymentLinks.list({ page: 1, size: 20 });
// Auto-page through all payment links
for await (const item of client.ecommerce.paymentLinks.listAll()) {
console.log(item.code, item.amount);
}
// Get link details
const detail = await client.ecommerce.paymentLinks.get('LINK_CODE');
// Update a link
await client.ecommerce.paymentLinks.update('LINK_CODE', { enable: false });
// Delete a link
await client.ecommerce.paymentLinks.delete('LINK_CODE');
// Get link transactions
const txns = await client.ecommerce.paymentLinks.getTransactions({
page: 1, size: 20,
dateFrom: '2025-01-01',
dateTo: '2025-03-31',
});Payment Buttons
// Create a payment button
const button = await client.ecommerce.paymentButtons.create({
buttonSize: 'Big',
itemName: 'Premium Plan',
itemPrice: 49.99,
quantity: 1,
currency: 'EUR',
returnUrl: 'https://example.com/success',
cancelUrl: 'https://example.com/cancel',
askForCustomerName: true,
askForShippingAddress: false,
askForCustomerEmail: true,
askForCustomerPhoneNumber: false,
askForCustomerId: false,
sendSms: false,
sendEmail: true,
});
// List, get, update, delete — same pattern as payment links
const buttons = await client.ecommerce.paymentButtons.list({ page: 1, size: 20 });Payment Requests
// Create a payment request
const pr = await client.ecommerce.paymentRequests.create({
amount: 150.00,
currency: 'EUR',
clientName: 'John Doe',
reason: 'Consulting fee',
bookingText: 'INV-2025-001',
qrGenerated: true,
});
if (pr.success) {
console.log('Payment request URL:', pr.paymentRequestUrl);
}
// List payment requests
const prs = await client.ecommerce.paymentRequests.list({
page: 1, size: 20,
status: 'Pending',
});
// Get details
const prDetail = await client.ecommerce.paymentRequests.get('PR_CODE');
// Send reminder
await client.ecommerce.paymentRequests.sendReminder('PR_CODE');Common Data
// List supported languages
const langs = await client.ecommerce.getLanguages({ page: 1, size: 50 });
// Get settlement data
const settlement = await client.ecommerce.getSettlementData({ page: 1, size: 50 });ePOS
Payments
// Create a POS payment
const payment = await client.epos.payments.create({
referenceNumber: 'ORD-2025-001',
amount: { value: 2500, currencyCode: 'EUR', tip: 0 },
description: 'Order #001',
terminalId: 'T001234',
appName: 'MyShopPOS',
appVersion: '1.0.0',
operatorCode: 'OP01',
});
if (payment.success) {
console.log('Payment ID:', payment.paymentId, 'Status:', payment.status);
}
// Get payment details
const detail = await client.epos.payments.get('pay_abc123');
// List terminal payments
const payments = await client.epos.payments.list({
terminalId: 'T001234',
page: 1,
size: 20,
});
// Cancel a pending payment
await client.epos.payments.cancel('pay_abc123');
// Reverse (void) a completed payment
await client.epos.payments.reverse('pay_abc123', {
description: 'Customer returned goods',
terminalId: 'T001234',
appName: 'MyShopPOS',
appVersion: '1.0.0',
});
// Process a refund
await client.epos.payments.refund({
amount: { value: 1000, currencyCode: 'EUR', tip: 0 },
description: 'Partial refund',
terminalId: 'T001234',
appName: 'MyShopPOS',
appVersion: '1.0.0',
});Terminals
// List terminals
const terminals = await client.epos.terminals.list({ page: 1, size: 20 });
// Get terminal details
const terminal = await client.epos.terminals.get('T001234');
// Get all terminal transactions
const txns = await client.epos.terminals.getTransactions({
fromDate: '2025-01-01',
toDate: '2025-03-31',
});
// Get transactions for a specific terminal
const tTxns = await client.epos.terminals.getTerminalTransactions('T001234', {
fromDate: '2025-03-01',
toDate: '2025-03-31',
});
// Get terminal models
const models = await client.epos.terminals.getModels();
// Get outlets
const outlets = await client.epos.terminals.getOutlets();
// Activate a terminal
const activation = await client.epos.terminals.activate();
// Deactivate a terminal
await client.epos.terminals.deactivate({ code: 'ACT123456' });
// Get receipt
const receipt = await client.epos.terminals.getReceipt('REF123456');
// Process terminal refund
await client.epos.terminals.refund('T001234', {
referenceNumber: 'ORD-2025-001',
amount: 1500,
});Configuration Reference
- [ ]
GatewayConfig(passed tonew MyPOSGateway(...))
| Field | Type | Required | Description |
| ---------------------------- | ---------- | -------- | ----------------------------------------------------------------- |
| gatewayUrl | string | Yes | Base URL. Use DEMO_GATEWAY_URL or PRODUCTION_GATEWAY_URL. |
| integration.clientId | string | Yes | Integration client ID (prefixed client_). |
| integration.clientSecret | string | Yes | Integration client secret (prefixed secret_). |
| partnerId | string | Yes | Partner ID (format:mps-p-*). |
| applicationId | string | Yes | Application ID (format:mps-app-*). |
| timeout | number | No | Request timeout in ms. Default:30000. |
MerchantCredentials (passed to gateway.createClient(...))
| Field | Type | Required | Description |
| ---------------- | ---------- | -------- | ------------------------------------------- |
| clientId | string | Yes | Merchant client ID (prefixed cli_). |
| clientSecret | string | Yes | Merchant client secret (prefixed sec_). |
Error Handling
Construction errors (thrown)
import { MyPOSGateway, GatewayConfigError } from 'mypos-api-gateway';
try {
const gateway = new MyPOSGateway({ /* ... */ });
const client = gateway.createClient({ /* ... */ });
} catch (e) {
if (e instanceof GatewayConfigError) {
console.error('Invalid configuration:', e.message);
}
}Authentication errors (thrown)
import { GatewayAuthError } from 'mypos-api-gateway';
try {
const accounts = await client.banking.getAccounts();
} catch (e) {
if (e instanceof GatewayAuthError) {
console.error('Authentication failed:', e.message);
}
}API errors (returned, never thrown)
const result = await client.banking.getAccounts();
if (result.success) {
// Access data fields
console.log(result.items);
} else {
// Handle error
console.error(`Error ${result.status}: ${result.statusMessage}`);
if (result.errorDetails?.errors) {
// Validation errors
for (const [field, messages] of Object.entries(result.errorDetails.errors)) {
console.error(` ${field}: ${messages.join(', ')}`);
}
}
}Auto-pagination
All list endpoints that return paginated results support manual pagination via the page and size parameters. Additionally, paymentLinks, paymentButtons, and paymentRequests provide a listAll() method that returns an async generator for automatic pagination:
for await (const link of client.ecommerce.paymentLinks.listAll({ size: 50 })) {
console.log(link.code, link.amount);
}Demo Environment & SSL
The demo API Gateway (https://demo-api-gateway.mypos.com) may require disabling SSL verification. If you encounter certificate errors, set:
NODE_TLS_REJECT_UNAUTHORIZED=0 node your-app.jsThis should only be used in development, never in production.
API Reference
- myPOS API Gateway — Identity
- myPOS API Gateway — Banking
- myPOS API Gateway — Ecommerce
- myPOS API Gateway — ePOS
License
MIT
