@paykit-sdk/gopay 1.0.0

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/README.md ADDED
@@ -0,0 +1,185 @@
1
+ # @paykit-sdk/gopay
2
+
3
+ Stripe provider for PayKit
4
+
5
+ ## Quick Start
6
+
7
+ ```typescript
8
+ import { createEndpointHandlers, PayKit } from '@paykit-sdk/core';
9
+ import { gopay, createGopay } from '@paykit-sdk/gopay';
10
+
11
+ // Method 1: Using environment variables
12
+ const provider = gopay(); // Ensure GOPAY_CLIENT_ID, GOPAY_CLIENT_SECRET, GOPAY_GO_ID, GOPAY_SANDBOX, GOPAY_WEBHOOK_URL environment variables are set
13
+
14
+ // Method 2: Direct configuration
15
+ const provider = createGopay({
16
+ clientId: 'sk_test_...',
17
+ clientSecret: 'clsec_...',
18
+ goId: 'go...',
19
+ isSandbox: true,
20
+ webhookUrl: 'http://localhost:8080/api/paykit/webhook',
21
+ });
22
+
23
+ export const paykit = new PayKit(provider);
24
+ export const endpoints = createEndpointHandlers(paykit);
25
+ ```
26
+
27
+ ### Next.js Catch All API Route (/api/paykit/[...endpoint]/route.ts)
28
+
29
+ ```typescript
30
+ import { paykit } from '@/lib/paykit';
31
+ import { EndpointPath } from '@paykit-sdk/core';
32
+
33
+ export async function POST(request: NextRequest, { params }: { params: { endpoint: string[] } }) {
34
+ try {
35
+ // Construct the endpoint path with full type safety
36
+ const endpoint = ('/' + params.endpoint.join('/')) as EndpointPath;
37
+ const handler = endpoints[endpoint];
38
+
39
+ if (!handler) {
40
+ return NextResponse.json({ message: 'Endpoint not found' }, { status: 404 });
41
+ }
42
+
43
+ // Parse request body
44
+ const body = await request.json();
45
+ const { args } = body;
46
+
47
+ const result = await handler(...args);
48
+
49
+ return NextResponse.json({ result });
50
+ } catch (error) {
51
+ console.error('PayKit API Error:', error);
52
+ return NextResponse.json(
53
+ { message: error instanceof Error ? error.message : 'Internal server error' },
54
+ { status: 500 },
55
+ );
56
+ }
57
+ }
58
+ ```
59
+
60
+ ### Next.js Webhooks (/api/paykit/webhooks/route.ts)
61
+
62
+ ```typescript
63
+ import { paykit } from '@/lib/paykit';
64
+ import { NextRequest } from 'next/server';
65
+
66
+ export async function POST(request: NextRequest) {
67
+ const webhook = paykit.webhooks
68
+ .setup({ webhookSecret: '' })
69
+ .on('customer.created', async event => {
70
+ console.log('Customer created:', event.data);
71
+ });
72
+ .on('subscription.created', async event => {
73
+ console.log('Subscription created:', event.data);
74
+ });
75
+ .on('payment.created', async event => {
76
+ console.log('Payment created:', event.data);
77
+ });
78
+ .on('refund.created', async event => {
79
+ console.log('Refund created:', event.data);
80
+ });
81
+ .on('invoice.generated', async event => {
82
+ console.log('Invoice generated:', event.data);
83
+ });
84
+
85
+ const body = await request.text();
86
+ const headers = Object.fromEntries(request.headers.entries());
87
+ const url = request.url
88
+ await webhook.handle({ body, headers, fullUrl: url });
89
+
90
+ // Return immediately, processing happens in background
91
+ return NextResponse.json({ success: true });
92
+ }
93
+ ```
94
+
95
+ ### Express.js with Webhook Handler
96
+
97
+ ```typescript
98
+ import { paykit, endpoints } from '@/lib/paykit';
99
+ import { createEndpointHandlers, EndpointPath } from '@paykit-sdk/core';
100
+ import express from 'express';
101
+
102
+ const app = express();
103
+
104
+ // IMPORTANT: Webhook route must come BEFORE express.json() middleware
105
+ // This ensures we get the raw body for signature verification
106
+ app.post('/api/webhooks/gopay', express.raw({ type: 'application/json' }), async (req, res) => {
107
+ try {
108
+ const webhook = paykit.webhooks
109
+ .setup({ webhookSecret: '' })
110
+ .on('customer.created', async event => {
111
+ console.log('Customer created:', event.data);
112
+ })
113
+ .on('subscription.created', async event => {
114
+ console.log('Subscription created:', event.data);
115
+ })
116
+ .on('payment.created', async event => {
117
+ console.log('Payment created:', event.data);
118
+ })
119
+ .on('refund.created', async event => {
120
+ console.log('Refund created:', event.data);
121
+ })
122
+ .on('invoice.generated', async event => {
123
+ console.log('Invoice generated:', event.data);
124
+ });
125
+
126
+ const body = req.body; // Raw buffer from express.raw()
127
+ const headers = req.headers;
128
+ const url = request.url;
129
+ await webhook.handle({ body, headers, fullUrl: url });
130
+
131
+ // Return immediately, processing happens in background
132
+ res.json({ success: true });
133
+ } catch (error) {
134
+ console.error('Webhook error:', error);
135
+ res.status(500).json({
136
+ message: error instanceof Error ? error.message : 'Webhook processing failed',
137
+ });
138
+ }
139
+ });
140
+
141
+ // Regular API routes use JSON middleware
142
+ app.use(express.json());
143
+
144
+ app.post('/api/paykit/*', async (req, res) => {
145
+ try {
146
+ const endpoint = req.path.replace('/api/paykit', '') as EndpointPath;
147
+ const handler = endpoints[endpoint];
148
+
149
+ if (!handler) {
150
+ return res.status(404).json({ message: 'Endpoint not found' });
151
+ }
152
+
153
+ const { args } = req.body;
154
+ const result = await handler(...args);
155
+
156
+ res.json({ result });
157
+ } catch (error) {
158
+ res.status(500).json({
159
+ message: error instanceof Error ? error.message : 'Internal server error',
160
+ });
161
+ }
162
+ });
163
+
164
+ app.listen(3000, () => {
165
+ console.log('Server running on port 3000');
166
+ });
167
+ ```
168
+
169
+ ## Environment Variables
170
+
171
+ ```bash
172
+ GOPAY_CLIENT_ID=sk_test_...
173
+ GOPAY_CLIENT_SECRET=clsec_...
174
+ GOPAY_GO_ID=go...
175
+ GOPAY_SANDBOX=true
176
+ GOPAY_WEBHOOK_URL=http://localhost:8080/api/paykit/webhook
177
+ ```
178
+
179
+ ## Support
180
+
181
+ - [Gopay Documentation](https://doc.gopay.com/)
182
+
183
+ ## License
184
+
185
+ ISC
@@ -0,0 +1,19 @@
1
+ import { GoPayOptions } from '../gopay-provider.mjs';
2
+ import '@paykit-sdk/core';
3
+
4
+ declare class AuthController {
5
+ private opts;
6
+ private _client;
7
+ private _accessToken;
8
+ constructor(opts: GoPayOptions & {
9
+ baseUrl: string;
10
+ });
11
+ getAccessToken: () => Promise<string>;
12
+ getAuthHeaders: () => Promise<{
13
+ Authorization: string;
14
+ 'Content-Type': string;
15
+ Accept: string;
16
+ }>;
17
+ }
18
+
19
+ export { AuthController };
@@ -0,0 +1,19 @@
1
+ import { GoPayOptions } from '../gopay-provider.js';
2
+ import '@paykit-sdk/core';
3
+
4
+ declare class AuthController {
5
+ private opts;
6
+ private _client;
7
+ private _accessToken;
8
+ constructor(opts: GoPayOptions & {
9
+ baseUrl: string;
10
+ });
11
+ getAccessToken: () => Promise<string>;
12
+ getAuthHeaders: () => Promise<{
13
+ Authorization: string;
14
+ 'Content-Type': string;
15
+ Accept: string;
16
+ }>;
17
+ }
18
+
19
+ export { AuthController };
@@ -0,0 +1,41 @@
1
+ 'use strict';
2
+
3
+ var core = require('@paykit-sdk/core');
4
+
5
+ // src/controllers/auth.ts
6
+ var AuthController = class {
7
+ constructor(opts) {
8
+ this.opts = opts;
9
+ const debug = opts.debug ?? true;
10
+ this._client = new core.HTTPClient({ baseUrl: this.opts.baseUrl, headers: {}, retryOptions: { max: 3, baseDelay: 1e3, debug } });
11
+ }
12
+ _client;
13
+ _accessToken = null;
14
+ getAccessToken = async () => {
15
+ if (this._accessToken) {
16
+ const [token, , expiryStr] = this._accessToken.split("::paykit::");
17
+ const expiry = parseInt(expiryStr || "0", 10);
18
+ if (expiry > Date.now()) return token;
19
+ }
20
+ const credentials = Buffer.from(`${this.opts.clientId}:${this.opts.clientSecret}`).toString("base64");
21
+ const response = await this._client.post("/oauth2/token", {
22
+ headers: { Authorization: `Basic ${credentials}`, "Content-Type": "application/x-www-form-urlencoded" },
23
+ body: new URLSearchParams({ grant_type: "client_credentials", scope: "payment-all" }).toString()
24
+ });
25
+ if (!response.ok || !response.value.access_token) {
26
+ throw new core.OperationFailedError("getAccessToken", "gopay", {
27
+ cause: new Error("Failed to obtain GoPay access token")
28
+ });
29
+ }
30
+ const expiryTime = Date.now() + (response.value.expires_in - 300) * 1e3;
31
+ const accessToken = `${response.value.access_token}::paykit::${expiryTime}`;
32
+ this._accessToken = accessToken;
33
+ return accessToken;
34
+ };
35
+ getAuthHeaders = async () => {
36
+ const token = await this.getAccessToken();
37
+ return { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "application/json" };
38
+ };
39
+ };
40
+
41
+ exports.AuthController = AuthController;
@@ -0,0 +1,39 @@
1
+ import { HTTPClient, OperationFailedError } from '@paykit-sdk/core';
2
+
3
+ // src/controllers/auth.ts
4
+ var AuthController = class {
5
+ constructor(opts) {
6
+ this.opts = opts;
7
+ const debug = opts.debug ?? true;
8
+ this._client = new HTTPClient({ baseUrl: this.opts.baseUrl, headers: {}, retryOptions: { max: 3, baseDelay: 1e3, debug } });
9
+ }
10
+ _client;
11
+ _accessToken = null;
12
+ getAccessToken = async () => {
13
+ if (this._accessToken) {
14
+ const [token, , expiryStr] = this._accessToken.split("::paykit::");
15
+ const expiry = parseInt(expiryStr || "0", 10);
16
+ if (expiry > Date.now()) return token;
17
+ }
18
+ const credentials = Buffer.from(`${this.opts.clientId}:${this.opts.clientSecret}`).toString("base64");
19
+ const response = await this._client.post("/oauth2/token", {
20
+ headers: { Authorization: `Basic ${credentials}`, "Content-Type": "application/x-www-form-urlencoded" },
21
+ body: new URLSearchParams({ grant_type: "client_credentials", scope: "payment-all" }).toString()
22
+ });
23
+ if (!response.ok || !response.value.access_token) {
24
+ throw new OperationFailedError("getAccessToken", "gopay", {
25
+ cause: new Error("Failed to obtain GoPay access token")
26
+ });
27
+ }
28
+ const expiryTime = Date.now() + (response.value.expires_in - 300) * 1e3;
29
+ const accessToken = `${response.value.access_token}::paykit::${expiryTime}`;
30
+ this._accessToken = accessToken;
31
+ return accessToken;
32
+ };
33
+ getAuthHeaders = async () => {
34
+ const token = await this.getAccessToken();
35
+ return { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "application/json" };
36
+ };
37
+ };
38
+
39
+ export { AuthController };
@@ -0,0 +1,58 @@
1
+ import { PaykitProviderOptions, AbstractPayKitProvider, PayKitProvider, CreateCheckoutSchema, Checkout, UpdateCheckoutSchema, CreateCustomerParams, Customer, UpdateCustomerParams, CreateSubscriptionSchema, Subscription, UpdateSubscriptionSchema, CreatePaymentSchema, Payment, CapturePaymentSchema, UpdatePaymentSchema, CreateRefundSchema, Refund, HandleWebhookParams, WebhookEventPayload } from '@paykit-sdk/core';
2
+
3
+ interface GoPayOptions extends PaykitProviderOptions {
4
+ /**
5
+ * The client ID for the GoPay API
6
+ */
7
+ clientId: string;
8
+ /**
9
+ * The client secret for the GoPay API
10
+ */
11
+ clientSecret: string;
12
+ /**
13
+ * The GoID for the GoPay API
14
+ */
15
+ goId: string;
16
+ /**
17
+ * Whether to use the sandbox environment
18
+ */
19
+ isSandbox: boolean;
20
+ /**
21
+ * The webhook URL for the GoPay API
22
+ */
23
+ webhookUrl: string;
24
+ }
25
+ declare class GoPayProvider extends AbstractPayKitProvider implements PayKitProvider {
26
+ private readonly opts;
27
+ readonly providerName = "gopay";
28
+ private _client;
29
+ private baseUrl;
30
+ private authController;
31
+ constructor(opts: GoPayOptions);
32
+ createCheckout: (params: CreateCheckoutSchema) => Promise<Checkout>;
33
+ retrieveCheckout: (id: string) => Promise<Checkout | null>;
34
+ updateCheckout: (id: string, params: UpdateCheckoutSchema) => Promise<Checkout>;
35
+ deleteCheckout: (id: string) => Promise<null>;
36
+ createCustomer: (params: CreateCustomerParams) => Promise<Customer>;
37
+ updateCustomer: (id: string, params: UpdateCustomerParams) => Promise<Customer>;
38
+ deleteCustomer: (id: string) => Promise<null>;
39
+ retrieveCustomer: (id: string) => Promise<Customer | null>;
40
+ createSubscription: (params: CreateSubscriptionSchema) => Promise<Subscription>;
41
+ updateSubscription: (id: string, params: UpdateSubscriptionSchema) => Promise<Subscription>;
42
+ cancelSubscription: (id: string) => Promise<Subscription>;
43
+ deleteSubscription: (id: string) => Promise<null>;
44
+ retrieveSubscription: (id: string) => Promise<Subscription | null>;
45
+ createPayment: (params: CreatePaymentSchema) => Promise<Payment>;
46
+ retrievePayment: (id: string) => Promise<Payment | null>;
47
+ deletePayment: (id: string) => Promise<null>;
48
+ capturePayment: (id: string, params: CapturePaymentSchema) => Promise<Payment>;
49
+ cancelPayment: (id: string) => Promise<Payment>;
50
+ /**
51
+ * Update payment - not supported by GoPay
52
+ */
53
+ updatePayment: (id: string, params: UpdatePaymentSchema) => Promise<Payment>;
54
+ createRefund(params: CreateRefundSchema): Promise<Refund>;
55
+ handleWebhook: (payload: HandleWebhookParams) => Promise<Array<WebhookEventPayload>>;
56
+ }
57
+
58
+ export { type GoPayOptions, GoPayProvider };
@@ -0,0 +1,58 @@
1
+ import { PaykitProviderOptions, AbstractPayKitProvider, PayKitProvider, CreateCheckoutSchema, Checkout, UpdateCheckoutSchema, CreateCustomerParams, Customer, UpdateCustomerParams, CreateSubscriptionSchema, Subscription, UpdateSubscriptionSchema, CreatePaymentSchema, Payment, CapturePaymentSchema, UpdatePaymentSchema, CreateRefundSchema, Refund, HandleWebhookParams, WebhookEventPayload } from '@paykit-sdk/core';
2
+
3
+ interface GoPayOptions extends PaykitProviderOptions {
4
+ /**
5
+ * The client ID for the GoPay API
6
+ */
7
+ clientId: string;
8
+ /**
9
+ * The client secret for the GoPay API
10
+ */
11
+ clientSecret: string;
12
+ /**
13
+ * The GoID for the GoPay API
14
+ */
15
+ goId: string;
16
+ /**
17
+ * Whether to use the sandbox environment
18
+ */
19
+ isSandbox: boolean;
20
+ /**
21
+ * The webhook URL for the GoPay API
22
+ */
23
+ webhookUrl: string;
24
+ }
25
+ declare class GoPayProvider extends AbstractPayKitProvider implements PayKitProvider {
26
+ private readonly opts;
27
+ readonly providerName = "gopay";
28
+ private _client;
29
+ private baseUrl;
30
+ private authController;
31
+ constructor(opts: GoPayOptions);
32
+ createCheckout: (params: CreateCheckoutSchema) => Promise<Checkout>;
33
+ retrieveCheckout: (id: string) => Promise<Checkout | null>;
34
+ updateCheckout: (id: string, params: UpdateCheckoutSchema) => Promise<Checkout>;
35
+ deleteCheckout: (id: string) => Promise<null>;
36
+ createCustomer: (params: CreateCustomerParams) => Promise<Customer>;
37
+ updateCustomer: (id: string, params: UpdateCustomerParams) => Promise<Customer>;
38
+ deleteCustomer: (id: string) => Promise<null>;
39
+ retrieveCustomer: (id: string) => Promise<Customer | null>;
40
+ createSubscription: (params: CreateSubscriptionSchema) => Promise<Subscription>;
41
+ updateSubscription: (id: string, params: UpdateSubscriptionSchema) => Promise<Subscription>;
42
+ cancelSubscription: (id: string) => Promise<Subscription>;
43
+ deleteSubscription: (id: string) => Promise<null>;
44
+ retrieveSubscription: (id: string) => Promise<Subscription | null>;
45
+ createPayment: (params: CreatePaymentSchema) => Promise<Payment>;
46
+ retrievePayment: (id: string) => Promise<Payment | null>;
47
+ deletePayment: (id: string) => Promise<null>;
48
+ capturePayment: (id: string, params: CapturePaymentSchema) => Promise<Payment>;
49
+ cancelPayment: (id: string) => Promise<Payment>;
50
+ /**
51
+ * Update payment - not supported by GoPay
52
+ */
53
+ updatePayment: (id: string, params: UpdatePaymentSchema) => Promise<Payment>;
54
+ createRefund(params: CreateRefundSchema): Promise<Refund>;
55
+ handleWebhook: (payload: HandleWebhookParams) => Promise<Array<WebhookEventPayload>>;
56
+ }
57
+
58
+ export { type GoPayOptions, GoPayProvider };