@innovateium/payload-dpo 0.0.1-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +177 -0
  3. package/dist/collections/DpoTransactions.d.ts +3 -0
  4. package/dist/collections/DpoTransactions.js +121 -0
  5. package/dist/collections/DpoTransactions.js.map +1 -0
  6. package/dist/collections/index.d.ts +3 -0
  7. package/dist/collections/index.js +9 -0
  8. package/dist/collections/index.js.map +1 -0
  9. package/dist/endpoints/index.d.ts +3 -0
  10. package/dist/endpoints/index.js +12 -0
  11. package/dist/endpoints/index.js.map +1 -0
  12. package/dist/endpoints/initiate.d.ts +3 -0
  13. package/dist/endpoints/initiate.js +131 -0
  14. package/dist/endpoints/initiate.js.map +1 -0
  15. package/dist/endpoints/notify.d.ts +3 -0
  16. package/dist/endpoints/notify.js +63 -0
  17. package/dist/endpoints/notify.js.map +1 -0
  18. package/dist/endpoints/return.d.ts +3 -0
  19. package/dist/endpoints/return.js +59 -0
  20. package/dist/endpoints/return.js.map +1 -0
  21. package/dist/endpoints/status.d.ts +3 -0
  22. package/dist/endpoints/status.js +74 -0
  23. package/dist/endpoints/status.js.map +1 -0
  24. package/dist/exports/client.d.ts +1 -0
  25. package/dist/exports/client.js +3 -0
  26. package/dist/exports/client.js.map +1 -0
  27. package/dist/exports/rsc.d.ts +1 -0
  28. package/dist/exports/rsc.js +3 -0
  29. package/dist/exports/rsc.js.map +1 -0
  30. package/dist/hooks/afterPayment.d.ts +3 -0
  31. package/dist/hooks/afterPayment.js +18 -0
  32. package/dist/hooks/afterPayment.js.map +1 -0
  33. package/dist/index.d.ts +3 -0
  34. package/dist/index.js +26 -0
  35. package/dist/index.js.map +1 -0
  36. package/dist/lib/checksum.d.ts +1 -0
  37. package/dist/lib/checksum.js +8 -0
  38. package/dist/lib/checksum.js.map +1 -0
  39. package/dist/lib/constants.d.ts +21 -0
  40. package/dist/lib/constants.js +89 -0
  41. package/dist/lib/constants.js.map +1 -0
  42. package/dist/lib/paygate.d.ts +3 -0
  43. package/dist/lib/paygate.js +43 -0
  44. package/dist/lib/paygate.js.map +1 -0
  45. package/dist/types.d.ts +26 -0
  46. package/dist/types.js +3 -0
  47. package/dist/types.js.map +1 -0
  48. package/package.json +138 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Innovateium
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,177 @@
1
+ # Payload DPO — PayGate PayWeb3 Plugin
2
+
3
+ [![npm](https://img.shields.io/npm/v/@innovateium/payload-dpo)](https://www.npmjs.com/package/@innovateium/payload-dpo)
4
+ [![License](https://img.shields.io/github/license/innovateium/payload-dpo)](LICENSE)
5
+ [![Beta](https://img.shields.io/badge/status-beta-yellow)]()
6
+
7
+ > **Beta** — This plugin is in active development. APIs may change between versions.
8
+
9
+ A [Payload CMS](https://payloadcms.com) v3 plugin that integrates [PayGate PayWeb3](https://www.paygate.co.za/payweb3/) (Direct Pay Online) — a payment gateway serving South African and African markets.
10
+
11
+ ## Features
12
+
13
+ - **Initiate** — POST to `/api/dpo/initiate` initiates a transaction with PayGate, returns the redirect URL
14
+ - **Redirect** — Front-end submits `PAY_REQUEST_ID` + `CHECKSUM` to PayGate's hosted payment page
15
+ - **Notify** — PayGate sends an IPN to `/api/dpo/notify` — the plugin updates the transaction record
16
+ - **Return** — PayGate redirects the user back; the plugin redirects to your front-end result page
17
+ - **Status** — `GET /api/dpo/status?id=xxx` queries PayGate's `query.trans` for the latest status
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ pnpm add @innovateium/payload-dpo
23
+ # or
24
+ npm install @innovateium/payload-dpo
25
+ # or
26
+ yarn add @innovateium/payload-dpo
27
+ ```
28
+
29
+ ## Usage
30
+
31
+ ### 1. Register the plugin
32
+
33
+ In your `payload.config.ts`:
34
+
35
+ ```ts
36
+ import { dpoPlugin } from '@innovateium/payload-dpo'
37
+
38
+ export default buildConfig({
39
+ plugins: [
40
+ dpoPlugin({
41
+ paygateId: process.env.PAYGATE_ID,
42
+ paygateKey: process.env.PAYGATE_KEY,
43
+ baseUrl: process.env.BASE_URL,
44
+ }),
45
+ ],
46
+ })
47
+ ```
48
+
49
+ ### 2. Set environment variables
50
+
51
+ ```bash
52
+ PAYGATE_ID=10011072130 # Your PayGate merchant ID
53
+ PAYGATE_KEY=secret # Your PayGate secret key
54
+ BASE_URL=http://localhost:3000 # Your app's public URL
55
+ PAYLOAD_SECRET=your-secret # Payload secret
56
+ DATABASE_URL=... # Your database URL
57
+ ```
58
+
59
+ > **Note**: `BASE_URL` must be a publicly reachable URL if you want PayGate's IPN (notify) callbacks to work. Use [ngrok](https://ngrok.com) during local development.
60
+
61
+ ### 3. Create the test front-end
62
+
63
+ The plugin registers a `dpo-transactions` collection visible in the admin panel under **DPO Payments**.
64
+
65
+ For testing, create a payment form that calls the initiate endpoint:
66
+
67
+ ```tsx
68
+ const res = await fetch('/api/dpo/initiate', {
69
+ method: 'POST',
70
+ headers: { 'Content-Type': 'application/json' },
71
+ body: JSON.stringify({ amount: '1000', email: 'user@example.com', currency: 'ZAR' }),
72
+ })
73
+
74
+ const data = await res.json()
75
+
76
+ const form = document.createElement('form')
77
+ form.method = 'POST'
78
+ form.action = data.paymentUrl
79
+ form.innerHTML = `
80
+ <input type="hidden" name="PAY_REQUEST_ID" value="${data.payRequestId}" />
81
+ <input type="hidden" name="CHECKSUM" value="${data.checksum}" />
82
+ `
83
+ document.body.appendChild(form)
84
+ form.submit()
85
+ ```
86
+
87
+ ## Configuration
88
+
89
+ ### `DpoPluginConfig`
90
+
91
+ | Option | Type | Default | Description |
92
+ | --------------------------- | --------------------------------------- | ------------------------------ | ----------------------------------------------- |
93
+ | `paygateId` | `string` | env `PAYGATE_ID` | Your PayGate merchant ID |
94
+ | `paygateKey` | `string` | env `PAYGATE_KEY` | Your PayGate secret key |
95
+ | `baseUrl` | `string` | env `BASE_URL` or `serverURL` | Public base URL for RETURN/NOTIFY URLs |
96
+ | `paygateUrl` | `string` | `https://secure.paygate.co.za` | PayGate API base URL |
97
+ | `disabled` | `boolean` | `false` | Disable the plugin (collections still register) |
98
+ | `collections` | `Partial<Record<CollectionSlug, true>>` | — | Collections to add a DPO relationship field to |
99
+ | `defaultCurrency` | `'ZAR' \| 'BWP' \| 'USD'` | `'ZAR'` | Default currency |
100
+ | `defaultCountry` | `string` | Auto from currency | Override the ISO country code sent to PayGate |
101
+ | `defaultLocale` | `string` | Auto from currency | Override the locale sent to PayGate |
102
+ | `transactionCollectionSlug` | `string` | `'dpo-transactions'` | Custom collection slug for transactions |
103
+ | `routes` | `DpoRoutes` | See below | Custom API endpoint paths |
104
+ | `onSuccess` | `(args) => Promise<void>` | — | Callback when a transaction is approved |
105
+
106
+ ### `DpoRoutes`
107
+
108
+ | Path | Default | Description |
109
+ | ---------- | --------------- | ------------------------- |
110
+ | `initiate` | `/dpo/initiate` | Initiate endpoint |
111
+ | `return` | `/dpo/return` | Return redirect endpoint |
112
+ | `notify` | `/dpo/notify` | IPN notification endpoint |
113
+ | `status` | `/dpo/status` | Status query endpoint |
114
+
115
+ ### Currency auto-mapping
116
+
117
+ Country and locale are auto-resolved from the selected currency:
118
+
119
+ | Currency | Country | Locale |
120
+ | -------- | ------- | ------- |
121
+ | `ZAR` | `ZAF` | `en-za` |
122
+ | `BWP` | `BWA` | `en-bw` |
123
+ | `USD` | `USA` | `en-us` |
124
+
125
+ Override with `defaultCountry` / `defaultLocale`.
126
+
127
+ ## Collection: `dpo-transactions`
128
+
129
+ | Field | Type | Description |
130
+ | ------------------- | ------------------------ | ------------------------------------------ |
131
+ | `payRequestId` | `text` (unique, indexed) | Returned by PayGate on initiate |
132
+ | `reference` | `text` (indexed) | Internal merchant order reference |
133
+ | `amount` | `number` | Amount in cents |
134
+ | `currency` | `select` | ZAR / BWP / USD |
135
+ | `email` | `email` | Customer email |
136
+ | `transactionStatus` | `select` | 0=Not Done, 1=Approved, 2=Declined, etc. |
137
+ | `statusMessage` | `text` | Human-readable status |
138
+ | `rawResponse` | `json` | Full PayGate response for auditing |
139
+ | `relatedCollection` | `text` | Slug of related collection |
140
+ | `relatedDoc` | `relationship` | Polymorphic link to a purchasable document |
141
+
142
+ ## Payment Flow
143
+
144
+ ```
145
+ User → Payment Form → POST /api/dpo/initiate
146
+
147
+ PayGate initiate.trans
148
+
149
+ { payRequestId, checksum, paymentUrl }
150
+
151
+ Browser auto-submits to PayGate process.trans
152
+
153
+ User completes payment on PayGate's hosted page
154
+
155
+ ┌────────────────┴────────────────┐
156
+ ↓ ↓
157
+ POST /api/dpo/notify (IPN) Browser redirect to RETURN_URL
158
+ (updates transaction status) ↓
159
+ /payment-result page
160
+
161
+ GET /api/dpo/status
162
+ (queries PayGate query.trans)
163
+ ```
164
+
165
+ ## Development
166
+
167
+ ```bash
168
+ pnpm dev
169
+ ```
170
+
171
+ Opens `http://localhost:3000`. Visit `/test-payment` to test the payment flow.
172
+
173
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for development guidelines.
174
+
175
+ ## License
176
+
177
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,3 @@
1
+ import type { CollectionConfig } from 'payload';
2
+ import type { DpoPluginConfig } from '../types.js';
3
+ export declare const createDpoTransactionsCollection: (pluginOptions: DpoPluginConfig) => CollectionConfig;
@@ -0,0 +1,121 @@
1
+ import { afterPaymentHook } from '../hooks/afterPayment.js';
2
+ import { CURRENCY_OPTIONS, TRANSACTION_STATUS_OPTIONS } from '../lib/constants.js';
3
+ export const createDpoTransactionsCollection = (pluginOptions)=>({
4
+ slug: pluginOptions.transactionCollectionSlug ?? 'dpo-transactions',
5
+ access: {
6
+ create: ({ req: { user } })=>Boolean(user),
7
+ delete: ({ req: { user } })=>Boolean(user),
8
+ read: ({ req: { user } })=>Boolean(user),
9
+ update: ({ req: { user } })=>Boolean(user)
10
+ },
11
+ admin: {
12
+ defaultColumns: [
13
+ 'reference',
14
+ 'amount',
15
+ 'currency',
16
+ 'transactionStatus',
17
+ 'email',
18
+ 'updatedAt'
19
+ ],
20
+ group: 'DPO Payments',
21
+ listSearchableFields: [
22
+ 'reference',
23
+ 'payRequestId',
24
+ 'email'
25
+ ],
26
+ useAsTitle: 'reference'
27
+ },
28
+ fields: [
29
+ {
30
+ name: 'payRequestId',
31
+ type: 'text',
32
+ admin: {
33
+ readOnly: true
34
+ },
35
+ required: false,
36
+ unique: true
37
+ },
38
+ {
39
+ name: 'reference',
40
+ type: 'text',
41
+ admin: {
42
+ readOnly: true
43
+ },
44
+ index: true,
45
+ required: true,
46
+ unique: true
47
+ },
48
+ {
49
+ name: 'amount',
50
+ type: 'number',
51
+ admin: {
52
+ readOnly: true
53
+ },
54
+ required: true
55
+ },
56
+ {
57
+ name: 'currency',
58
+ type: 'select',
59
+ admin: {
60
+ readOnly: true
61
+ },
62
+ options: CURRENCY_OPTIONS,
63
+ required: true
64
+ },
65
+ {
66
+ name: 'email',
67
+ type: 'email',
68
+ admin: {
69
+ readOnly: true
70
+ },
71
+ required: true
72
+ },
73
+ {
74
+ name: 'transactionStatus',
75
+ type: 'select',
76
+ admin: {
77
+ readOnly: true
78
+ },
79
+ defaultValue: '0',
80
+ options: TRANSACTION_STATUS_OPTIONS,
81
+ required: true
82
+ },
83
+ {
84
+ name: 'statusMessage',
85
+ type: 'text',
86
+ admin: {
87
+ readOnly: true
88
+ }
89
+ },
90
+ {
91
+ name: 'rawResponse',
92
+ type: 'json',
93
+ admin: {
94
+ readOnly: true
95
+ }
96
+ },
97
+ {
98
+ name: 'relatedCollection',
99
+ type: 'text',
100
+ admin: {
101
+ readOnly: true
102
+ }
103
+ },
104
+ {
105
+ name: 'relatedDoc',
106
+ type: 'relationship',
107
+ admin: {
108
+ readOnly: true
109
+ },
110
+ hasMany: false,
111
+ relationTo: pluginOptions.collections ? Object.keys(pluginOptions.collections) : []
112
+ }
113
+ ],
114
+ hooks: {
115
+ afterChange: [
116
+ afterPaymentHook(pluginOptions)
117
+ ]
118
+ }
119
+ });
120
+
121
+ //# sourceMappingURL=DpoTransactions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/collections/DpoTransactions.ts"],"sourcesContent":["import type { CollectionConfig } from 'payload'\n\nimport type { DpoPluginConfig } from '../types.js'\n\nimport { afterPaymentHook } from '../hooks/afterPayment.js'\nimport { CURRENCY_OPTIONS, TRANSACTION_STATUS_OPTIONS } from '../lib/constants.js'\n\nexport const createDpoTransactionsCollection = (\n pluginOptions: DpoPluginConfig,\n): CollectionConfig => ({\n slug: pluginOptions.transactionCollectionSlug ?? 'dpo-transactions',\n access: {\n create: ({ req: { user } }) => Boolean(user),\n delete: ({ req: { user } }) => Boolean(user),\n read: ({ req: { user } }) => Boolean(user),\n update: ({ req: { user } }) => Boolean(user),\n },\n admin: {\n defaultColumns: ['reference', 'amount', 'currency', 'transactionStatus', 'email', 'updatedAt'],\n group: 'DPO Payments',\n listSearchableFields: ['reference', 'payRequestId', 'email'],\n useAsTitle: 'reference',\n },\n fields: [\n {\n name: 'payRequestId',\n type: 'text',\n admin: {\n readOnly: true,\n },\n required: false,\n unique: true,\n },\n {\n name: 'reference',\n type: 'text',\n admin: {\n readOnly: true,\n },\n index: true,\n required: true,\n unique: true,\n },\n {\n name: 'amount',\n type: 'number',\n admin: {\n readOnly: true,\n },\n required: true,\n },\n {\n name: 'currency',\n type: 'select',\n admin: {\n readOnly: true,\n },\n options: CURRENCY_OPTIONS,\n required: true,\n },\n {\n name: 'email',\n type: 'email',\n admin: {\n readOnly: true,\n },\n required: true,\n },\n {\n name: 'transactionStatus',\n type: 'select',\n admin: {\n readOnly: true,\n },\n defaultValue: '0',\n options: TRANSACTION_STATUS_OPTIONS,\n required: true,\n },\n {\n name: 'statusMessage',\n type: 'text',\n admin: {\n readOnly: true,\n },\n },\n {\n name: 'rawResponse',\n type: 'json',\n admin: {\n readOnly: true,\n },\n },\n {\n name: 'relatedCollection',\n type: 'text',\n admin: {\n readOnly: true,\n },\n },\n {\n name: 'relatedDoc',\n type: 'relationship',\n admin: {\n readOnly: true,\n },\n hasMany: false,\n relationTo: pluginOptions.collections ? Object.keys(pluginOptions.collections) : [],\n },\n ],\n hooks: {\n afterChange: [afterPaymentHook(pluginOptions)],\n },\n})\n"],"names":["afterPaymentHook","CURRENCY_OPTIONS","TRANSACTION_STATUS_OPTIONS","createDpoTransactionsCollection","pluginOptions","slug","transactionCollectionSlug","access","create","req","user","Boolean","delete","read","update","admin","defaultColumns","group","listSearchableFields","useAsTitle","fields","name","type","readOnly","required","unique","index","options","defaultValue","hasMany","relationTo","collections","Object","keys","hooks","afterChange"],"mappings":"AAIA,SAASA,gBAAgB,QAAQ,2BAA0B;AAC3D,SAASC,gBAAgB,EAAEC,0BAA0B,QAAQ,sBAAqB;AAElF,OAAO,MAAMC,kCAAkC,CAC7CC,gBACsB,CAAA;QACtBC,MAAMD,cAAcE,yBAAyB,I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;gBACEF,MAAM;gBACNC,MAAM;gBACNP,OAAO;oBACLQ,UAAU;gBACZ;YACF;YACA;gBACEF,MAAM;gBACNC,MAAM;gBACNP,OAAO;oBACLQ,UAAU;gBACZ;gBACAM,SAAS;gBACTC,YAAY1B,cAAc2B,WAAW,GAAGC,OAAOC,IAAI,CAAC7B,cAAc2B,WAAW,IAAI,EAAE;YACrF;SACD;QACDG,OAAO;YACLC,aAAa;gBAACnC,iBAAiBI;aAAe;QAChD;IACF,CAAA,EAAE"}
@@ -0,0 +1,3 @@
1
+ import type { CollectionConfig } from 'payload';
2
+ import type { DpoPluginConfig } from '../types.js';
3
+ export declare const getCollections: (pluginOptions: DpoPluginConfig) => CollectionConfig[];
@@ -0,0 +1,9 @@
1
+ import { createDpoTransactionsCollection } from './DpoTransactions.js';
2
+ export const getCollections = (pluginOptions)=>{
3
+ const collections = [
4
+ createDpoTransactionsCollection(pluginOptions)
5
+ ];
6
+ return collections;
7
+ };
8
+
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/collections/index.ts"],"sourcesContent":["import type { CollectionConfig } from 'payload'\n\nimport type { DpoPluginConfig } from '../types.js'\n\nimport { createDpoTransactionsCollection } from './DpoTransactions.js'\n\nexport const getCollections = (pluginOptions: DpoPluginConfig): CollectionConfig[] => {\n const collections: CollectionConfig[] = [createDpoTransactionsCollection(pluginOptions)]\n\n return collections\n}\n"],"names":["createDpoTransactionsCollection","getCollections","pluginOptions","collections"],"mappings":"AAIA,SAASA,+BAA+B,QAAQ,uBAAsB;AAEtE,OAAO,MAAMC,iBAAiB,CAACC;IAC7B,MAAMC,cAAkC;QAACH,gCAAgCE;KAAe;IAExF,OAAOC;AACT,EAAC"}
@@ -0,0 +1,3 @@
1
+ import type { Endpoint } from 'payload';
2
+ import type { DpoPluginConfig } from '../types.js';
3
+ export declare const getEndpoints: (pluginOptions: DpoPluginConfig) => Endpoint[];
@@ -0,0 +1,12 @@
1
+ import { createInitiateEndpoint } from './initiate.js';
2
+ import { createNotifyEndpoint } from './notify.js';
3
+ import { createReturnEndpoint } from './return.js';
4
+ import { createStatusEndpoint } from './status.js';
5
+ export const getEndpoints = (pluginOptions)=>[
6
+ createInitiateEndpoint(pluginOptions),
7
+ createNotifyEndpoint(pluginOptions),
8
+ ...createReturnEndpoint(pluginOptions),
9
+ createStatusEndpoint(pluginOptions)
10
+ ];
11
+
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/endpoints/index.ts"],"sourcesContent":["import type { Endpoint } from 'payload'\n\nimport type { DpoPluginConfig } from '../types.js'\n\nimport { createInitiateEndpoint } from './initiate.js'\nimport { createNotifyEndpoint } from './notify.js'\nimport { createReturnEndpoint } from './return.js'\nimport { createStatusEndpoint } from './status.js'\n\nexport const getEndpoints = (pluginOptions: DpoPluginConfig): Endpoint[] => [\n createInitiateEndpoint(pluginOptions),\n createNotifyEndpoint(pluginOptions),\n ...createReturnEndpoint(pluginOptions),\n createStatusEndpoint(pluginOptions),\n]\n"],"names":["createInitiateEndpoint","createNotifyEndpoint","createReturnEndpoint","createStatusEndpoint","getEndpoints","pluginOptions"],"mappings":"AAIA,SAASA,sBAAsB,QAAQ,gBAAe;AACtD,SAASC,oBAAoB,QAAQ,cAAa;AAClD,SAASC,oBAAoB,QAAQ,cAAa;AAClD,SAASC,oBAAoB,QAAQ,cAAa;AAElD,OAAO,MAAMC,eAAe,CAACC,gBAA+C;QAC1EL,uBAAuBK;QACvBJ,qBAAqBI;WAClBH,qBAAqBG;QACxBF,qBAAqBE;KACtB,CAAA"}
@@ -0,0 +1,3 @@
1
+ import type { Endpoint } from 'payload';
2
+ import type { DpoPluginConfig } from '../types.js';
3
+ export declare const createInitiateEndpoint: (pluginOptions: DpoPluginConfig) => Endpoint;
@@ -0,0 +1,131 @@
1
+ import { generateSignature } from '../lib/checksum.js';
2
+ import { CURRENCY_LOCALE_MAP, DEFAULT_PAYGATE_URL, DEFAULT_ROUTES } from '../lib/constants.js';
3
+ import { initiateTransaction } from '../lib/paygate.js';
4
+ function buildReturnUrl(baseUrl, routes) {
5
+ return `${baseUrl}/api${routes?.return ?? DEFAULT_ROUTES.return}`;
6
+ }
7
+ function buildNotifyUrl(baseUrl, routes) {
8
+ return `${baseUrl}/api${routes?.notify ?? DEFAULT_ROUTES.notify}`;
9
+ }
10
+ function resolveCountry(currency, configDefault) {
11
+ if (configDefault) return configDefault;
12
+ return CURRENCY_LOCALE_MAP[currency]?.country ?? 'ZAF';
13
+ }
14
+ function resolveLocale(currency, configDefault) {
15
+ if (configDefault) return configDefault;
16
+ return CURRENCY_LOCALE_MAP[currency]?.locale ?? 'en-za';
17
+ }
18
+ export const createInitiateEndpoint = (pluginOptions)=>{
19
+ const initiatePath = pluginOptions.routes?.initiate ?? DEFAULT_ROUTES.initiate;
20
+ const collectionSlug = pluginOptions.transactionCollectionSlug ?? 'dpo-transactions';
21
+ return {
22
+ handler: async (req)=>{
23
+ try {
24
+ const body = await req.json?.() ?? {};
25
+ const { amount, currency, email, reference, relatedCollection, relatedDoc } = body;
26
+ if (!amount || !email) {
27
+ return Response.json({
28
+ error: 'Amount and email are required',
29
+ success: false
30
+ }, {
31
+ status: 400
32
+ });
33
+ }
34
+ const paygateId = pluginOptions.paygateId || process.env.PAYGATE_ID || '';
35
+ const paygateKey = pluginOptions.paygateKey || process.env.PAYGATE_KEY || '';
36
+ const paygateUrl = pluginOptions.paygateUrl || process.env.PAYGATE_URL || DEFAULT_PAYGATE_URL;
37
+ const serverUrl = req.payload?.config?.serverURL || '';
38
+ const baseUrl = pluginOptions.baseUrl || process.env.BASE_URL || serverUrl;
39
+ if (!paygateId || !paygateKey) {
40
+ return Response.json({
41
+ error: 'PayGate is not configured — missing PAYGATE_ID or PAYGATE_KEY',
42
+ success: false
43
+ }, {
44
+ status: 500
45
+ });
46
+ }
47
+ if (!baseUrl) {
48
+ return Response.json({
49
+ error: 'BASE_URL is not configured. Set BASE_URL in your .env (e.g., https://www.example.com) or configure the Payload serverURL.',
50
+ success: false
51
+ }, {
52
+ status: 500
53
+ });
54
+ }
55
+ const formattedAmount = String(amount).replace(/\D/g, '');
56
+ const txReference = reference || `ORDER_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
57
+ const txCurrency = currency || pluginOptions.defaultCurrency || 'ZAR';
58
+ const transactionData = {
59
+ AMOUNT: formattedAmount,
60
+ COUNTRY: resolveCountry(txCurrency, pluginOptions.defaultCountry),
61
+ CURRENCY: txCurrency,
62
+ EMAIL: email,
63
+ LOCALE: resolveLocale(txCurrency, pluginOptions.defaultLocale),
64
+ NOTIFY_URL: buildNotifyUrl(baseUrl, pluginOptions.routes),
65
+ PAYGATE_ID: paygateId,
66
+ REFERENCE: txReference,
67
+ RETURN_URL: buildReturnUrl(baseUrl, pluginOptions.routes),
68
+ TRANSACTION_DATE: new Date().toISOString().slice(0, 19).replace('T', ' ')
69
+ };
70
+ const checksum = generateSignature(transactionData, paygateKey);
71
+ transactionData.CHECKSUM = checksum;
72
+ const responseParams = await initiateTransaction(paygateUrl, transactionData);
73
+ if (responseParams.ERROR) {
74
+ return Response.json({
75
+ error: `PayGate Error: ${responseParams.ERROR}`,
76
+ success: false
77
+ }, {
78
+ status: 400
79
+ });
80
+ }
81
+ if (!responseParams.PAY_REQUEST_ID || !responseParams.CHECKSUM) {
82
+ return Response.json({
83
+ error: 'Invalid PayGate response — missing PAY_REQUEST_ID or CHECKSUM',
84
+ raw: responseParams,
85
+ sentTo: `${paygateUrl}/payweb3/initiate.trans`,
86
+ success: false
87
+ }, {
88
+ status: 500
89
+ });
90
+ }
91
+ if (req.payload) {
92
+ await req.payload.create({
93
+ collection: collectionSlug,
94
+ data: {
95
+ amount: parseInt(formattedAmount, 10),
96
+ currency: txCurrency,
97
+ email,
98
+ payRequestId: responseParams.PAY_REQUEST_ID,
99
+ rawResponse: responseParams,
100
+ reference: txReference,
101
+ relatedCollection: relatedCollection || null,
102
+ relatedDoc: relatedDoc || null,
103
+ statusMessage: 'Initiated',
104
+ transactionStatus: '0'
105
+ }
106
+ });
107
+ }
108
+ return Response.json({
109
+ checksum: responseParams.CHECKSUM,
110
+ paymentUrl: `${paygateUrl}/payweb3/process.trans`,
111
+ payRequestId: responseParams.PAY_REQUEST_ID,
112
+ reference: txReference,
113
+ success: true
114
+ });
115
+ } catch (error) {
116
+ const message = error instanceof Error ? error.message : 'Unknown error';
117
+ return Response.json({
118
+ error: 'Payment initiation failed',
119
+ message,
120
+ success: false
121
+ }, {
122
+ status: 500
123
+ });
124
+ }
125
+ },
126
+ method: 'post',
127
+ path: initiatePath
128
+ };
129
+ };
130
+
131
+ //# sourceMappingURL=initiate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/endpoints/initiate.ts"],"sourcesContent":["import type { Endpoint, PayloadRequest } from 'payload'\nimport { generateSignature } from '../lib/checksum.js'\nimport { CURRENCY_LOCALE_MAP, DEFAULT_PAYGATE_URL, DEFAULT_ROUTES } from '../lib/constants.js'\nimport { initiateTransaction } from '../lib/paygate.js'\nimport type { DpoPluginConfig, DpoRoutes } from '../types.js'\n\nfunction buildReturnUrl(baseUrl: string, routes: DpoRoutes | undefined): string {\n return `${baseUrl}/api${routes?.return ?? DEFAULT_ROUTES.return}`\n}\n\nfunction buildNotifyUrl(baseUrl: string, routes: DpoRoutes | undefined): string {\n return `${baseUrl}/api${routes?.notify ?? DEFAULT_ROUTES.notify}`\n}\n\nfunction resolveCountry(currency: string, configDefault: string | undefined): string {\n if (configDefault) return configDefault\n return CURRENCY_LOCALE_MAP[currency]?.country ?? 'ZAF'\n}\n\nfunction resolveLocale(currency: string, configDefault: string | undefined): string {\n if (configDefault) return configDefault\n return CURRENCY_LOCALE_MAP[currency]?.locale ?? 'en-za'\n}\n\nexport const createInitiateEndpoint = (pluginOptions: DpoPluginConfig): Endpoint => {\n const initiatePath = pluginOptions.routes?.initiate ?? DEFAULT_ROUTES.initiate\n const collectionSlug = pluginOptions.transactionCollectionSlug ?? 'dpo-transactions'\n\n return {\n handler: async (req: PayloadRequest) => {\n try {\n const body = (await req.json?.()) ?? {}\n const { amount, currency, email, reference, relatedCollection, relatedDoc } = body\n\n if (!amount || !email) {\n return Response.json(\n { error: 'Amount and email are required', success: false },\n { status: 400 },\n )\n }\n\n const paygateId = pluginOptions.paygateId || process.env.PAYGATE_ID || ''\n const paygateKey = pluginOptions.paygateKey || process.env.PAYGATE_KEY || ''\n const paygateUrl =\n pluginOptions.paygateUrl || process.env.PAYGATE_URL || DEFAULT_PAYGATE_URL\n const serverUrl = req.payload?.config?.serverURL || ''\n const baseUrl = pluginOptions.baseUrl || process.env.BASE_URL || serverUrl\n\n if (!paygateId || !paygateKey) {\n return Response.json(\n {\n error: 'PayGate is not configured — missing PAYGATE_ID or PAYGATE_KEY',\n success: false,\n },\n { status: 500 },\n )\n }\n\n if (!baseUrl) {\n return Response.json(\n {\n error:\n 'BASE_URL is not configured. Set BASE_URL in your .env (e.g., https://www.example.com) or configure the Payload serverURL.',\n success: false,\n },\n { status: 500 },\n )\n }\n\n const formattedAmount = String(amount).replace(/\\D/g, '')\n const txReference =\n reference || `ORDER_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`\n const txCurrency = currency || pluginOptions.defaultCurrency || 'ZAR'\n\n const transactionData: Record<string, string> = {\n AMOUNT: formattedAmount,\n COUNTRY: resolveCountry(txCurrency, pluginOptions.defaultCountry),\n CURRENCY: txCurrency,\n EMAIL: email,\n LOCALE: resolveLocale(txCurrency, pluginOptions.defaultLocale),\n NOTIFY_URL: buildNotifyUrl(baseUrl, pluginOptions.routes),\n PAYGATE_ID: paygateId,\n REFERENCE: txReference,\n RETURN_URL: buildReturnUrl(baseUrl, pluginOptions.routes),\n TRANSACTION_DATE: new Date().toISOString().slice(0, 19).replace('T', ' '),\n }\n\n const checksum = generateSignature(transactionData, paygateKey)\n transactionData.CHECKSUM = checksum\n\n const responseParams = await initiateTransaction(paygateUrl, transactionData)\n\n if (responseParams.ERROR) {\n return Response.json(\n { error: `PayGate Error: ${responseParams.ERROR}`, success: false },\n { status: 400 },\n )\n }\n\n if (!responseParams.PAY_REQUEST_ID || !responseParams.CHECKSUM) {\n return Response.json(\n {\n error: 'Invalid PayGate response — missing PAY_REQUEST_ID or CHECKSUM',\n raw: responseParams,\n sentTo: `${paygateUrl}/payweb3/initiate.trans`,\n success: false,\n },\n { status: 500 },\n )\n }\n\n if (req.payload) {\n await req.payload.create({\n collection: collectionSlug,\n data: {\n amount: parseInt(formattedAmount, 10),\n currency: txCurrency,\n email,\n payRequestId: responseParams.PAY_REQUEST_ID,\n rawResponse: responseParams,\n reference: txReference,\n relatedCollection: relatedCollection || null,\n relatedDoc: relatedDoc || null,\n statusMessage: 'Initiated',\n transactionStatus: '0',\n },\n })\n }\n\n return Response.json({\n checksum: responseParams.CHECKSUM,\n paymentUrl: `${paygateUrl}/payweb3/process.trans`,\n payRequestId: responseParams.PAY_REQUEST_ID,\n reference: txReference,\n success: true,\n })\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : 'Unknown error'\n return Response.json(\n {\n error: 'Payment initiation failed',\n message,\n success: false,\n },\n { status: 500 },\n )\n }\n },\n method: 'post',\n path: initiatePath,\n }\n}\n"],"names":["generateSignature","CURRENCY_LOCALE_MAP","DEFAULT_PAYGATE_URL","DEFAULT_ROUTES","initiateTransaction","buildReturnUrl","baseUrl","routes","return","buildNotifyUrl","notify","resolveCountry","currency","configDefault","country","resolveLocale","locale","createInitiateEndpoint","pluginOptions","initiatePath","initiate","collectionSlug","transactionCollectionSlug","handler","req","body","json","amount","email","reference","relatedCollection","relatedDoc","Response","error","success","status","paygateId","process","env","PAYGATE_ID","paygateKey","PAYGATE_KEY","paygateUrl","PAYGATE_URL","serverUrl","payload","config","serverURL","BASE_URL","formattedAmount","String","replace","txReference","Date","now","Math","random","toString","substring","txCurrency","defaultCurrency","transactionData","AMOUNT","COUNTRY","defaultCountry","CURRENCY","EMAIL","LOCALE","defaultLocale","NOTIFY_URL","REFERENCE","RETURN_URL","TRANSACTION_DATE","toISOString","slice","checksum","CHECKSUM","responseParams","ERROR","PAY_REQUEST_ID","raw","sentTo","create","collection","data","parseInt","payRequestId","rawResponse","statusMessage","transactionStatus","paymentUrl","message","Error","method","path"],"mappings":"AACA,SAASA,iBAAiB,QAAQ,qBAAoB;AACtD,SAASC,mBAAmB,EAAEC,mBAAmB,EAAEC,cAAc,QAAQ,sBAAqB;AAC9F,SAASC,mBAAmB,QAAQ,oBAAmB;AAGvD,SAASC,eAAeC,OAAe,EAAEC,MAA6B;IACpE,OAAO,GAAGD,QAAQ,IAAI,EAAEC,QAAQC,UAAUL,eAAeK,MAAM,EAAE;AACnE;AAEA,SAASC,eAAeH,OAAe,EAAEC,MAA6B;IACpE,OAAO,GAAGD,QAAQ,IAAI,EAAEC,QAAQG,UAAUP,eAAeO,MAAM,EAAE;AACnE;AAEA,SAASC,eAAeC,QAAgB,EAAEC,aAAiC;IACzE,IAAIA,eAAe,OAAOA;IAC1B,OAAOZ,mBAAmB,CAACW,SAAS,EAAEE,WAAW;AACnD;AAEA,SAASC,cAAcH,QAAgB,EAAEC,aAAiC;IACxE,IAAIA,eAAe,OAAOA;IAC1B,OAAOZ,mBAAmB,CAACW,SAAS,EAAEI,UAAU;AAClD;AAEA,OAAO,MAAMC,yBAAyB,CAACC;IACrC,MAAMC,eAAeD,cAAcX,MAAM,EAAEa,YAAYjB,eAAeiB,QAAQ;IAC9E,MAAMC,iBAAiBH,cAAcI,yBAAyB,IAAI;IAElE,OAAO;QACLC,SAAS,OAAOC;YACd,IAAI;gBACF,MAAMC,OAAO,AAAC,MAAMD,IAAIE,IAAI,QAAS,CAAC;gBACtC,MAAM,EAAEC,MAAM,EAAEf,QAAQ,EAAEgB,KAAK,EAAEC,SAAS,EAAEC,iBAAiB,EAAEC,UAAU,EAAE,GAAGN;gBAE9E,IAAI,CAACE,UAAU,CAACC,OAAO;oBACrB,OAAOI,SAASN,IAAI,CAClB;wBAAEO,OAAO;wBAA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D,OAAO,GAAG;gBACzD,OAAO3D,SAASN,IAAI,CAClB;oBACEO,OAAO;oBACP0D;oBACAzD,SAAS;gBACX,GACA;oBAAEC,QAAQ;gBAAI;YAElB;QACF;QACA0D,QAAQ;QACRC,MAAM3E;IACR;AACF,EAAC"}
@@ -0,0 +1,3 @@
1
+ import type { Endpoint } from 'payload';
2
+ import type { DpoPluginConfig } from '../types.js';
3
+ export declare const createNotifyEndpoint: (pluginOptions: DpoPluginConfig) => Endpoint;
@@ -0,0 +1,63 @@
1
+ import { DEFAULT_ROUTES, STATUS_MAP } from '../lib/constants.js';
2
+ export const createNotifyEndpoint = (pluginOptions)=>{
3
+ const notifyPath = pluginOptions.routes?.notify ?? DEFAULT_ROUTES.notify;
4
+ const collectionSlug = pluginOptions.transactionCollectionSlug ?? 'dpo-transactions';
5
+ return {
6
+ handler: async (req)=>{
7
+ try {
8
+ const rawText = await req.text?.() ?? '';
9
+ const body = {};
10
+ for (const pair of rawText.split('&')){
11
+ const eqIdx = pair.indexOf('=');
12
+ if (eqIdx === -1) continue;
13
+ body[decodeURIComponent(pair.slice(0, eqIdx))] = decodeURIComponent(pair.slice(eqIdx + 1));
14
+ }
15
+ const payRequestId = body.PAY_REQUEST_ID || body.payRequestId;
16
+ const transactionStatus = body.TRANSACTION_STATUS || body.transactionStatus;
17
+ if (!payRequestId || !transactionStatus) {
18
+ return Response.json({
19
+ error: 'Invalid notification data',
20
+ receivedText: rawText.slice(0, 500),
21
+ receivedKeys: Object.keys(body)
22
+ }, {
23
+ status: 400
24
+ });
25
+ }
26
+ if (req.payload) {
27
+ const existing = await req.payload.find({
28
+ collection: collectionSlug,
29
+ limit: 1,
30
+ where: {
31
+ payRequestId: {
32
+ equals: payRequestId
33
+ }
34
+ }
35
+ });
36
+ if (existing.docs.length > 0) {
37
+ await req.payload.update({
38
+ id: existing.docs[0].id,
39
+ collection: collectionSlug,
40
+ data: {
41
+ rawResponse: body,
42
+ statusMessage: STATUS_MAP[transactionStatus] || 'Unknown',
43
+ transactionStatus
44
+ }
45
+ });
46
+ }
47
+ }
48
+ return new Response('OK', {
49
+ status: 200
50
+ });
51
+ } catch (error) {
52
+ const message = error instanceof Error ? error.message : 'Unknown error';
53
+ return new Response(`Error processing notification: ${message}`, {
54
+ status: 400
55
+ });
56
+ }
57
+ },
58
+ method: 'post',
59
+ path: notifyPath
60
+ };
61
+ };
62
+
63
+ //# sourceMappingURL=notify.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/endpoints/notify.ts"],"sourcesContent":["import type { Endpoint, PayloadRequest } from 'payload'\n\nimport type { DpoPluginConfig } from '../types.js'\n\nimport { DEFAULT_ROUTES, STATUS_MAP } from '../lib/constants.js'\n\nexport const createNotifyEndpoint = (pluginOptions: DpoPluginConfig): Endpoint => {\n const notifyPath = pluginOptions.routes?.notify ?? DEFAULT_ROUTES.notify\n const collectionSlug = pluginOptions.transactionCollectionSlug ?? 'dpo-transactions'\n\n return {\n handler: async (req: PayloadRequest) => {\n try {\n const rawText = (await req.text?.()) ?? ''\n\n const body: Record<string, string> = {}\n for (const pair of rawText.split('&')) {\n const eqIdx = pair.indexOf('=')\n if (eqIdx === -1) continue\n body[decodeURIComponent(pair.slice(0, eqIdx))] = decodeURIComponent(pair.slice(eqIdx + 1))\n }\n\n const payRequestId = body.PAY_REQUEST_ID || body.payRequestId\n const transactionStatus = body.TRANSACTION_STATUS || body.transactionStatus\n\n if (!payRequestId || !transactionStatus) {\n return Response.json(\n {\n error: 'Invalid notification data',\n receivedText: rawText.slice(0, 500),\n receivedKeys: Object.keys(body),\n },\n { status: 400 },\n )\n }\n\n if (req.payload) {\n const existing = await req.payload.find({\n collection: collectionSlug,\n limit: 1,\n where: { payRequestId: { equals: payRequestId } },\n })\n\n if (existing.docs.length > 0) {\n await req.payload.update({\n id: existing.docs[0].id,\n collection: collectionSlug,\n data: {\n rawResponse: body,\n statusMessage: STATUS_MAP[transactionStatus] || 'Unknown',\n transactionStatus,\n },\n })\n }\n }\n\n return new Response('OK', { status: 200 })\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : 'Unknown error'\n return new Response(`Error processing notification: ${message}`, {\n status: 400,\n })\n }\n },\n method: 'post',\n path: notifyPath,\n }\n}\n"],"names":["DEFAULT_ROUTES","STATUS_MAP","createNotifyEndpoint","pluginOptions","notifyPath","routes","notify","collectionSlug","transactionCollectionSlug","handler","req","rawText","text","body","pair","split","eqIdx","indexOf","decodeURIComponent","slice","payRequestId","PAY_REQUEST_ID","transactionStatus","TRANSACTION_STATUS","Response","json","error","receivedText","receivedKeys","Object","keys","status","payload","existing","find","collection","limit","where","equals","docs","length","update","id","data","rawResponse","statusMessage","message","Error","method","path"],"mappings":"AAIA,SAASA,cAAc,EAAEC,UAAU,QAAQ,sBAAqB;AAEhE,OAAO,MAAMC,uBAAuB,CAACC;IACnC,MAAMC,aAAaD,cAAcE,MAAM,EAAEC,UAAUN,eAAeM,MAAM;IACxE,MAAMC,iBAAiBJ,cAAcK,yBAAyB,IAAI;IAElE,OAAO;QACLC,SAAS,OAAOC;YACd,IAAI;gBACF,MAAMC,UAAU,AAAC,MAAMD,IAAIE,IAAI,QAAS;gBAExC,MAAMC,OAA+B,CAAC;gBACtC,KAAK,MAAMC,QAAQH,QAAQI,KAAK,CAAC,KAAM;oBACrC,MAAMC,QAAQF,KAAKG,OAAO,CAAC;oBAC3B,IAAID,UAAU,CAAC,GAAG;oBAClBH,IAAI,CAACK,mBAAmBJ,KAAKK,KAAK,CAAC,GAAGH,QAAQ,GAAGE,mBAAmBJ,KAAKK,KAAK,CAACH,QAAQ;gBACzF;gBAEA,MAAMI,eAAeP,KAAKQ,cAAc,IAAIR,KAAKO,YAAY;gBAC7D,MAAME,oBAAoBT,KAAKU,kBAAkB,IAAIV,KAAKS,iBAAiB;gBAE3E,IAAI,CAACF,gBAAgB,CAACE,mBAAmB;oBACvC,OAAOE,SAASC,IAAI,CAClB;wBACEC,OAAO;wBACPC,cAAchB,QAAQQ,KAAK,CAAC,GAAG;wBAC/BS,cAAcC,OAAOC,IAAI,CAACjB;oBAC5B,GACA;wBAAEkB,QAAQ;oBAAI;gBAElB;gBAEA,IAAIrB,IAAIsB,OAAO,EAAE;oBACf,MAAMC,WAAW,MAAMvB,IAAIsB,OAAO,CAACE,IAAI,CAAC;wBACtCC,YAAY5B;wBACZ6B,OAAO;wBACPC,OAAO;4BAAEjB,cAAc;gCAAEkB,QAAQlB;4BAAa;wBAAE;oBAClD;oBAEA,IAAIa,SAASM,IAAI,CAACC,MAAM,GAAG,GAAG;wBAC5B,MAAM9B,IAAIsB,OAAO,CAACS,MAAM,CAAC;4BACvBC,IAAIT,SAASM,IAAI,CAAC,EAAE,CAACG,EAAE;4BACvBP,YAAY5B;4BACZoC,MAAM;gCACJC,aAAa/B;gCACbgC,eAAe5C,UAAU,CAACqB,kBAAkB,IAAI;gCAChDA;4BACF;wBACF;oBACF;gBACF;gBAEA,OAAO,IAAIE,SAAS,MAAM;oBAAEO,QAAQ;gBAAI;YAC1C,EAAE,OAAOL,OAAgB;gBACvB,MAAMoB,UAAUpB,iBAAiBqB,QAAQrB,MAAMoB,OAAO,GAAG;gBACzD,OAAO,IAAItB,SAAS,CAAC,+BAA+B,EAAEsB,SAAS,EAAE;oBAC/Df,QAAQ;gBACV;YACF;QACF;QACAiB,QAAQ;QACRC,MAAM7C;IACR;AACF,EAAC"}
@@ -0,0 +1,3 @@
1
+ import type { Endpoint } from 'payload';
2
+ import type { DpoPluginConfig } from '../types.js';
3
+ export declare const createReturnEndpoint: (pluginOptions: DpoPluginConfig) => Endpoint[];