@singularity-payments/sveltekit 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,77 @@
1
+ import { RequestEvent } from '@sveltejs/kit';
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
+ interface RouteHandler {
6
+ POST: (event: RequestEvent) => Promise<Response>;
7
+ }
8
+ interface MpesaRouteHandlers {
9
+ stkCallback: RouteHandler;
10
+ c2bValidation: RouteHandler;
11
+ c2bConfirmation: RouteHandler;
12
+ b2cResult: RouteHandler;
13
+ b2cTimeout: RouteHandler;
14
+ catchAll: RouteHandler;
15
+ }
16
+
17
+ /**
18
+ * Create SvelteKit route handlers for M-Pesa callbacks and client-side API requests
19
+ */
20
+ declare function createMpesaHandlers(client: MpesaClient): MpesaRouteHandlers;
21
+
22
+ /**
23
+ * Create M-Pesa instance for SvelteKit
24
+ *
25
+ * @example
26
+ * ```typescript
27
+ * // lib/mpesa.ts
28
+ * import { createMpesa } from "@singularity-payments/sveltekit";
29
+ *
30
+ * export const mpesa = createMpesa({
31
+ * consumerKey: process.env.MPESA_CONSUMER_KEY!,
32
+ * consumerSecret: process.env.MPESA_CONSUMER_SECRET!,
33
+ * passkey: process.env.MPESA_PASSKEY!,
34
+ * shortcode: process.env.MPESA_SHORTCODE!,
35
+ * environment: "sandbox",
36
+ * callbackUrl: `${process.env.PUBLIC_APP_URL}/api/mpesa/callback`
37
+ * }, {
38
+ * callbackOptions: {
39
+ * onSuccess: async (data) => {
40
+ * console.log("Payment successful:", data);
41
+ * // Save to database
42
+ * },
43
+ * onFailure: async (data) => {
44
+ * console.log("Payment failed:", data);
45
+ * }
46
+ * }
47
+ * });
48
+ * ```
49
+ *
50
+ * @example
51
+ * ```typescript
52
+ * // src/routes/api/mpesa/callback/+server.ts
53
+ * import { mpesa } from "$lib/mpesa";
54
+ *
55
+ * export const POST = mpesa.handlers.stkCallback.POST;
56
+ * ```
57
+ *
58
+ * @example
59
+ * ```typescript
60
+ * // src/routes/api/mpesa/[...path]/+server.ts - Catch-all route
61
+ * import { mpesa } from "$lib/mpesa";
62
+ *
63
+ * export const POST = mpesa.handlers.catchAll.POST;
64
+ * ```
65
+ */
66
+ declare function createMpesa(config: MpesaConfig, options?: MpesaClientOptions): {
67
+ /**
68
+ * M-Pesa client instance for making API calls
69
+ */
70
+ client: MpesaClient;
71
+ /**
72
+ * Pre-configured SvelteKit route handlers for M-Pesa callbacks
73
+ */
74
+ handlers: MpesaRouteHandlers;
75
+ };
76
+
77
+ export { type MpesaRouteHandlers, type RouteHandler, createMpesa, createMpesaHandlers };
@@ -0,0 +1,77 @@
1
+ import { RequestEvent } from '@sveltejs/kit';
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
+ interface RouteHandler {
6
+ POST: (event: RequestEvent) => Promise<Response>;
7
+ }
8
+ interface MpesaRouteHandlers {
9
+ stkCallback: RouteHandler;
10
+ c2bValidation: RouteHandler;
11
+ c2bConfirmation: RouteHandler;
12
+ b2cResult: RouteHandler;
13
+ b2cTimeout: RouteHandler;
14
+ catchAll: RouteHandler;
15
+ }
16
+
17
+ /**
18
+ * Create SvelteKit route handlers for M-Pesa callbacks and client-side API requests
19
+ */
20
+ declare function createMpesaHandlers(client: MpesaClient): MpesaRouteHandlers;
21
+
22
+ /**
23
+ * Create M-Pesa instance for SvelteKit
24
+ *
25
+ * @example
26
+ * ```typescript
27
+ * // lib/mpesa.ts
28
+ * import { createMpesa } from "@singularity-payments/sveltekit";
29
+ *
30
+ * export const mpesa = createMpesa({
31
+ * consumerKey: process.env.MPESA_CONSUMER_KEY!,
32
+ * consumerSecret: process.env.MPESA_CONSUMER_SECRET!,
33
+ * passkey: process.env.MPESA_PASSKEY!,
34
+ * shortcode: process.env.MPESA_SHORTCODE!,
35
+ * environment: "sandbox",
36
+ * callbackUrl: `${process.env.PUBLIC_APP_URL}/api/mpesa/callback`
37
+ * }, {
38
+ * callbackOptions: {
39
+ * onSuccess: async (data) => {
40
+ * console.log("Payment successful:", data);
41
+ * // Save to database
42
+ * },
43
+ * onFailure: async (data) => {
44
+ * console.log("Payment failed:", data);
45
+ * }
46
+ * }
47
+ * });
48
+ * ```
49
+ *
50
+ * @example
51
+ * ```typescript
52
+ * // src/routes/api/mpesa/callback/+server.ts
53
+ * import { mpesa } from "$lib/mpesa";
54
+ *
55
+ * export const POST = mpesa.handlers.stkCallback.POST;
56
+ * ```
57
+ *
58
+ * @example
59
+ * ```typescript
60
+ * // src/routes/api/mpesa/[...path]/+server.ts - Catch-all route
61
+ * import { mpesa } from "$lib/mpesa";
62
+ *
63
+ * export const POST = mpesa.handlers.catchAll.POST;
64
+ * ```
65
+ */
66
+ declare function createMpesa(config: MpesaConfig, options?: MpesaClientOptions): {
67
+ /**
68
+ * M-Pesa client instance for making API calls
69
+ */
70
+ client: MpesaClient;
71
+ /**
72
+ * Pre-configured SvelteKit route handlers for M-Pesa callbacks
73
+ */
74
+ handlers: MpesaRouteHandlers;
75
+ };
76
+
77
+ export { type MpesaRouteHandlers, type RouteHandler, createMpesa, createMpesaHandlers };
package/dist/index.js ADDED
@@ -0,0 +1,509 @@
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_kit = require("@sveltejs/kit");
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: {
39
+ POST: async (event) => {
40
+ try {
41
+ const body = await event.request.json();
42
+ const ipAddress = event.request.headers.get("x-forwarded-for") || event.request.headers.get("x-real-ip") || void 0;
43
+ const response = await client.handleSTKCallback(body, ipAddress);
44
+ return (0, import_kit.json)(response, { status: 200 });
45
+ } catch (error) {
46
+ console.error("STK Callback error:", error);
47
+ return (0, import_kit.json)(
48
+ {
49
+ ResultCode: 1,
50
+ ResultDesc: "Internal error processing callback"
51
+ },
52
+ { status: 200 }
53
+ );
54
+ }
55
+ }
56
+ },
57
+ /**
58
+ * C2B validation handler
59
+ * Validates C2B transactions before they are processed
60
+ */
61
+ c2bValidation: {
62
+ POST: async (event) => {
63
+ try {
64
+ const body = await event.request.json();
65
+ const response = await client.handleC2BValidation(body);
66
+ return (0, import_kit.json)(response, { status: 200 });
67
+ } catch (error) {
68
+ console.error("C2B Validation error:", error);
69
+ return (0, import_kit.json)(
70
+ {
71
+ ResultCode: 1,
72
+ ResultDesc: "Validation failed"
73
+ },
74
+ { status: 200 }
75
+ );
76
+ }
77
+ }
78
+ },
79
+ /**
80
+ * C2B confirmation handler
81
+ * Confirms C2B transactions after they are processed
82
+ */
83
+ c2bConfirmation: {
84
+ POST: async (event) => {
85
+ try {
86
+ const body = await event.request.json();
87
+ const response = await client.handleC2BConfirmation(body);
88
+ return (0, import_kit.json)(response, { status: 200 });
89
+ } catch (error) {
90
+ console.error("C2B Confirmation error:", error);
91
+ return (0, import_kit.json)(
92
+ {
93
+ ResultCode: 1,
94
+ ResultDesc: "Processing failed"
95
+ },
96
+ { status: 200 }
97
+ );
98
+ }
99
+ }
100
+ },
101
+ /**
102
+ * B2C result handler
103
+ * Handles callbacks from M-Pesa after B2C requests
104
+ */
105
+ b2cResult: {
106
+ POST: async (event) => {
107
+ try {
108
+ const body = await event.request.json();
109
+ const parsed = client.getCallbackHandler().parseB2CCallback(body);
110
+ console.log("B2C Result:", parsed);
111
+ return (0, import_kit.json)(
112
+ {
113
+ ResultCode: 0,
114
+ ResultDesc: "Accepted"
115
+ },
116
+ { status: 200 }
117
+ );
118
+ } catch (error) {
119
+ console.error("B2C Result error:", error);
120
+ return (0, import_kit.json)(
121
+ {
122
+ ResultCode: 1,
123
+ ResultDesc: "Processing failed"
124
+ },
125
+ { status: 200 }
126
+ );
127
+ }
128
+ }
129
+ },
130
+ /**
131
+ * B2C timeout handler
132
+ * Handles timeout notifications from M-Pesa for B2C requests
133
+ */
134
+ b2cTimeout: {
135
+ POST: async (event) => {
136
+ try {
137
+ const body = await event.request.json();
138
+ console.log("B2C Timeout:", body);
139
+ return (0, import_kit.json)(
140
+ {
141
+ ResultCode: 0,
142
+ ResultDesc: "Timeout received"
143
+ },
144
+ { status: 200 }
145
+ );
146
+ } catch (error) {
147
+ console.error("B2C Timeout error:", error);
148
+ return (0, import_kit.json)(
149
+ {
150
+ ResultCode: 1,
151
+ ResultDesc: "Processing failed"
152
+ },
153
+ { status: 200 }
154
+ );
155
+ }
156
+ }
157
+ },
158
+ /**
159
+ * Catch-all handler for all M-Pesa webhooks and client-side API requests
160
+ * Routes based on URL path segment
161
+ *
162
+ * Usage: src/routes/api/mpesa/[...path]/+server.ts
163
+ * import { mpesa } from "$lib/mpesa";
164
+ * export const POST = mpesa.handlers.catchAll.POST;
165
+ *
166
+ * Supported endpoints:
167
+ *
168
+ * WEBHOOKS (from M-Pesa):
169
+ * - /api/mpesa/callback or /api/mpesa/stk-callback - STK Push callbacks
170
+ * - /api/mpesa/validation or /api/mpesa/c2b-validation - C2B validation
171
+ * - /api/mpesa/confirmation or /api/mpesa/c2b-confirmation - C2B confirmation
172
+ * - /api/mpesa/b2c-result - B2C result callback
173
+ * - /api/mpesa/b2c-timeout - B2C timeout callback
174
+ * - /api/mpesa/b2b-result - B2B result callback
175
+ * - /api/mpesa/b2b-timeout - B2B timeout callback
176
+ * - /api/mpesa/balance-result - Account balance result
177
+ * - /api/mpesa/balance-timeout - Account balance timeout
178
+ * - /api/mpesa/reversal-result - Reversal result
179
+ * - /api/mpesa/reversal-timeout - Reversal timeout
180
+ * - /api/mpesa/status-result - Transaction status result
181
+ * - /api/mpesa/status-timeout - Transaction status timeout
182
+ *
183
+ * CLIENT APIs (from your frontend):
184
+ * - /api/mpesa/stk-push - Initiate STK Push request
185
+ * - /api/mpesa/stk-query - Query STK Push status
186
+ * - /api/mpesa/b2c - Initiate B2C payment
187
+ * - /api/mpesa/b2b - Initiate B2B payment
188
+ * - /api/mpesa/balance - Query account balance
189
+ * - /api/mpesa/transaction-status - Query transaction status
190
+ * - /api/mpesa/reversal - Reverse a transaction
191
+ * - /api/mpesa/register-c2b - Register C2B URLs
192
+ * - /api/mpesa/generate-qr - Generate dynamic QR code
193
+ */
194
+ catchAll: {
195
+ POST: async (event) => {
196
+ const pathname = event.url.pathname;
197
+ const segments = pathname.split("/").filter(Boolean);
198
+ const lastSegment = segments[segments.length - 1];
199
+ try {
200
+ if (lastSegment === "callback" || lastSegment === "stk-callback") {
201
+ return handlers.stkCallback.POST(event);
202
+ }
203
+ if (lastSegment === "validation" || lastSegment === "c2b-validation") {
204
+ return handlers.c2bValidation.POST(event);
205
+ }
206
+ if (lastSegment === "confirmation" || lastSegment === "c2b-confirmation") {
207
+ return handlers.c2bConfirmation.POST(event);
208
+ }
209
+ if (lastSegment === "b2c-result") {
210
+ return handlers.b2cResult.POST(event);
211
+ }
212
+ if (lastSegment === "b2c-timeout") {
213
+ return handlers.b2cTimeout.POST(event);
214
+ }
215
+ if (lastSegment === "b2b-result") {
216
+ const body = await event.request.json();
217
+ const parsed = client.getCallbackHandler().parseB2BCallback(body);
218
+ console.log("B2B Result:", parsed);
219
+ return (0, import_kit.json)({ ResultCode: 0, ResultDesc: "Accepted" });
220
+ }
221
+ if (lastSegment === "b2b-timeout") {
222
+ const body = await event.request.json();
223
+ console.log("B2B Timeout:", body);
224
+ return (0, import_kit.json)({
225
+ ResultCode: 0,
226
+ ResultDesc: "Timeout received"
227
+ });
228
+ }
229
+ if (lastSegment === "balance-result") {
230
+ const body = await event.request.json();
231
+ const parsed = client.getCallbackHandler().parseAccountBalanceCallback(body);
232
+ console.log("Balance Result:", parsed);
233
+ return (0, import_kit.json)({ ResultCode: 0, ResultDesc: "Accepted" });
234
+ }
235
+ if (lastSegment === "balance-timeout") {
236
+ const body = await event.request.json();
237
+ console.log("Balance Timeout:", body);
238
+ return (0, import_kit.json)({
239
+ ResultCode: 0,
240
+ ResultDesc: "Timeout received"
241
+ });
242
+ }
243
+ if (lastSegment === "status-result") {
244
+ const body = await event.request.json();
245
+ const parsed = client.getCallbackHandler().parseTransactionStatusCallback(body);
246
+ console.log("Status Result:", parsed);
247
+ return (0, import_kit.json)({ ResultCode: 0, ResultDesc: "Accepted" });
248
+ }
249
+ if (lastSegment === "status-timeout") {
250
+ const body = await event.request.json();
251
+ console.log("Status Timeout:", body);
252
+ return (0, import_kit.json)({
253
+ ResultCode: 0,
254
+ ResultDesc: "Timeout received"
255
+ });
256
+ }
257
+ if (lastSegment === "reversal-result") {
258
+ const body = await event.request.json();
259
+ const parsed = client.getCallbackHandler().parseReversalCallback(body);
260
+ console.log("Reversal Result:", parsed);
261
+ return (0, import_kit.json)({ ResultCode: 0, ResultDesc: "Accepted" });
262
+ }
263
+ if (lastSegment === "reversal-timeout") {
264
+ const body = await event.request.json();
265
+ console.log("Reversal Timeout:", body);
266
+ return (0, import_kit.json)({
267
+ ResultCode: 0,
268
+ ResultDesc: "Timeout received"
269
+ });
270
+ }
271
+ if (lastSegment === "stk-push") {
272
+ const body = await event.request.json();
273
+ const {
274
+ amount,
275
+ phoneNumber,
276
+ accountReference,
277
+ transactionDesc,
278
+ callbackUrl
279
+ } = body;
280
+ if (!amount || !phoneNumber) {
281
+ return (0, import_kit.json)(
282
+ { error: "Amount and phone number are required" },
283
+ { status: 400 }
284
+ );
285
+ }
286
+ const response = await client.stkPush({
287
+ amount: Number(amount),
288
+ phoneNumber: String(phoneNumber),
289
+ accountReference: accountReference || "Payment",
290
+ transactionDesc: transactionDesc || "Payment",
291
+ callbackUrl
292
+ });
293
+ return (0, import_kit.json)(response);
294
+ }
295
+ if (lastSegment === "stk-query") {
296
+ const body = await event.request.json();
297
+ const { CheckoutRequestID } = body;
298
+ if (!CheckoutRequestID) {
299
+ return (0, import_kit.json)(
300
+ { error: "CheckoutRequestID is required" },
301
+ { status: 400 }
302
+ );
303
+ }
304
+ const response = await client.stkQuery({ CheckoutRequestID });
305
+ return (0, import_kit.json)(response);
306
+ }
307
+ if (lastSegment === "b2c") {
308
+ const body = await event.request.json();
309
+ const {
310
+ amount,
311
+ phoneNumber,
312
+ commandID,
313
+ remarks,
314
+ occasion,
315
+ resultUrl,
316
+ timeoutUrl
317
+ } = body;
318
+ if (!amount || !phoneNumber || !commandID) {
319
+ return (0, import_kit.json)(
320
+ { error: "Amount, phone number, and command ID are required" },
321
+ { status: 400 }
322
+ );
323
+ }
324
+ const response = await client.b2c({
325
+ amount: Number(amount),
326
+ phoneNumber: String(phoneNumber),
327
+ commandID,
328
+ remarks: remarks || "Payment",
329
+ occasion,
330
+ resultUrl,
331
+ timeoutUrl
332
+ });
333
+ return (0, import_kit.json)(response);
334
+ }
335
+ if (lastSegment === "b2b") {
336
+ const body = await event.request.json();
337
+ const {
338
+ amount,
339
+ partyB,
340
+ commandID,
341
+ senderIdentifierType,
342
+ receiverIdentifierType,
343
+ accountReference,
344
+ remarks,
345
+ resultUrl,
346
+ timeoutUrl
347
+ } = body;
348
+ console.log("B2B Request Parameters:", {
349
+ amount,
350
+ partyB,
351
+ commandID,
352
+ senderIdentifierType,
353
+ receiverIdentifierType,
354
+ accountReference,
355
+ remarks
356
+ });
357
+ if (!amount || !partyB || !commandID || !accountReference) {
358
+ return (0, import_kit.json)(
359
+ {
360
+ error: "Amount, partyB, commandID, and account reference are required"
361
+ },
362
+ { status: 400 }
363
+ );
364
+ }
365
+ const response = await client.b2b({
366
+ amount: Number(amount),
367
+ partyB: String(partyB),
368
+ commandID,
369
+ senderIdentifierType,
370
+ receiverIdentifierType,
371
+ accountReference: String(accountReference),
372
+ remarks: remarks || "Payment",
373
+ resultUrl,
374
+ timeoutUrl
375
+ });
376
+ console.log("B2B Response:", response);
377
+ return (0, import_kit.json)(response);
378
+ }
379
+ if (lastSegment === "balance") {
380
+ const body = await event.request.json();
381
+ const response = await client.accountBalance(
382
+ body
383
+ );
384
+ return (0, import_kit.json)(response);
385
+ }
386
+ if (lastSegment === "transaction-status") {
387
+ const body = await event.request.json();
388
+ const { transactionID } = body;
389
+ if (!transactionID) {
390
+ return (0, import_kit.json)(
391
+ { error: "Transaction ID is required" },
392
+ { status: 400 }
393
+ );
394
+ }
395
+ const response = await client.transactionStatus(body);
396
+ return (0, import_kit.json)(response);
397
+ }
398
+ if (lastSegment === "reversal") {
399
+ const body = await event.request.json();
400
+ const { transactionID, amount } = body;
401
+ if (!transactionID || !amount) {
402
+ return (0, import_kit.json)(
403
+ { error: "Transaction ID and amount are required" },
404
+ { status: 400 }
405
+ );
406
+ }
407
+ const response = await client.reversal(body);
408
+ return (0, import_kit.json)(response);
409
+ }
410
+ if (lastSegment === "register-c2b") {
411
+ const body = await event.request.json();
412
+ const { shortCode, responseType, confirmationURL, validationURL } = body;
413
+ if (!confirmationURL || !validationURL) {
414
+ return (0, import_kit.json)(
415
+ { error: "Confirmation URL and validation URL are required" },
416
+ { status: 400 }
417
+ );
418
+ }
419
+ const response = await client.registerC2BUrl({
420
+ shortCode,
421
+ responseType,
422
+ confirmationURL,
423
+ validationURL
424
+ });
425
+ return (0, import_kit.json)(response);
426
+ }
427
+ if (lastSegment === "generate-qr") {
428
+ const body = await event.request.json();
429
+ const {
430
+ merchantName,
431
+ refNo,
432
+ amount,
433
+ transactionType,
434
+ creditPartyIdentifier,
435
+ size
436
+ } = body;
437
+ if (!merchantName || !refNo || !amount || !transactionType || !creditPartyIdentifier) {
438
+ return (0, import_kit.json)(
439
+ {
440
+ error: "Merchant name, reference number, amount, transaction type, and credit party identifier are required",
441
+ received: body
442
+ },
443
+ { status: 400 }
444
+ );
445
+ }
446
+ let qrSize = void 0;
447
+ if (size) {
448
+ if (size !== "500" && size !== "300") {
449
+ return (0, import_kit.json)(
450
+ {
451
+ error: "Size must be either '300' or '500'"
452
+ },
453
+ { status: 400 }
454
+ );
455
+ }
456
+ qrSize = size;
457
+ }
458
+ const response = await client.generateDynamicQR({
459
+ merchantName,
460
+ refNo,
461
+ amount: Number(amount),
462
+ transactionType,
463
+ creditPartyIdentifier,
464
+ size: qrSize
465
+ });
466
+ return (0, import_kit.json)(response);
467
+ }
468
+ return (0, import_kit.json)(
469
+ {
470
+ ResultCode: 1,
471
+ ResultDesc: `Unknown endpoint: ${lastSegment}`
472
+ },
473
+ { status: 404 }
474
+ );
475
+ } catch (error) {
476
+ console.error(`M-Pesa ${lastSegment} error:`, error);
477
+ return (0, import_kit.json)(
478
+ { error: error.message || "Request failed" },
479
+ { status: 500 }
480
+ );
481
+ }
482
+ }
483
+ }
484
+ };
485
+ return handlers;
486
+ }
487
+
488
+ // src/index.ts
489
+ var import_core2 = require("@singularity-payments/core");
490
+ function createMpesa(config, options) {
491
+ const client = new import_core.MpesaClient(config, options);
492
+ const handlers = createMpesaHandlers(client);
493
+ return {
494
+ /**
495
+ * M-Pesa client instance for making API calls
496
+ */
497
+ client,
498
+ /**
499
+ * Pre-configured SvelteKit route handlers for M-Pesa callbacks
500
+ */
501
+ handlers
502
+ };
503
+ }
504
+ // Annotate the CommonJS export names for ESM import in node:
505
+ 0 && (module.exports = {
506
+ MpesaClient,
507
+ createMpesa,
508
+ createMpesaHandlers
509
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,484 @@
1
+ // src/index.ts
2
+ import { MpesaClient } from "@singularity-payments/core";
3
+
4
+ // src/handlers.ts
5
+ import { json } from "@sveltejs/kit";
6
+ function createMpesaHandlers(client) {
7
+ const handlers = {
8
+ /**
9
+ * STK Push callback handler
10
+ * Handles callbacks from M-Pesa after STK Push requests
11
+ */
12
+ stkCallback: {
13
+ POST: async (event) => {
14
+ try {
15
+ const body = await event.request.json();
16
+ const ipAddress = event.request.headers.get("x-forwarded-for") || event.request.headers.get("x-real-ip") || void 0;
17
+ const response = await client.handleSTKCallback(body, ipAddress);
18
+ return json(response, { status: 200 });
19
+ } catch (error) {
20
+ console.error("STK Callback error:", error);
21
+ return json(
22
+ {
23
+ ResultCode: 1,
24
+ ResultDesc: "Internal error processing callback"
25
+ },
26
+ { status: 200 }
27
+ );
28
+ }
29
+ }
30
+ },
31
+ /**
32
+ * C2B validation handler
33
+ * Validates C2B transactions before they are processed
34
+ */
35
+ c2bValidation: {
36
+ POST: async (event) => {
37
+ try {
38
+ const body = await event.request.json();
39
+ const response = await client.handleC2BValidation(body);
40
+ return json(response, { status: 200 });
41
+ } catch (error) {
42
+ console.error("C2B Validation error:", error);
43
+ return json(
44
+ {
45
+ ResultCode: 1,
46
+ ResultDesc: "Validation failed"
47
+ },
48
+ { status: 200 }
49
+ );
50
+ }
51
+ }
52
+ },
53
+ /**
54
+ * C2B confirmation handler
55
+ * Confirms C2B transactions after they are processed
56
+ */
57
+ c2bConfirmation: {
58
+ POST: async (event) => {
59
+ try {
60
+ const body = await event.request.json();
61
+ const response = await client.handleC2BConfirmation(body);
62
+ return json(response, { status: 200 });
63
+ } catch (error) {
64
+ console.error("C2B Confirmation error:", error);
65
+ return json(
66
+ {
67
+ ResultCode: 1,
68
+ ResultDesc: "Processing failed"
69
+ },
70
+ { status: 200 }
71
+ );
72
+ }
73
+ }
74
+ },
75
+ /**
76
+ * B2C result handler
77
+ * Handles callbacks from M-Pesa after B2C requests
78
+ */
79
+ b2cResult: {
80
+ POST: async (event) => {
81
+ try {
82
+ const body = await event.request.json();
83
+ const parsed = client.getCallbackHandler().parseB2CCallback(body);
84
+ console.log("B2C Result:", parsed);
85
+ return json(
86
+ {
87
+ ResultCode: 0,
88
+ ResultDesc: "Accepted"
89
+ },
90
+ { status: 200 }
91
+ );
92
+ } catch (error) {
93
+ console.error("B2C Result error:", error);
94
+ return json(
95
+ {
96
+ ResultCode: 1,
97
+ ResultDesc: "Processing failed"
98
+ },
99
+ { status: 200 }
100
+ );
101
+ }
102
+ }
103
+ },
104
+ /**
105
+ * B2C timeout handler
106
+ * Handles timeout notifications from M-Pesa for B2C requests
107
+ */
108
+ b2cTimeout: {
109
+ POST: async (event) => {
110
+ try {
111
+ const body = await event.request.json();
112
+ console.log("B2C Timeout:", body);
113
+ return json(
114
+ {
115
+ ResultCode: 0,
116
+ ResultDesc: "Timeout received"
117
+ },
118
+ { status: 200 }
119
+ );
120
+ } catch (error) {
121
+ console.error("B2C Timeout error:", error);
122
+ return json(
123
+ {
124
+ ResultCode: 1,
125
+ ResultDesc: "Processing failed"
126
+ },
127
+ { status: 200 }
128
+ );
129
+ }
130
+ }
131
+ },
132
+ /**
133
+ * Catch-all handler for all M-Pesa webhooks and client-side API requests
134
+ * Routes based on URL path segment
135
+ *
136
+ * Usage: src/routes/api/mpesa/[...path]/+server.ts
137
+ * import { mpesa } from "$lib/mpesa";
138
+ * export const POST = mpesa.handlers.catchAll.POST;
139
+ *
140
+ * Supported endpoints:
141
+ *
142
+ * WEBHOOKS (from M-Pesa):
143
+ * - /api/mpesa/callback or /api/mpesa/stk-callback - STK Push callbacks
144
+ * - /api/mpesa/validation or /api/mpesa/c2b-validation - C2B validation
145
+ * - /api/mpesa/confirmation or /api/mpesa/c2b-confirmation - C2B confirmation
146
+ * - /api/mpesa/b2c-result - B2C result callback
147
+ * - /api/mpesa/b2c-timeout - B2C timeout callback
148
+ * - /api/mpesa/b2b-result - B2B result callback
149
+ * - /api/mpesa/b2b-timeout - B2B timeout callback
150
+ * - /api/mpesa/balance-result - Account balance result
151
+ * - /api/mpesa/balance-timeout - Account balance timeout
152
+ * - /api/mpesa/reversal-result - Reversal result
153
+ * - /api/mpesa/reversal-timeout - Reversal timeout
154
+ * - /api/mpesa/status-result - Transaction status result
155
+ * - /api/mpesa/status-timeout - Transaction status timeout
156
+ *
157
+ * CLIENT APIs (from your frontend):
158
+ * - /api/mpesa/stk-push - Initiate STK Push request
159
+ * - /api/mpesa/stk-query - Query STK Push status
160
+ * - /api/mpesa/b2c - Initiate B2C payment
161
+ * - /api/mpesa/b2b - Initiate B2B payment
162
+ * - /api/mpesa/balance - Query account balance
163
+ * - /api/mpesa/transaction-status - Query transaction status
164
+ * - /api/mpesa/reversal - Reverse a transaction
165
+ * - /api/mpesa/register-c2b - Register C2B URLs
166
+ * - /api/mpesa/generate-qr - Generate dynamic QR code
167
+ */
168
+ catchAll: {
169
+ POST: async (event) => {
170
+ const pathname = event.url.pathname;
171
+ const segments = pathname.split("/").filter(Boolean);
172
+ const lastSegment = segments[segments.length - 1];
173
+ try {
174
+ if (lastSegment === "callback" || lastSegment === "stk-callback") {
175
+ return handlers.stkCallback.POST(event);
176
+ }
177
+ if (lastSegment === "validation" || lastSegment === "c2b-validation") {
178
+ return handlers.c2bValidation.POST(event);
179
+ }
180
+ if (lastSegment === "confirmation" || lastSegment === "c2b-confirmation") {
181
+ return handlers.c2bConfirmation.POST(event);
182
+ }
183
+ if (lastSegment === "b2c-result") {
184
+ return handlers.b2cResult.POST(event);
185
+ }
186
+ if (lastSegment === "b2c-timeout") {
187
+ return handlers.b2cTimeout.POST(event);
188
+ }
189
+ if (lastSegment === "b2b-result") {
190
+ const body = await event.request.json();
191
+ const parsed = client.getCallbackHandler().parseB2BCallback(body);
192
+ console.log("B2B Result:", parsed);
193
+ return json({ ResultCode: 0, ResultDesc: "Accepted" });
194
+ }
195
+ if (lastSegment === "b2b-timeout") {
196
+ const body = await event.request.json();
197
+ console.log("B2B Timeout:", body);
198
+ return json({
199
+ ResultCode: 0,
200
+ ResultDesc: "Timeout received"
201
+ });
202
+ }
203
+ if (lastSegment === "balance-result") {
204
+ const body = await event.request.json();
205
+ const parsed = client.getCallbackHandler().parseAccountBalanceCallback(body);
206
+ console.log("Balance Result:", parsed);
207
+ return json({ ResultCode: 0, ResultDesc: "Accepted" });
208
+ }
209
+ if (lastSegment === "balance-timeout") {
210
+ const body = await event.request.json();
211
+ console.log("Balance Timeout:", body);
212
+ return json({
213
+ ResultCode: 0,
214
+ ResultDesc: "Timeout received"
215
+ });
216
+ }
217
+ if (lastSegment === "status-result") {
218
+ const body = await event.request.json();
219
+ const parsed = client.getCallbackHandler().parseTransactionStatusCallback(body);
220
+ console.log("Status Result:", parsed);
221
+ return json({ ResultCode: 0, ResultDesc: "Accepted" });
222
+ }
223
+ if (lastSegment === "status-timeout") {
224
+ const body = await event.request.json();
225
+ console.log("Status Timeout:", body);
226
+ return json({
227
+ ResultCode: 0,
228
+ ResultDesc: "Timeout received"
229
+ });
230
+ }
231
+ if (lastSegment === "reversal-result") {
232
+ const body = await event.request.json();
233
+ const parsed = client.getCallbackHandler().parseReversalCallback(body);
234
+ console.log("Reversal Result:", parsed);
235
+ return json({ ResultCode: 0, ResultDesc: "Accepted" });
236
+ }
237
+ if (lastSegment === "reversal-timeout") {
238
+ const body = await event.request.json();
239
+ console.log("Reversal Timeout:", body);
240
+ return json({
241
+ ResultCode: 0,
242
+ ResultDesc: "Timeout received"
243
+ });
244
+ }
245
+ if (lastSegment === "stk-push") {
246
+ const body = await event.request.json();
247
+ const {
248
+ amount,
249
+ phoneNumber,
250
+ accountReference,
251
+ transactionDesc,
252
+ callbackUrl
253
+ } = body;
254
+ if (!amount || !phoneNumber) {
255
+ return json(
256
+ { error: "Amount and phone number are required" },
257
+ { status: 400 }
258
+ );
259
+ }
260
+ const response = await client.stkPush({
261
+ amount: Number(amount),
262
+ phoneNumber: String(phoneNumber),
263
+ accountReference: accountReference || "Payment",
264
+ transactionDesc: transactionDesc || "Payment",
265
+ callbackUrl
266
+ });
267
+ return json(response);
268
+ }
269
+ if (lastSegment === "stk-query") {
270
+ const body = await event.request.json();
271
+ const { CheckoutRequestID } = body;
272
+ if (!CheckoutRequestID) {
273
+ return json(
274
+ { error: "CheckoutRequestID is required" },
275
+ { status: 400 }
276
+ );
277
+ }
278
+ const response = await client.stkQuery({ CheckoutRequestID });
279
+ return json(response);
280
+ }
281
+ if (lastSegment === "b2c") {
282
+ const body = await event.request.json();
283
+ const {
284
+ amount,
285
+ phoneNumber,
286
+ commandID,
287
+ remarks,
288
+ occasion,
289
+ resultUrl,
290
+ timeoutUrl
291
+ } = body;
292
+ if (!amount || !phoneNumber || !commandID) {
293
+ return json(
294
+ { error: "Amount, phone number, and command ID are required" },
295
+ { status: 400 }
296
+ );
297
+ }
298
+ const response = await client.b2c({
299
+ amount: Number(amount),
300
+ phoneNumber: String(phoneNumber),
301
+ commandID,
302
+ remarks: remarks || "Payment",
303
+ occasion,
304
+ resultUrl,
305
+ timeoutUrl
306
+ });
307
+ return json(response);
308
+ }
309
+ if (lastSegment === "b2b") {
310
+ const body = await event.request.json();
311
+ const {
312
+ amount,
313
+ partyB,
314
+ commandID,
315
+ senderIdentifierType,
316
+ receiverIdentifierType,
317
+ accountReference,
318
+ remarks,
319
+ resultUrl,
320
+ timeoutUrl
321
+ } = body;
322
+ console.log("B2B Request Parameters:", {
323
+ amount,
324
+ partyB,
325
+ commandID,
326
+ senderIdentifierType,
327
+ receiverIdentifierType,
328
+ accountReference,
329
+ remarks
330
+ });
331
+ if (!amount || !partyB || !commandID || !accountReference) {
332
+ return json(
333
+ {
334
+ error: "Amount, partyB, commandID, and account reference are required"
335
+ },
336
+ { status: 400 }
337
+ );
338
+ }
339
+ const response = await client.b2b({
340
+ amount: Number(amount),
341
+ partyB: String(partyB),
342
+ commandID,
343
+ senderIdentifierType,
344
+ receiverIdentifierType,
345
+ accountReference: String(accountReference),
346
+ remarks: remarks || "Payment",
347
+ resultUrl,
348
+ timeoutUrl
349
+ });
350
+ console.log("B2B Response:", response);
351
+ return json(response);
352
+ }
353
+ if (lastSegment === "balance") {
354
+ const body = await event.request.json();
355
+ const response = await client.accountBalance(
356
+ body
357
+ );
358
+ return json(response);
359
+ }
360
+ if (lastSegment === "transaction-status") {
361
+ const body = await event.request.json();
362
+ const { transactionID } = body;
363
+ if (!transactionID) {
364
+ return json(
365
+ { error: "Transaction ID is required" },
366
+ { status: 400 }
367
+ );
368
+ }
369
+ const response = await client.transactionStatus(body);
370
+ return json(response);
371
+ }
372
+ if (lastSegment === "reversal") {
373
+ const body = await event.request.json();
374
+ const { transactionID, amount } = body;
375
+ if (!transactionID || !amount) {
376
+ return json(
377
+ { error: "Transaction ID and amount are required" },
378
+ { status: 400 }
379
+ );
380
+ }
381
+ const response = await client.reversal(body);
382
+ return json(response);
383
+ }
384
+ if (lastSegment === "register-c2b") {
385
+ const body = await event.request.json();
386
+ const { shortCode, responseType, confirmationURL, validationURL } = body;
387
+ if (!confirmationURL || !validationURL) {
388
+ return json(
389
+ { error: "Confirmation URL and validation URL are required" },
390
+ { status: 400 }
391
+ );
392
+ }
393
+ const response = await client.registerC2BUrl({
394
+ shortCode,
395
+ responseType,
396
+ confirmationURL,
397
+ validationURL
398
+ });
399
+ return json(response);
400
+ }
401
+ if (lastSegment === "generate-qr") {
402
+ const body = await event.request.json();
403
+ const {
404
+ merchantName,
405
+ refNo,
406
+ amount,
407
+ transactionType,
408
+ creditPartyIdentifier,
409
+ size
410
+ } = body;
411
+ if (!merchantName || !refNo || !amount || !transactionType || !creditPartyIdentifier) {
412
+ return json(
413
+ {
414
+ error: "Merchant name, reference number, amount, transaction type, and credit party identifier are required",
415
+ received: body
416
+ },
417
+ { status: 400 }
418
+ );
419
+ }
420
+ let qrSize = void 0;
421
+ if (size) {
422
+ if (size !== "500" && size !== "300") {
423
+ return json(
424
+ {
425
+ error: "Size must be either '300' or '500'"
426
+ },
427
+ { status: 400 }
428
+ );
429
+ }
430
+ qrSize = size;
431
+ }
432
+ const response = await client.generateDynamicQR({
433
+ merchantName,
434
+ refNo,
435
+ amount: Number(amount),
436
+ transactionType,
437
+ creditPartyIdentifier,
438
+ size: qrSize
439
+ });
440
+ return json(response);
441
+ }
442
+ return json(
443
+ {
444
+ ResultCode: 1,
445
+ ResultDesc: `Unknown endpoint: ${lastSegment}`
446
+ },
447
+ { status: 404 }
448
+ );
449
+ } catch (error) {
450
+ console.error(`M-Pesa ${lastSegment} error:`, error);
451
+ return json(
452
+ { error: error.message || "Request failed" },
453
+ { status: 500 }
454
+ );
455
+ }
456
+ }
457
+ }
458
+ };
459
+ return handlers;
460
+ }
461
+
462
+ // src/index.ts
463
+ import {
464
+ MpesaClient as MpesaClient2
465
+ } from "@singularity-payments/core";
466
+ function createMpesa(config, options) {
467
+ const client = new MpesaClient(config, options);
468
+ const handlers = createMpesaHandlers(client);
469
+ return {
470
+ /**
471
+ * M-Pesa client instance for making API calls
472
+ */
473
+ client,
474
+ /**
475
+ * Pre-configured SvelteKit route handlers for M-Pesa callbacks
476
+ */
477
+ handlers
478
+ };
479
+ }
480
+ export {
481
+ MpesaClient2 as MpesaClient,
482
+ createMpesa,
483
+ createMpesaHandlers
484
+ };
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@singularity-payments/sveltekit",
3
+ "version": "0.1.0-alpha.1",
4
+ "publishConfig": {
5
+ "access": "public"
6
+ },
7
+ "description": "SvelteKit 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
+ "sveltekit",
25
+ "payments",
26
+ "kenya"
27
+ ],
28
+ "author": "",
29
+ "license": "Apache-2.0",
30
+ "peerDependencies": {
31
+ "next": ">=13.0.0"
32
+ },
33
+ "dependencies": {
34
+ "@sveltejs/kit": "^2.49.2",
35
+ "@singularity-payments/core": "0.1.0-alpha.0"
36
+ },
37
+ "devDependencies": {
38
+ "@types/node": "^25.0.3",
39
+ "next": "^15.1.0",
40
+ "tsup": "^8.5.1",
41
+ "typescript": "^5.9.3"
42
+ },
43
+ "scripts": {
44
+ "test": "echo \"Error: no test specified\" && exit 1",
45
+ "build": "tsup src/index.ts --format cjs,esm --dts --external next",
46
+ "dev": "tsup src/index.ts --format cjs,esm --dts --external next --watch"
47
+ }
48
+ }