{"_id":"@altev/pg-sdk","name":"@altev/pg-sdk","dist-tags":{"latest":"0.1.0"},"versions":{"0.1.0":{"name":"@altev/pg-sdk","version":"0.1.0","type":"module","description":"TypeScript SDK for the Altev Payment Gateway","license":"SEE LICENSE IN LICENSE","author":{"name":"Altev Tech"},"keywords":["payment","gateway","paymongo","sdk","nestjs","altev"],"publishConfig":{"access":"public"},"engines":{"node":">=18"},"exports":{".":{"import":{"types":"./dist/index.d.ts","default":"./dist/index.js"},"require":{"types":"./dist/index.d.cts","default":"./dist/index.cjs"}},"./nestjs":{"import":{"types":"./dist/nestjs/index.d.ts","default":"./dist/nestjs/index.js"},"require":{"types":"./dist/nestjs/index.d.cts","default":"./dist/nestjs/index.cjs"}},"./testing":{"import":{"types":"./dist/testing/index.d.ts","default":"./dist/testing/index.js"},"require":{"types":"./dist/testing/index.d.cts","default":"./dist/testing/index.cjs"}},"./mcp":{"import":{"types":"./dist/mcp/index.d.ts","default":"./dist/mcp/index.js"},"require":{"types":"./dist/mcp/index.d.cts","default":"./dist/mcp/index.cjs"}}},"bin":{"pg-sdk":"dist/mcp/index.js"},"scripts":{"build":"tsup","typecheck":"tsc --noEmit","test":"vitest run","test:watch":"vitest","prepublishOnly":"npm run build && npm run test"},"peerDependencies":{"@nestjs/common":">=10","@nestjs/core":">=10"},"peerDependenciesMeta":{"@nestjs/common":{"optional":true},"@nestjs/core":{"optional":true}},"dependencies":{"@modelcontextprotocol/sdk":"^1.0.0"},"devDependencies":{"@nestjs/common":"^11.1.15","@nestjs/core":"^11.1.15","@types/node":"^20.0.0","reflect-metadata":"^0.2.2","rxjs":"^7.8.2","tsup":"^8.0.0","typescript":"^5.5.0","vitest":"^2.0.0"},"_id":"@altev/pg-sdk@0.1.0","_nodeVersion":"25.6.1","_npmVersion":"11.9.0","dist":{"integrity":"sha512-ul9AFH0Qbe3j8Mb4y0cknFzsxIq9EuXQ37WzExNw6CSbfzEFGsNzu/5h5FJb/jsqfD9wYntq45JewdqlkjZ7VA==","shasum":"606c442d8dfb1f530c5c635f2a5f6b2ed44206d3","tarball":"https://registry.npmjs.org/@altev/pg-sdk/-/pg-sdk-0.1.0.tgz","fileCount":21,"unpackedSize":1258533,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIE0eHYIhDUQNQoAPOvOtd1oLj84dCm6QEuXwtqSEXX01AiEAo17xI6BoCWZ9HGcyS0CE+NKaP4s3YZUXhkGj6dCmtO8="}]},"_npmUser":{"name":"rhyumiranda","email":"hello.rhyumiranda@gmail.com"},"directories":{},"maintainers":[{"name":"rhyumiranda","email":"hello.rhyumiranda@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/pg-sdk_0.1.0_1772564248848_0.5701514517812183"},"_hasShrinkwrap":false}},"time":{"created":"2026-03-03T18:57:28.763Z","0.1.0":"2026-03-03T18:57:29.072Z","modified":"2026-03-03T18:57:29.303Z"},"maintainers":[{"name":"rhyumiranda","email":"hello.rhyumiranda@gmail.com"}],"description":"TypeScript SDK for the Altev Payment Gateway","keywords":["payment","gateway","paymongo","sdk","nestjs","altev"],"author":{"name":"Altev Tech"},"license":"SEE LICENSE IN LICENSE","readme":"# @altev/pg-sdk\n\nTypeScript SDK for the Altev Payment Gateway. Handles checkout payments, payment intents, refunds, webhook verification, and status checks.\n\n## Install & Init\n\n```bash\nnpm install @altev/pg-sdk\n```\n\n```ts\nimport { PaymentGateway } from '@altev/pg-sdk'\n\nconst pg = new PaymentGateway('sk_test_xxx')\n// or: new PaymentGateway('sk_live_xxx', { baseUrl, timeout, maxRetries })\n```\n\n---\n\n## Checkout Payment\n\nCreates a hosted checkout page. Customer gets redirected to PayMongo, then back to your success/cancel URL.\n\n```ts\nconst payment = await pg.payments.create({\n  amount: 10000,        // centavos (PHP 100.00)\n  currency: 'PHP',\n  successUrl: 'https://myapp.com/success',\n  cancelUrl: 'https://myapp.com/cancel',\n  description: 'Order #123',\n  customer: { email: 'user@example.com', name: 'Juan' },\n  metadata: { orderId: '123' },\n})\n\n// Redirect user to:\npayment.checkoutUrl\n```\n\n## Payment Intent\n\nUse when you need a specific payment method (GCash, Maya, card, GrabPay, bank transfer). Returns method-specific details like redirect URLs or QR codes.\n\n```ts\nconst intent = await pg.payments.createIntent({\n  amount: 10000,\n  currency: 'PHP',\n  paymentMethod: 'gcash',  // 'gcash' | 'paymaya' | 'card' | 'grab_pay' | 'bank_transfer'\n  successUrl: 'https://myapp.com/success',\n  cancelUrl: 'https://myapp.com/cancel',\n})\n\nintent.paymentMethodDetails.redirectUrl  // send user here\nintent.clientKey                         // for client-side polling\n```\n\n## Status Check\n\nCheck current payment status by transaction ID.\n\n```ts\nconst status = await pg.payments.get('transaction-uuid')\n// status.status → 'AWAITING_PAYMENT_METHOD' | 'PENDING' | 'SUCCEEDED' | 'FAILED' | 'CANCELLED'\n```\n\nPublic status (no auth, for client-side):\n\n```ts\nconst status = await pg.payments.getPublicStatus('payment-intent-id')\n```\n\n## Refund\n\nRefund a payment fully or partially. Amount in centavos; omit for full refund.\n\n```ts\nconst refund = await pg.refunds.create('transaction-uuid', {\n  reason: 'requested_by_customer',  // 'duplicate' | 'fraudulent' | 'requested_by_customer' | 'others'\n  amount: 5000,                     // optional, partial refund in centavos\n  notes: 'Customer requested',      // optional, max 500 chars\n})\n\nrefund.totalRefunded        // cumulative refunded amount\nrefund.remainingRefundable  // what's left\n```\n\n## Idempotency\n\nPass idempotency keys on create operations to prevent duplicate charges.\n\n```ts\nawait pg.payments.create(params, { idempotencyKey: 'order-123-attempt-1' })\nawait pg.refunds.create(id, params, { idempotencyKey: 'refund-order-123' })\n```\n\n## Webhook Verification\n\nVerifies HMAC-SHA256 signature from `X-Webhook-Signature` header. Throws `WebhookSignatureError` on failure.\n\n```ts\nimport { PaymentGateway, WebhookSignatureError } from '@altev/pg-sdk'\n\nconst pg = new PaymentGateway('sk_test_xxx')\n\n// Express example\napp.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {\n  try {\n    const event = pg.webhooks.constructEvent(\n      req.body,                            // raw body (string | Buffer)\n      req.headers['x-webhook-signature'],  // signature header\n      'whsec_your_webhook_secret',         // webhook secret\n    )\n\n    switch (event.event) {\n      case 'payment.completed': /* ... */ break\n      case 'payment.failed':    /* ... */ break\n      case 'payment.expired':   /* ... */ break\n      case 'payment.refunded':  /* ... */ break\n    }\n\n    res.sendStatus(200)\n  } catch (err) {\n    if (err instanceof WebhookSignatureError) {\n      return res.status(400).send('Invalid signature')\n    }\n    throw err\n  }\n})\n```\n\nSignature tolerance default: 300s (5 min). Override:\n\n```ts\npg.webhooks.constructEvent(body, sig, secret, { tolerance: 600 })\n```\n\n---\n\n## NestJS Integration\n\nDrop-in NestJS module. Registers `PaymentGateway` as global injectable.\n\n### Module Setup\n\n```ts\n// app.module.ts\nimport { PaymentGatewayModule } from '@altev/pg-sdk/nestjs'\n\n@Module({\n  imports: [\n    // Sync\n    PaymentGatewayModule.register({\n      secretKey: 'sk_test_xxx',\n      webhookSecret: 'whsec_xxx',\n    }),\n\n    // Async (from ConfigService)\n    PaymentGatewayModule.registerAsync({\n      imports: [ConfigModule],\n      inject: [ConfigService],\n      useFactory: (config: ConfigService) => ({\n        secretKey: config.get('PG_SECRET_KEY'),\n        webhookSecret: config.get('PG_WEBHOOK_SECRET'),\n      }),\n    }),\n  ],\n})\nexport class AppModule {}\n```\n\n**Important:** Enable `rawBody` for webhook verification:\n\n```ts\nconst app = await NestFactory.create(AppModule, { rawBody: true })\n```\n\n### Inject & Use\n\n```ts\nimport { PaymentGateway } from '@altev/pg-sdk'\n\n@Injectable()\nexport class PaymentService {\n  constructor(private readonly pg: PaymentGateway) {}\n\n  async charge(amount: number) {\n    return this.pg.payments.create({\n      amount,\n      currency: 'PHP',\n      successUrl: 'https://myapp.com/success',\n      cancelUrl: 'https://myapp.com/cancel',\n    })\n  }\n}\n```\n\n### Webhook Controller\n\n`WebhookGuard` verifies signature automatically. `@WebhookEvent()` extracts the parsed event.\n\n```ts\nimport { Controller, Post, UseGuards } from '@nestjs/common'\nimport { WebhookGuard, WebhookEvent } from '@altev/pg-sdk/nestjs'\nimport type { WebhookEvent as WebhookEventType } from '@altev/pg-sdk'\n\n@Controller('webhook')\nexport class WebhookController {\n  @Post()\n  @UseGuards(WebhookGuard)\n  handle(@WebhookEvent() event: WebhookEventType) {\n    switch (event.event) {\n      case 'payment.completed':\n        // event.data.transactionId, event.data.amount, etc.\n        break\n      case 'payment.failed':\n        // event.data.failureReason\n        break\n    }\n    return { received: true }\n  }\n}\n```\n\n---\n\n## Error Handling\n\nAll errors extend `PaymentGatewayError`. Catch specific types:\n\n```ts\nimport {\n  ApiError,\n  AuthenticationError,\n  RateLimitError,\n  NetworkError,\n  ValidationError,\n  WebhookSignatureError,\n} from '@altev/pg-sdk'\n\ntry {\n  await pg.payments.create(params)\n} catch (err) {\n  if (err instanceof ValidationError) {\n    // Client-side validation failed before API call\n    console.log(err.field, err.message)\n  }\n  if (err instanceof AuthenticationError) {\n    // 401 — bad API key\n  }\n  if (err instanceof RateLimitError) {\n    // 429 — err.retryAfter (seconds), err.retryable = true\n  }\n  if (err instanceof ApiError) {\n    // Any API error — err.statusCode, err.code, err.correlationId, err.retryable\n  }\n  if (err instanceof NetworkError) {\n    // Fetch failed — err.retryable = true\n  }\n}\n```\n\n---\n\n## Testing Utils\n\nMock gateway and fixture factories for unit tests. No real API calls.\n\n```ts\nimport {\n  MockPaymentGateway,\n  createPaymentFixture,\n  createRefundFixture,\n  createWebhookEventFixture,\n  generateTestSignature,\n} from '@altev/pg-sdk/testing'\n```\n\n### Mock Gateway\n\nDrop-in replacement. All methods return fixture defaults.\n\n```ts\n// NestJS test\nconst module = await Test.createTestingModule({\n  providers: [\n    PaymentService,\n    { provide: PaymentGateway, useValue: new MockPaymentGateway() },\n  ],\n}).compile()\n```\n\n### Fixtures\n\nOverride any field:\n\n```ts\nconst payment = createPaymentFixture({ status: 'SUCCEEDED', amount: 50000 })\nconst refund = createRefundFixture({ reason: 'duplicate' })\nconst event = createWebhookEventFixture({ event: 'payment.failed' })\n```\n\nAvailable: `createPaymentFixture`, `createPaymentIntentFixture`, `createPaymentStatusFixture`, `createRefundFixture`, `createWebhookEventFixture`.\n\n### Test Signatures\n\nGenerate valid webhook signatures for testing your webhook handler:\n\n```ts\nconst payload = JSON.stringify(createWebhookEventFixture())\nconst signature = generateTestSignature(payload, 'whsec_test_secret')\n// Use in test requests as X-Webhook-Signature header\n```\n\n---\n\n## MCP Server\n\nAI assistant integration via [Model Context Protocol](https://modelcontextprotocol.io). Exposes payment tools + documentation as MCP resources.\n\n### Claude Desktop / Cursor\n\n```json\n{\n  \"mcpServers\": {\n    \"payment-gateway\": {\n      \"command\": \"npx\",\n      \"args\": [\"@altev/pg-sdk\", \"mcp\"],\n      \"env\": {\n        \"PG_SECRET_KEY\": \"sk_test_xxx\"\n      }\n    }\n  }\n}\n```\n\nWithout `PG_SECRET_KEY`, starts in docs-only mode (documentation resources available, payment tools disabled).\n\n---\n\n## Types\n\nAll types exported from main entry:\n\n```ts\nimport type {\n  Currency,               // 'PHP' | 'USD'\n  PaymentMethod,          // 'gcash' | 'paymaya' | 'card' | 'grab_pay' | 'bank_transfer'\n  TransactionStatus,      // 'AWAITING_PAYMENT_METHOD' | 'PENDING' | 'SUCCEEDED' | 'FAILED' | 'CANCELLED'\n  Environment,            // 'TEST' | 'LIVE'\n  RefundReason,           // 'duplicate' | 'fraudulent' | 'requested_by_customer' | 'others'\n  WebhookEventType,       // 'payment.completed' | 'payment.failed' | 'payment.expired' | 'payment.refunded'\n  CreatePaymentParams,\n  PaymentResponse,\n  CreatePaymentIntentParams,\n  PaymentIntentResponse,\n  PaymentStatus,\n  CreateRefundParams,\n  RefundResponse,\n  WebhookEvent,\n  CustomerInfo,\n  PaymentGatewayConfig,\n} from '@altev/pg-sdk'\n```\n","readmeFilename":"README.md","_rev":"1-f5be4b007bb49961732bb788ab2971eb"}