@singularity-payments/nuxt 0.1.0-alpha.1

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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,67 @@
1
+ import { EventHandler } from 'h3';
2
+ import { MpesaClient, MpesaConfig, MpesaClientOptions } from '@singularity-payments/core';
3
+ export { C2BCallback, C2BRegisterRequest, C2BRegisterResponse, MpesaClient, MpesaClientOptions, MpesaConfig, ParsedC2BCallback, ParsedCallbackData, STKCallback, STKPushRequest, STKPushResponse, TransactionStatusRequest, TransactionStatusResponse } from '@singularity-payments/core';
4
+
5
+ type MpesaEventHandler = EventHandler;
6
+ interface MpesaEventHandlers {
7
+ stkCallback: MpesaEventHandler;
8
+ c2bValidation: MpesaEventHandler;
9
+ c2bConfirmation: MpesaEventHandler;
10
+ b2cResult: MpesaEventHandler;
11
+ b2cTimeout: MpesaEventHandler;
12
+ catchAll: MpesaEventHandler;
13
+ }
14
+
15
+ /**
16
+ * Create Nuxt/Nitro event handlers for M-Pesa callbacks and client-side API requests
17
+ */
18
+ declare function createMpesaHandlers(client: MpesaClient): MpesaEventHandlers;
19
+
20
+ /**
21
+ * Create M-Pesa instance for Nuxt
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * // utils/mpesa.ts
26
+ * import { createMpesa } from "@singularity-payments/nuxt";
27
+ *
28
+ * export const mpesa = createMpesa({
29
+ * consumerKey: process.env.MPESA_CONSUMER_KEY!,
30
+ * consumerSecret: process.env.MPESA_CONSUMER_SECRET!,
31
+ * passkey: process.env.MPESA_PASSKEY!,
32
+ * shortcode: process.env.MPESA_SHORTCODE!,
33
+ * environment: "sandbox",
34
+ * callbackUrl: `${process.env.NUXT_PUBLIC_APP_URL}/api/mpesa/callback`
35
+ * }, {
36
+ * callbackOptions: {
37
+ * onSuccess: async (data) => {
38
+ * console.log("Payment successful:", data);
39
+ * // Save to database
40
+ * },
41
+ * onFailure: async (data) => {
42
+ * console.log("Payment failed:", data);
43
+ * }
44
+ * }
45
+ * });
46
+ * ```
47
+ *
48
+ * @example
49
+ * ```typescript
50
+ * // server/api/mpesa/[...mpesa].ts
51
+ * import { mpesa } from "~/utils/mpesa";
52
+ *
53
+ * export default mpesa.handlers.catchAll;
54
+ * ```
55
+ */
56
+ declare function createMpesa(config: MpesaConfig, options?: MpesaClientOptions): {
57
+ /**
58
+ * M-Pesa client instance for making API calls
59
+ */
60
+ client: MpesaClient;
61
+ /**
62
+ * Pre-configured Nuxt event handlers for M-Pesa callbacks
63
+ */
64
+ handlers: MpesaEventHandlers;
65
+ };
66
+
67
+ export { type MpesaEventHandler, type MpesaEventHandlers, createMpesa, createMpesaHandlers };
@@ -0,0 +1,67 @@
1
+ import { EventHandler } from 'h3';
2
+ import { MpesaClient, MpesaConfig, MpesaClientOptions } from '@singularity-payments/core';
3
+ export { C2BCallback, C2BRegisterRequest, C2BRegisterResponse, MpesaClient, MpesaClientOptions, MpesaConfig, ParsedC2BCallback, ParsedCallbackData, STKCallback, STKPushRequest, STKPushResponse, TransactionStatusRequest, TransactionStatusResponse } from '@singularity-payments/core';
4
+
5
+ type MpesaEventHandler = EventHandler;
6
+ interface MpesaEventHandlers {
7
+ stkCallback: MpesaEventHandler;
8
+ c2bValidation: MpesaEventHandler;
9
+ c2bConfirmation: MpesaEventHandler;
10
+ b2cResult: MpesaEventHandler;
11
+ b2cTimeout: MpesaEventHandler;
12
+ catchAll: MpesaEventHandler;
13
+ }
14
+
15
+ /**
16
+ * Create Nuxt/Nitro event handlers for M-Pesa callbacks and client-side API requests
17
+ */
18
+ declare function createMpesaHandlers(client: MpesaClient): MpesaEventHandlers;
19
+
20
+ /**
21
+ * Create M-Pesa instance for Nuxt
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * // utils/mpesa.ts
26
+ * import { createMpesa } from "@singularity-payments/nuxt";
27
+ *
28
+ * export const mpesa = createMpesa({
29
+ * consumerKey: process.env.MPESA_CONSUMER_KEY!,
30
+ * consumerSecret: process.env.MPESA_CONSUMER_SECRET!,
31
+ * passkey: process.env.MPESA_PASSKEY!,
32
+ * shortcode: process.env.MPESA_SHORTCODE!,
33
+ * environment: "sandbox",
34
+ * callbackUrl: `${process.env.NUXT_PUBLIC_APP_URL}/api/mpesa/callback`
35
+ * }, {
36
+ * callbackOptions: {
37
+ * onSuccess: async (data) => {
38
+ * console.log("Payment successful:", data);
39
+ * // Save to database
40
+ * },
41
+ * onFailure: async (data) => {
42
+ * console.log("Payment failed:", data);
43
+ * }
44
+ * }
45
+ * });
46
+ * ```
47
+ *
48
+ * @example
49
+ * ```typescript
50
+ * // server/api/mpesa/[...mpesa].ts
51
+ * import { mpesa } from "~/utils/mpesa";
52
+ *
53
+ * export default mpesa.handlers.catchAll;
54
+ * ```
55
+ */
56
+ declare function createMpesa(config: MpesaConfig, options?: MpesaClientOptions): {
57
+ /**
58
+ * M-Pesa client instance for making API calls
59
+ */
60
+ client: MpesaClient;
61
+ /**
62
+ * Pre-configured Nuxt event handlers for M-Pesa callbacks
63
+ */
64
+ handlers: MpesaEventHandlers;
65
+ };
66
+
67
+ export { type MpesaEventHandler, type MpesaEventHandlers, createMpesa, createMpesaHandlers };
package/dist/index.js ADDED
@@ -0,0 +1,468 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ MpesaClient: () => import_core2.MpesaClient,
24
+ createMpesa: () => createMpesa,
25
+ createMpesaHandlers: () => createMpesaHandlers
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+ var import_core = require("@singularity-payments/core");
29
+
30
+ // src/handlers.ts
31
+ var import_h3 = require("h3");
32
+ function createMpesaHandlers(client) {
33
+ const handlers = {
34
+ /**
35
+ * STK Push callback handler
36
+ * Handles callbacks from M-Pesa after STK Push requests
37
+ */
38
+ stkCallback: (0, import_h3.defineEventHandler)(async (event) => {
39
+ try {
40
+ const body = await (0, import_h3.readBody)(event);
41
+ const ipAddress = (0, import_h3.getRequestHeader)(event, "x-forwarded-for") || (0, import_h3.getRequestHeader)(event, "x-real-ip") || void 0;
42
+ const response = await client.handleSTKCallback(body, ipAddress);
43
+ return response;
44
+ } catch (error) {
45
+ console.error("STK Callback error:", error);
46
+ return {
47
+ ResultCode: 1,
48
+ ResultDesc: "Internal error processing callback"
49
+ };
50
+ }
51
+ }),
52
+ /**
53
+ * C2B validation handler
54
+ * Validates C2B transactions before they are processed
55
+ */
56
+ c2bValidation: (0, import_h3.defineEventHandler)(async (event) => {
57
+ try {
58
+ const body = await (0, import_h3.readBody)(event);
59
+ const response = await client.handleC2BValidation(body);
60
+ return response;
61
+ } catch (error) {
62
+ console.error("C2B Validation error:", error);
63
+ return {
64
+ ResultCode: 1,
65
+ ResultDesc: "Validation failed"
66
+ };
67
+ }
68
+ }),
69
+ /**
70
+ * C2B confirmation handler
71
+ * Confirms C2B transactions after they are processed
72
+ */
73
+ c2bConfirmation: (0, import_h3.defineEventHandler)(async (event) => {
74
+ try {
75
+ const body = await (0, import_h3.readBody)(event);
76
+ const response = await client.handleC2BConfirmation(body);
77
+ return response;
78
+ } catch (error) {
79
+ console.error("C2B Confirmation error:", error);
80
+ return {
81
+ ResultCode: 1,
82
+ ResultDesc: "Processing failed"
83
+ };
84
+ }
85
+ }),
86
+ /**
87
+ * B2C result handler
88
+ * Handles callbacks from M-Pesa after B2C requests
89
+ */
90
+ b2cResult: (0, import_h3.defineEventHandler)(async (event) => {
91
+ try {
92
+ const body = await (0, import_h3.readBody)(event);
93
+ const parsed = client.getCallbackHandler().parseB2CCallback(body);
94
+ console.log("B2C Result:", parsed);
95
+ return {
96
+ ResultCode: 0,
97
+ ResultDesc: "Accepted"
98
+ };
99
+ } catch (error) {
100
+ console.error("B2C Result error:", error);
101
+ return {
102
+ ResultCode: 1,
103
+ ResultDesc: "Processing failed"
104
+ };
105
+ }
106
+ }),
107
+ /**
108
+ * B2C timeout handler
109
+ * Handles timeout notifications from M-Pesa for B2C requests
110
+ */
111
+ b2cTimeout: (0, import_h3.defineEventHandler)(async (event) => {
112
+ try {
113
+ const body = await (0, import_h3.readBody)(event);
114
+ console.log("B2C Timeout:", body);
115
+ return {
116
+ ResultCode: 0,
117
+ ResultDesc: "Timeout received"
118
+ };
119
+ } catch (error) {
120
+ console.error("B2C Timeout error:", error);
121
+ return {
122
+ ResultCode: 1,
123
+ ResultDesc: "Processing failed"
124
+ };
125
+ }
126
+ }),
127
+ /**
128
+ * Catch-all handler for all M-Pesa webhooks and client-side API requests
129
+ * Routes based on URL path segment
130
+ *
131
+ * Usage: server/api/mpesa/[...mpesa].ts
132
+ * export default mpesa.handlers.catchAll;
133
+ *
134
+ * Supported endpoints:
135
+ *
136
+ * WEBHOOKS (from M-Pesa):
137
+ * - /api/mpesa/callback or /api/mpesa/stk-callback - STK Push callbacks
138
+ * - /api/mpesa/validation or /api/mpesa/c2b-validation - C2B validation
139
+ * - /api/mpesa/confirmation or /api/mpesa/c2b-confirmation - C2B confirmation
140
+ * - /api/mpesa/b2c-result - B2C result callback
141
+ * - /api/mpesa/b2c-timeout - B2C timeout callback
142
+ * - /api/mpesa/b2b-result - B2B result callback
143
+ * - /api/mpesa/b2b-timeout - B2B timeout callback
144
+ * - /api/mpesa/balance-result - Account balance result
145
+ * - /api/mpesa/balance-timeout - Account balance timeout
146
+ * - /api/mpesa/reversal-result - Reversal result
147
+ * - /api/mpesa/reversal-timeout - Reversal timeout
148
+ * - /api/mpesa/status-result - Transaction status result
149
+ * - /api/mpesa/status-timeout - Transaction status timeout
150
+ *
151
+ * CLIENT APIs (from the frontend):
152
+ * - /api/mpesa/stk-push - Initiate STK Push request
153
+ * - /api/mpesa/stk-query - Query STK Push status
154
+ * - /api/mpesa/b2c - Initiate B2C payment
155
+ * - /api/mpesa/b2b - Initiate B2B payment
156
+ * - /api/mpesa/balance - Query account balance
157
+ * - /api/mpesa/transaction-status - Query transaction status
158
+ * - /api/mpesa/reversal - Reverse a transaction
159
+ * - /api/mpesa/register-c2b - Register C2B URLs
160
+ * - /api/mpesa/generate-qr - Generate dynamic QR code
161
+ */
162
+ catchAll: (0, import_h3.defineEventHandler)(async (event) => {
163
+ const url = (0, import_h3.getRequestURL)(event);
164
+ const pathname = url.pathname;
165
+ const segments = pathname.split("/").filter(Boolean);
166
+ const lastSegment = segments[segments.length - 1];
167
+ try {
168
+ if (lastSegment === "callback" || lastSegment === "stk-callback") {
169
+ const body = await (0, import_h3.readBody)(event);
170
+ const ipAddress = (0, import_h3.getRequestHeader)(event, "x-forwarded-for") || (0, import_h3.getRequestHeader)(event, "x-real-ip") || void 0;
171
+ const response = await client.handleSTKCallback(body, ipAddress);
172
+ return response;
173
+ }
174
+ if (lastSegment === "validation" || lastSegment === "c2b-validation") {
175
+ const body = await (0, import_h3.readBody)(event);
176
+ const response = await client.handleC2BValidation(body);
177
+ return response;
178
+ }
179
+ if (lastSegment === "confirmation" || lastSegment === "c2b-confirmation") {
180
+ const body = await (0, import_h3.readBody)(event);
181
+ const response = await client.handleC2BConfirmation(body);
182
+ return response;
183
+ }
184
+ if (lastSegment === "b2c-result") {
185
+ const body = await (0, import_h3.readBody)(event);
186
+ const parsed = client.getCallbackHandler().parseB2CCallback(body);
187
+ console.log("B2C Result:", parsed);
188
+ return { ResultCode: 0, ResultDesc: "Accepted" };
189
+ }
190
+ if (lastSegment === "b2c-timeout") {
191
+ const body = await (0, import_h3.readBody)(event);
192
+ console.log("B2C Timeout:", body);
193
+ return { ResultCode: 0, ResultDesc: "Timeout received" };
194
+ }
195
+ if (lastSegment === "b2b-result") {
196
+ const body = await (0, import_h3.readBody)(event);
197
+ const parsed = client.getCallbackHandler().parseB2BCallback(body);
198
+ console.log("B2B Result:", parsed);
199
+ return { ResultCode: 0, ResultDesc: "Accepted" };
200
+ }
201
+ if (lastSegment === "b2b-timeout") {
202
+ const body = await (0, import_h3.readBody)(event);
203
+ console.log("B2B Timeout:", body);
204
+ return { ResultCode: 0, ResultDesc: "Timeout received" };
205
+ }
206
+ if (lastSegment === "balance-result") {
207
+ const body = await (0, import_h3.readBody)(event);
208
+ const parsed = client.getCallbackHandler().parseAccountBalanceCallback(body);
209
+ console.log("Balance Result:", parsed);
210
+ return { ResultCode: 0, ResultDesc: "Accepted" };
211
+ }
212
+ if (lastSegment === "balance-timeout") {
213
+ const body = await (0, import_h3.readBody)(event);
214
+ console.log("Balance Timeout:", body);
215
+ return { ResultCode: 0, ResultDesc: "Timeout received" };
216
+ }
217
+ if (lastSegment === "status-result") {
218
+ const body = await (0, import_h3.readBody)(event);
219
+ const parsed = client.getCallbackHandler().parseTransactionStatusCallback(body);
220
+ console.log("Status Result:", parsed);
221
+ return { ResultCode: 0, ResultDesc: "Accepted" };
222
+ }
223
+ if (lastSegment === "status-timeout") {
224
+ const body = await (0, import_h3.readBody)(event);
225
+ console.log("Status Timeout:", body);
226
+ return { ResultCode: 0, ResultDesc: "Timeout received" };
227
+ }
228
+ if (lastSegment === "reversal-result") {
229
+ const body = await (0, import_h3.readBody)(event);
230
+ const parsed = client.getCallbackHandler().parseReversalCallback(body);
231
+ console.log("Reversal Result:", parsed);
232
+ return { ResultCode: 0, ResultDesc: "Accepted" };
233
+ }
234
+ if (lastSegment === "reversal-timeout") {
235
+ const body = await (0, import_h3.readBody)(event);
236
+ console.log("Reversal Timeout:", body);
237
+ return { ResultCode: 0, ResultDesc: "Timeout received" };
238
+ }
239
+ if (lastSegment === "stk-push") {
240
+ const body = await (0, import_h3.readBody)(event);
241
+ const {
242
+ amount,
243
+ phoneNumber,
244
+ accountReference,
245
+ transactionDesc,
246
+ callbackUrl
247
+ } = body;
248
+ if (!amount || !phoneNumber) {
249
+ throw (0, import_h3.createError)({
250
+ statusCode: 400,
251
+ message: "Amount and phone number are required"
252
+ });
253
+ }
254
+ const response = await client.stkPush({
255
+ amount: Number(amount),
256
+ phoneNumber: String(phoneNumber),
257
+ accountReference: accountReference || "Payment",
258
+ transactionDesc: transactionDesc || "Payment",
259
+ callbackUrl
260
+ });
261
+ return response;
262
+ }
263
+ if (lastSegment === "stk-query") {
264
+ const body = await (0, import_h3.readBody)(event);
265
+ const { CheckoutRequestID } = body;
266
+ if (!CheckoutRequestID) {
267
+ throw (0, import_h3.createError)({
268
+ statusCode: 400,
269
+ message: "CheckoutRequestID is required"
270
+ });
271
+ }
272
+ const response = await client.stkQuery({ CheckoutRequestID });
273
+ return response;
274
+ }
275
+ if (lastSegment === "b2c") {
276
+ const body = await (0, import_h3.readBody)(event);
277
+ const {
278
+ amount,
279
+ phoneNumber,
280
+ commandID,
281
+ remarks,
282
+ occasion,
283
+ resultUrl,
284
+ timeoutUrl
285
+ } = body;
286
+ if (!amount || !phoneNumber || !commandID) {
287
+ throw (0, import_h3.createError)({
288
+ statusCode: 400,
289
+ message: "Amount, phone number, and command ID are required"
290
+ });
291
+ }
292
+ const response = await client.b2c({
293
+ amount: Number(amount),
294
+ phoneNumber: String(phoneNumber),
295
+ commandID,
296
+ remarks: remarks || "Payment",
297
+ occasion,
298
+ resultUrl,
299
+ timeoutUrl
300
+ });
301
+ return response;
302
+ }
303
+ if (lastSegment === "b2b") {
304
+ const body = await (0, import_h3.readBody)(event);
305
+ const {
306
+ amount,
307
+ partyB,
308
+ commandID,
309
+ senderIdentifierType,
310
+ receiverIdentifierType,
311
+ accountReference,
312
+ remarks,
313
+ resultUrl,
314
+ timeoutUrl
315
+ } = body;
316
+ console.log("B2B Request Parameters:", {
317
+ amount,
318
+ partyB,
319
+ commandID,
320
+ senderIdentifierType,
321
+ receiverIdentifierType,
322
+ accountReference,
323
+ remarks
324
+ });
325
+ if (!amount || !partyB || !commandID || !accountReference) {
326
+ throw (0, import_h3.createError)({
327
+ statusCode: 400,
328
+ message: "Amount, partyB, commandID, and account reference are required"
329
+ });
330
+ }
331
+ const response = await client.b2b({
332
+ amount: Number(amount),
333
+ partyB: String(partyB),
334
+ commandID,
335
+ senderIdentifierType,
336
+ receiverIdentifierType,
337
+ accountReference: String(accountReference),
338
+ remarks: remarks || "Payment",
339
+ resultUrl,
340
+ timeoutUrl
341
+ });
342
+ console.log("B2B Response:", response);
343
+ return response;
344
+ }
345
+ if (lastSegment === "balance") {
346
+ const body = await (0, import_h3.readBody)(event);
347
+ const response = await client.accountBalance(body);
348
+ return response;
349
+ }
350
+ if (lastSegment === "transaction-status") {
351
+ const body = await (0, import_h3.readBody)(event);
352
+ const { transactionID } = body;
353
+ if (!transactionID) {
354
+ throw (0, import_h3.createError)({
355
+ statusCode: 400,
356
+ message: "Transaction ID is required"
357
+ });
358
+ }
359
+ const response = await client.transactionStatus(body);
360
+ return response;
361
+ }
362
+ if (lastSegment === "reversal") {
363
+ const body = await (0, import_h3.readBody)(event);
364
+ const { transactionID, amount } = body;
365
+ if (!transactionID || !amount) {
366
+ throw (0, import_h3.createError)({
367
+ statusCode: 400,
368
+ message: "Transaction ID and amount are required"
369
+ });
370
+ }
371
+ const response = await client.reversal(body);
372
+ return response;
373
+ }
374
+ if (lastSegment === "register-c2b") {
375
+ const body = await (0, import_h3.readBody)(event);
376
+ const { shortCode, responseType, confirmationURL, validationURL } = body;
377
+ if (!confirmationURL || !validationURL) {
378
+ throw (0, import_h3.createError)({
379
+ statusCode: 400,
380
+ message: "Confirmation URL and validation URL are required"
381
+ });
382
+ }
383
+ const response = await client.registerC2BUrl({
384
+ shortCode,
385
+ responseType,
386
+ confirmationURL,
387
+ validationURL
388
+ });
389
+ return response;
390
+ }
391
+ if (lastSegment === "generate-qr") {
392
+ const body = await (0, import_h3.readBody)(event);
393
+ const {
394
+ merchantName,
395
+ refNo,
396
+ amount,
397
+ transactionType,
398
+ creditPartyIdentifier,
399
+ size
400
+ } = body;
401
+ if (!merchantName || !refNo || !amount || !transactionType || !creditPartyIdentifier) {
402
+ throw (0, import_h3.createError)({
403
+ statusCode: 400,
404
+ message: "Merchant name, reference number, amount, transaction type, and credit party identifier are required",
405
+ data: { received: body }
406
+ });
407
+ }
408
+ let qrSize = void 0;
409
+ if (size) {
410
+ if (size !== "500" && size !== "300") {
411
+ throw (0, import_h3.createError)({
412
+ statusCode: 400,
413
+ message: "Size must be either '300' or '500'"
414
+ });
415
+ }
416
+ qrSize = size;
417
+ }
418
+ const response = await client.generateDynamicQR({
419
+ merchantName,
420
+ refNo,
421
+ amount: Number(amount),
422
+ transactionType,
423
+ creditPartyIdentifier,
424
+ size: qrSize
425
+ });
426
+ return response;
427
+ }
428
+ throw (0, import_h3.createError)({
429
+ statusCode: 404,
430
+ message: `Unknown endpoint: ${lastSegment}`
431
+ });
432
+ } catch (error) {
433
+ console.error(`M-Pesa ${lastSegment} error:`, error);
434
+ if (error.statusCode) {
435
+ throw error;
436
+ }
437
+ throw (0, import_h3.createError)({
438
+ statusCode: 500,
439
+ message: error.message || "Request failed"
440
+ });
441
+ }
442
+ })
443
+ };
444
+ return handlers;
445
+ }
446
+
447
+ // src/index.ts
448
+ var import_core2 = require("@singularity-payments/core");
449
+ function createMpesa(config, options) {
450
+ const client = new import_core.MpesaClient(config, options);
451
+ const handlers = createMpesaHandlers(client);
452
+ return {
453
+ /**
454
+ * M-Pesa client instance for making API calls
455
+ */
456
+ client,
457
+ /**
458
+ * Pre-configured Nuxt event handlers for M-Pesa callbacks
459
+ */
460
+ handlers
461
+ };
462
+ }
463
+ // Annotate the CommonJS export names for ESM import in node:
464
+ 0 && (module.exports = {
465
+ MpesaClient,
466
+ createMpesa,
467
+ createMpesaHandlers
468
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,449 @@
1
+ // src/index.ts
2
+ import { MpesaClient } from "@singularity-payments/core";
3
+
4
+ // src/handlers.ts
5
+ import {
6
+ defineEventHandler,
7
+ readBody,
8
+ getRequestURL,
9
+ getRequestHeader,
10
+ createError
11
+ } from "h3";
12
+ function createMpesaHandlers(client) {
13
+ const handlers = {
14
+ /**
15
+ * STK Push callback handler
16
+ * Handles callbacks from M-Pesa after STK Push requests
17
+ */
18
+ stkCallback: defineEventHandler(async (event) => {
19
+ try {
20
+ const body = await readBody(event);
21
+ const ipAddress = getRequestHeader(event, "x-forwarded-for") || getRequestHeader(event, "x-real-ip") || void 0;
22
+ const response = await client.handleSTKCallback(body, ipAddress);
23
+ return response;
24
+ } catch (error) {
25
+ console.error("STK Callback error:", error);
26
+ return {
27
+ ResultCode: 1,
28
+ ResultDesc: "Internal error processing callback"
29
+ };
30
+ }
31
+ }),
32
+ /**
33
+ * C2B validation handler
34
+ * Validates C2B transactions before they are processed
35
+ */
36
+ c2bValidation: defineEventHandler(async (event) => {
37
+ try {
38
+ const body = await readBody(event);
39
+ const response = await client.handleC2BValidation(body);
40
+ return response;
41
+ } catch (error) {
42
+ console.error("C2B Validation error:", error);
43
+ return {
44
+ ResultCode: 1,
45
+ ResultDesc: "Validation failed"
46
+ };
47
+ }
48
+ }),
49
+ /**
50
+ * C2B confirmation handler
51
+ * Confirms C2B transactions after they are processed
52
+ */
53
+ c2bConfirmation: defineEventHandler(async (event) => {
54
+ try {
55
+ const body = await readBody(event);
56
+ const response = await client.handleC2BConfirmation(body);
57
+ return response;
58
+ } catch (error) {
59
+ console.error("C2B Confirmation error:", error);
60
+ return {
61
+ ResultCode: 1,
62
+ ResultDesc: "Processing failed"
63
+ };
64
+ }
65
+ }),
66
+ /**
67
+ * B2C result handler
68
+ * Handles callbacks from M-Pesa after B2C requests
69
+ */
70
+ b2cResult: defineEventHandler(async (event) => {
71
+ try {
72
+ const body = await readBody(event);
73
+ const parsed = client.getCallbackHandler().parseB2CCallback(body);
74
+ console.log("B2C Result:", parsed);
75
+ return {
76
+ ResultCode: 0,
77
+ ResultDesc: "Accepted"
78
+ };
79
+ } catch (error) {
80
+ console.error("B2C Result error:", error);
81
+ return {
82
+ ResultCode: 1,
83
+ ResultDesc: "Processing failed"
84
+ };
85
+ }
86
+ }),
87
+ /**
88
+ * B2C timeout handler
89
+ * Handles timeout notifications from M-Pesa for B2C requests
90
+ */
91
+ b2cTimeout: defineEventHandler(async (event) => {
92
+ try {
93
+ const body = await readBody(event);
94
+ console.log("B2C Timeout:", body);
95
+ return {
96
+ ResultCode: 0,
97
+ ResultDesc: "Timeout received"
98
+ };
99
+ } catch (error) {
100
+ console.error("B2C Timeout error:", error);
101
+ return {
102
+ ResultCode: 1,
103
+ ResultDesc: "Processing failed"
104
+ };
105
+ }
106
+ }),
107
+ /**
108
+ * Catch-all handler for all M-Pesa webhooks and client-side API requests
109
+ * Routes based on URL path segment
110
+ *
111
+ * Usage: server/api/mpesa/[...mpesa].ts
112
+ * export default mpesa.handlers.catchAll;
113
+ *
114
+ * Supported endpoints:
115
+ *
116
+ * WEBHOOKS (from M-Pesa):
117
+ * - /api/mpesa/callback or /api/mpesa/stk-callback - STK Push callbacks
118
+ * - /api/mpesa/validation or /api/mpesa/c2b-validation - C2B validation
119
+ * - /api/mpesa/confirmation or /api/mpesa/c2b-confirmation - C2B confirmation
120
+ * - /api/mpesa/b2c-result - B2C result callback
121
+ * - /api/mpesa/b2c-timeout - B2C timeout callback
122
+ * - /api/mpesa/b2b-result - B2B result callback
123
+ * - /api/mpesa/b2b-timeout - B2B timeout callback
124
+ * - /api/mpesa/balance-result - Account balance result
125
+ * - /api/mpesa/balance-timeout - Account balance timeout
126
+ * - /api/mpesa/reversal-result - Reversal result
127
+ * - /api/mpesa/reversal-timeout - Reversal timeout
128
+ * - /api/mpesa/status-result - Transaction status result
129
+ * - /api/mpesa/status-timeout - Transaction status timeout
130
+ *
131
+ * CLIENT APIs (from the frontend):
132
+ * - /api/mpesa/stk-push - Initiate STK Push request
133
+ * - /api/mpesa/stk-query - Query STK Push status
134
+ * - /api/mpesa/b2c - Initiate B2C payment
135
+ * - /api/mpesa/b2b - Initiate B2B payment
136
+ * - /api/mpesa/balance - Query account balance
137
+ * - /api/mpesa/transaction-status - Query transaction status
138
+ * - /api/mpesa/reversal - Reverse a transaction
139
+ * - /api/mpesa/register-c2b - Register C2B URLs
140
+ * - /api/mpesa/generate-qr - Generate dynamic QR code
141
+ */
142
+ catchAll: defineEventHandler(async (event) => {
143
+ const url = getRequestURL(event);
144
+ const pathname = url.pathname;
145
+ const segments = pathname.split("/").filter(Boolean);
146
+ const lastSegment = segments[segments.length - 1];
147
+ try {
148
+ if (lastSegment === "callback" || lastSegment === "stk-callback") {
149
+ const body = await readBody(event);
150
+ const ipAddress = getRequestHeader(event, "x-forwarded-for") || getRequestHeader(event, "x-real-ip") || void 0;
151
+ const response = await client.handleSTKCallback(body, ipAddress);
152
+ return response;
153
+ }
154
+ if (lastSegment === "validation" || lastSegment === "c2b-validation") {
155
+ const body = await readBody(event);
156
+ const response = await client.handleC2BValidation(body);
157
+ return response;
158
+ }
159
+ if (lastSegment === "confirmation" || lastSegment === "c2b-confirmation") {
160
+ const body = await readBody(event);
161
+ const response = await client.handleC2BConfirmation(body);
162
+ return response;
163
+ }
164
+ if (lastSegment === "b2c-result") {
165
+ const body = await readBody(event);
166
+ const parsed = client.getCallbackHandler().parseB2CCallback(body);
167
+ console.log("B2C Result:", parsed);
168
+ return { ResultCode: 0, ResultDesc: "Accepted" };
169
+ }
170
+ if (lastSegment === "b2c-timeout") {
171
+ const body = await readBody(event);
172
+ console.log("B2C Timeout:", body);
173
+ return { ResultCode: 0, ResultDesc: "Timeout received" };
174
+ }
175
+ if (lastSegment === "b2b-result") {
176
+ const body = await readBody(event);
177
+ const parsed = client.getCallbackHandler().parseB2BCallback(body);
178
+ console.log("B2B Result:", parsed);
179
+ return { ResultCode: 0, ResultDesc: "Accepted" };
180
+ }
181
+ if (lastSegment === "b2b-timeout") {
182
+ const body = await readBody(event);
183
+ console.log("B2B Timeout:", body);
184
+ return { ResultCode: 0, ResultDesc: "Timeout received" };
185
+ }
186
+ if (lastSegment === "balance-result") {
187
+ const body = await readBody(event);
188
+ const parsed = client.getCallbackHandler().parseAccountBalanceCallback(body);
189
+ console.log("Balance Result:", parsed);
190
+ return { ResultCode: 0, ResultDesc: "Accepted" };
191
+ }
192
+ if (lastSegment === "balance-timeout") {
193
+ const body = await readBody(event);
194
+ console.log("Balance Timeout:", body);
195
+ return { ResultCode: 0, ResultDesc: "Timeout received" };
196
+ }
197
+ if (lastSegment === "status-result") {
198
+ const body = await readBody(event);
199
+ const parsed = client.getCallbackHandler().parseTransactionStatusCallback(body);
200
+ console.log("Status Result:", parsed);
201
+ return { ResultCode: 0, ResultDesc: "Accepted" };
202
+ }
203
+ if (lastSegment === "status-timeout") {
204
+ const body = await readBody(event);
205
+ console.log("Status Timeout:", body);
206
+ return { ResultCode: 0, ResultDesc: "Timeout received" };
207
+ }
208
+ if (lastSegment === "reversal-result") {
209
+ const body = await readBody(event);
210
+ const parsed = client.getCallbackHandler().parseReversalCallback(body);
211
+ console.log("Reversal Result:", parsed);
212
+ return { ResultCode: 0, ResultDesc: "Accepted" };
213
+ }
214
+ if (lastSegment === "reversal-timeout") {
215
+ const body = await readBody(event);
216
+ console.log("Reversal Timeout:", body);
217
+ return { ResultCode: 0, ResultDesc: "Timeout received" };
218
+ }
219
+ if (lastSegment === "stk-push") {
220
+ const body = await readBody(event);
221
+ const {
222
+ amount,
223
+ phoneNumber,
224
+ accountReference,
225
+ transactionDesc,
226
+ callbackUrl
227
+ } = body;
228
+ if (!amount || !phoneNumber) {
229
+ throw createError({
230
+ statusCode: 400,
231
+ message: "Amount and phone number are required"
232
+ });
233
+ }
234
+ const response = await client.stkPush({
235
+ amount: Number(amount),
236
+ phoneNumber: String(phoneNumber),
237
+ accountReference: accountReference || "Payment",
238
+ transactionDesc: transactionDesc || "Payment",
239
+ callbackUrl
240
+ });
241
+ return response;
242
+ }
243
+ if (lastSegment === "stk-query") {
244
+ const body = await readBody(event);
245
+ const { CheckoutRequestID } = body;
246
+ if (!CheckoutRequestID) {
247
+ throw createError({
248
+ statusCode: 400,
249
+ message: "CheckoutRequestID is required"
250
+ });
251
+ }
252
+ const response = await client.stkQuery({ CheckoutRequestID });
253
+ return response;
254
+ }
255
+ if (lastSegment === "b2c") {
256
+ const body = await readBody(event);
257
+ const {
258
+ amount,
259
+ phoneNumber,
260
+ commandID,
261
+ remarks,
262
+ occasion,
263
+ resultUrl,
264
+ timeoutUrl
265
+ } = body;
266
+ if (!amount || !phoneNumber || !commandID) {
267
+ throw createError({
268
+ statusCode: 400,
269
+ message: "Amount, phone number, and command ID are required"
270
+ });
271
+ }
272
+ const response = await client.b2c({
273
+ amount: Number(amount),
274
+ phoneNumber: String(phoneNumber),
275
+ commandID,
276
+ remarks: remarks || "Payment",
277
+ occasion,
278
+ resultUrl,
279
+ timeoutUrl
280
+ });
281
+ return response;
282
+ }
283
+ if (lastSegment === "b2b") {
284
+ const body = await readBody(event);
285
+ const {
286
+ amount,
287
+ partyB,
288
+ commandID,
289
+ senderIdentifierType,
290
+ receiverIdentifierType,
291
+ accountReference,
292
+ remarks,
293
+ resultUrl,
294
+ timeoutUrl
295
+ } = body;
296
+ console.log("B2B Request Parameters:", {
297
+ amount,
298
+ partyB,
299
+ commandID,
300
+ senderIdentifierType,
301
+ receiverIdentifierType,
302
+ accountReference,
303
+ remarks
304
+ });
305
+ if (!amount || !partyB || !commandID || !accountReference) {
306
+ throw createError({
307
+ statusCode: 400,
308
+ message: "Amount, partyB, commandID, and account reference are required"
309
+ });
310
+ }
311
+ const response = await client.b2b({
312
+ amount: Number(amount),
313
+ partyB: String(partyB),
314
+ commandID,
315
+ senderIdentifierType,
316
+ receiverIdentifierType,
317
+ accountReference: String(accountReference),
318
+ remarks: remarks || "Payment",
319
+ resultUrl,
320
+ timeoutUrl
321
+ });
322
+ console.log("B2B Response:", response);
323
+ return response;
324
+ }
325
+ if (lastSegment === "balance") {
326
+ const body = await readBody(event);
327
+ const response = await client.accountBalance(body);
328
+ return response;
329
+ }
330
+ if (lastSegment === "transaction-status") {
331
+ const body = await readBody(event);
332
+ const { transactionID } = body;
333
+ if (!transactionID) {
334
+ throw createError({
335
+ statusCode: 400,
336
+ message: "Transaction ID is required"
337
+ });
338
+ }
339
+ const response = await client.transactionStatus(body);
340
+ return response;
341
+ }
342
+ if (lastSegment === "reversal") {
343
+ const body = await readBody(event);
344
+ const { transactionID, amount } = body;
345
+ if (!transactionID || !amount) {
346
+ throw createError({
347
+ statusCode: 400,
348
+ message: "Transaction ID and amount are required"
349
+ });
350
+ }
351
+ const response = await client.reversal(body);
352
+ return response;
353
+ }
354
+ if (lastSegment === "register-c2b") {
355
+ const body = await readBody(event);
356
+ const { shortCode, responseType, confirmationURL, validationURL } = body;
357
+ if (!confirmationURL || !validationURL) {
358
+ throw createError({
359
+ statusCode: 400,
360
+ message: "Confirmation URL and validation URL are required"
361
+ });
362
+ }
363
+ const response = await client.registerC2BUrl({
364
+ shortCode,
365
+ responseType,
366
+ confirmationURL,
367
+ validationURL
368
+ });
369
+ return response;
370
+ }
371
+ if (lastSegment === "generate-qr") {
372
+ const body = await readBody(event);
373
+ const {
374
+ merchantName,
375
+ refNo,
376
+ amount,
377
+ transactionType,
378
+ creditPartyIdentifier,
379
+ size
380
+ } = body;
381
+ if (!merchantName || !refNo || !amount || !transactionType || !creditPartyIdentifier) {
382
+ throw createError({
383
+ statusCode: 400,
384
+ message: "Merchant name, reference number, amount, transaction type, and credit party identifier are required",
385
+ data: { received: body }
386
+ });
387
+ }
388
+ let qrSize = void 0;
389
+ if (size) {
390
+ if (size !== "500" && size !== "300") {
391
+ throw createError({
392
+ statusCode: 400,
393
+ message: "Size must be either '300' or '500'"
394
+ });
395
+ }
396
+ qrSize = size;
397
+ }
398
+ const response = await client.generateDynamicQR({
399
+ merchantName,
400
+ refNo,
401
+ amount: Number(amount),
402
+ transactionType,
403
+ creditPartyIdentifier,
404
+ size: qrSize
405
+ });
406
+ return response;
407
+ }
408
+ throw createError({
409
+ statusCode: 404,
410
+ message: `Unknown endpoint: ${lastSegment}`
411
+ });
412
+ } catch (error) {
413
+ console.error(`M-Pesa ${lastSegment} error:`, error);
414
+ if (error.statusCode) {
415
+ throw error;
416
+ }
417
+ throw createError({
418
+ statusCode: 500,
419
+ message: error.message || "Request failed"
420
+ });
421
+ }
422
+ })
423
+ };
424
+ return handlers;
425
+ }
426
+
427
+ // src/index.ts
428
+ import {
429
+ MpesaClient as MpesaClient2
430
+ } from "@singularity-payments/core";
431
+ function createMpesa(config, options) {
432
+ const client = new MpesaClient(config, options);
433
+ const handlers = createMpesaHandlers(client);
434
+ return {
435
+ /**
436
+ * M-Pesa client instance for making API calls
437
+ */
438
+ client,
439
+ /**
440
+ * Pre-configured Nuxt event handlers for M-Pesa callbacks
441
+ */
442
+ handlers
443
+ };
444
+ }
445
+ export {
446
+ MpesaClient2 as MpesaClient,
447
+ createMpesa,
448
+ createMpesaHandlers
449
+ };
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@singularity-payments/nuxt",
3
+ "version": "0.1.0-alpha.1",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
7
+ "description": "Nuxt integration for M-Pesa payments",
8
+ "main": "./dist/index.js",
9
+ "module": "./dist/index.mjs",
10
+ "types": "./dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "import": "./dist/index.mjs",
15
+ "require": "./dist/index.js",
16
+ "default": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "keywords": [
23
+ "mpesa",
24
+ "nuxt",
25
+ "payments",
26
+ "kenya"
27
+ ],
28
+ "author": "",
29
+ "license": "Apache-2.0",
30
+ "peerDependencies": {
31
+ "h3": ">=1.0.0",
32
+ "nuxt": ">=3.0.0"
33
+ },
34
+ "dependencies": {
35
+ "@singularity-payments/core": "0.1.0-alpha.0"
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "^25.0.3",
39
+ "h3": "^1.13.0",
40
+ "nuxt": "^3.15.3",
41
+ "tsup": "^8.5.1",
42
+ "typescript": "^5.9.3"
43
+ },
44
+ "scripts": {
45
+ "test": "echo \"Error: no test specified\" && exit 1",
46
+ "build": "tsup src/index.ts --format cjs,esm --dts --external h3,nuxt",
47
+ "dev": "tsup src/index.ts --format cjs,esm --dts --external h3,nuxt --watch"
48
+ }
49
+ }