@dodopayments/better-auth 1.3.3 → 1.3.5
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/dist/chunk-CRRND2EH.js +67 -0
- package/dist/chunk-CRRND2EH.js.map +1 -0
- package/dist/chunk-HHIXOUFD.js +80 -0
- package/dist/chunk-HHIXOUFD.js.map +1 -0
- package/dist/chunk-J55PDPLE.js +196 -0
- package/dist/chunk-J55PDPLE.js.map +1 -0
- package/dist/chunk-O3BTJOIO.js +177 -0
- package/dist/chunk-O3BTJOIO.js.map +1 -0
- package/dist/chunk-PXI4EHZC.js +12 -0
- package/dist/chunk-PXI4EHZC.js.map +1 -0
- package/dist/client.cjs +36 -0
- package/dist/client.cjs.map +1 -0
- package/dist/client.d.cts +7 -0
- package/dist/client.d.ts +7 -5
- package/dist/client.js +6 -5
- package/dist/client.js.map +1 -0
- package/dist/hooks/customer.cjs +92 -0
- package/dist/hooks/customer.cjs.map +1 -0
- package/dist/hooks/customer.d.cts +11 -0
- package/dist/hooks/customer.d.ts +11 -4
- package/dist/hooks/customer.js +8 -62
- package/dist/hooks/customer.js.map +1 -0
- package/dist/index.cjs +573 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +909 -0
- package/dist/index.d.ts +321 -200
- package/dist/index.js +53 -34
- package/dist/index.js.map +1 -0
- package/dist/plugins/checkout.cjs +197 -0
- package/dist/plugins/checkout.cjs.map +1 -0
- package/dist/plugins/checkout.d.cts +6 -0
- package/dist/plugins/checkout.d.ts +6 -548
- package/dist/plugins/checkout.js +6 -170
- package/dist/plugins/checkout.js.map +1 -0
- package/dist/plugins/portal.cjs +220 -0
- package/dist/plugins/portal.cjs.map +1 -0
- package/dist/plugins/portal.d.cts +6 -0
- package/dist/plugins/portal.d.ts +6 -204
- package/dist/plugins/portal.js +6 -171
- package/dist/plugins/portal.js.map +1 -0
- package/dist/plugins/webhooks.cjs +102 -0
- package/dist/plugins/webhooks.cjs.map +1 -0
- package/dist/plugins/webhooks.d.cts +6 -0
- package/dist/plugins/webhooks.d.ts +6 -41
- package/dist/plugins/webhooks.js +6 -61
- package/dist/plugins/webhooks.js.map +1 -0
- package/dist/types-yAk7fHrK.d.cts +953 -0
- package/dist/types-yAk7fHrK.d.ts +953 -0
- package/dist/types.cjs +19 -0
- package/dist/types.cjs.map +1 -0
- package/dist/types.d.cts +6 -0
- package/dist/types.d.ts +6 -52
- package/dist/types.js +1 -1
- package/dist/types.js.map +1 -0
- package/package.json +5 -10
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// src/hooks/customer.ts
|
|
2
|
+
import { APIError } from "better-auth/api";
|
|
3
|
+
var onUserCreate = (options) => async (user, ctx) => {
|
|
4
|
+
if (ctx && options.createCustomerOnSignUp) {
|
|
5
|
+
try {
|
|
6
|
+
const customers = await options.client.customers.list({
|
|
7
|
+
email: user.email
|
|
8
|
+
});
|
|
9
|
+
const existingCustomer = customers.items[0];
|
|
10
|
+
if (existingCustomer) {
|
|
11
|
+
if (existingCustomer.email !== user.email) {
|
|
12
|
+
await options.client.customers.update(
|
|
13
|
+
existingCustomer.customer_id,
|
|
14
|
+
{
|
|
15
|
+
name: user.name
|
|
16
|
+
}
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
} else {
|
|
20
|
+
await options.client.customers.create({
|
|
21
|
+
email: user.email,
|
|
22
|
+
name: user.name
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
} catch (e) {
|
|
26
|
+
if (e instanceof Error) {
|
|
27
|
+
throw new APIError("INTERNAL_SERVER_ERROR", {
|
|
28
|
+
message: `DodoPayments customer creation failed. Error: ${e.message}`
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
throw new APIError("INTERNAL_SERVER_ERROR", {
|
|
32
|
+
message: `DodoPayments customer creation failed. Error: ${e}`
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
var onUserUpdate = (options) => async (user, ctx) => {
|
|
38
|
+
if (ctx && options.createCustomerOnSignUp) {
|
|
39
|
+
try {
|
|
40
|
+
const customers = await options.client.customers.list({
|
|
41
|
+
email: user.email
|
|
42
|
+
});
|
|
43
|
+
const existingCustomer = customers.items[0];
|
|
44
|
+
if (existingCustomer) {
|
|
45
|
+
await options.client.customers.update(existingCustomer.customer_id, {
|
|
46
|
+
name: user.name
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
} catch (e) {
|
|
50
|
+
if (e instanceof Error) {
|
|
51
|
+
ctx.context.logger.error(
|
|
52
|
+
`DodoPayments customer update failed. Error: ${e.message}`
|
|
53
|
+
);
|
|
54
|
+
} else {
|
|
55
|
+
ctx.context.logger.error(
|
|
56
|
+
`DodoPayments customer update failed. Error: ${e}`
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
export {
|
|
64
|
+
onUserCreate,
|
|
65
|
+
onUserUpdate
|
|
66
|
+
};
|
|
67
|
+
//# sourceMappingURL=chunk-CRRND2EH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/hooks/customer.ts"],"sourcesContent":["import type { GenericEndpointContext, User } from \"better-auth\";\nimport { APIError } from \"better-auth/api\";\nimport type { DodoPaymentsOptions } from \"../types\";\n\nexport const onUserCreate =\n (options: DodoPaymentsOptions) =>\n async (user: User, ctx?: GenericEndpointContext) => {\n if (ctx && options.createCustomerOnSignUp) {\n try {\n const customers = await options.client.customers.list({\n email: user.email,\n });\n const existingCustomer = customers.items[0];\n\n if (existingCustomer) {\n if (existingCustomer.email !== user.email) {\n await options.client.customers.update(\n existingCustomer.customer_id,\n {\n name: user.name,\n },\n );\n }\n } else {\n // TODO: Add metadata to customer object via\n // getCustomerCreateParams option when it becomes\n // available in the API\n await options.client.customers.create({\n email: user.email,\n name: user.name,\n });\n }\n } catch (e: unknown) {\n if (e instanceof Error) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: `DodoPayments customer creation failed. Error: ${e.message}`,\n });\n }\n\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: `DodoPayments customer creation failed. Error: ${e}`,\n });\n }\n }\n };\n\nexport const onUserUpdate =\n (options: DodoPaymentsOptions) =>\n async (user: User, ctx?: GenericEndpointContext) => {\n if (ctx && options.createCustomerOnSignUp) {\n try {\n const customers = await options.client.customers.list({\n email: user.email,\n });\n const existingCustomer = customers.items[0];\n\n if (existingCustomer) {\n // TODO: Add metadata to customer object via\n // getCustomerCreateParams option when it becomes\n // available in the API\n await options.client.customers.update(existingCustomer.customer_id, {\n name: user.name,\n });\n }\n } catch (e: unknown) {\n if (e instanceof Error) {\n ctx.context.logger.error(\n `DodoPayments customer update failed. Error: ${e.message}`,\n );\n } else {\n ctx.context.logger.error(\n `DodoPayments customer update failed. Error: ${e}`,\n );\n }\n }\n }\n };\n"],"mappings":";AACA,SAAS,gBAAgB;AAGlB,IAAM,eACX,CAAC,YACD,OAAO,MAAY,QAAiC;AAClD,MAAI,OAAO,QAAQ,wBAAwB;AACzC,QAAI;AACF,YAAM,YAAY,MAAM,QAAQ,OAAO,UAAU,KAAK;AAAA,QACpD,OAAO,KAAK;AAAA,MACd,CAAC;AACD,YAAM,mBAAmB,UAAU,MAAM,CAAC;AAE1C,UAAI,kBAAkB;AACpB,YAAI,iBAAiB,UAAU,KAAK,OAAO;AACzC,gBAAM,QAAQ,OAAO,UAAU;AAAA,YAC7B,iBAAiB;AAAA,YACjB;AAAA,cACE,MAAM,KAAK;AAAA,YACb;AAAA,UACF;AAAA,QACF;AAAA,MACF,OAAO;AAIL,cAAM,QAAQ,OAAO,UAAU,OAAO;AAAA,UACpC,OAAO,KAAK;AAAA,UACZ,MAAM,KAAK;AAAA,QACb,CAAC;AAAA,MACH;AAAA,IACF,SAAS,GAAY;AACnB,UAAI,aAAa,OAAO;AACtB,cAAM,IAAI,SAAS,yBAAyB;AAAA,UAC1C,SAAS,iDAAiD,EAAE,OAAO;AAAA,QACrE,CAAC;AAAA,MACH;AAEA,YAAM,IAAI,SAAS,yBAAyB;AAAA,QAC1C,SAAS,iDAAiD,CAAC;AAAA,MAC7D,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAEK,IAAM,eACX,CAAC,YACD,OAAO,MAAY,QAAiC;AAClD,MAAI,OAAO,QAAQ,wBAAwB;AACzC,QAAI;AACF,YAAM,YAAY,MAAM,QAAQ,OAAO,UAAU,KAAK;AAAA,QACpD,OAAO,KAAK;AAAA,MACd,CAAC;AACD,YAAM,mBAAmB,UAAU,MAAM,CAAC;AAE1C,UAAI,kBAAkB;AAIpB,cAAM,QAAQ,OAAO,UAAU,OAAO,iBAAiB,aAAa;AAAA,UAClE,MAAM,KAAK;AAAA,QACb,CAAC;AAAA,MACH;AAAA,IACF,SAAS,GAAY;AACnB,UAAI,aAAa,OAAO;AACtB,YAAI,QAAQ,OAAO;AAAA,UACjB,+CAA+C,EAAE,OAAO;AAAA,QAC1D;AAAA,MACF,OAAO;AACL,YAAI,QAAQ,OAAO;AAAA,UACjB,+CAA+C,CAAC;AAAA,QAClD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// src/plugins/webhooks.ts
|
|
2
|
+
import {
|
|
3
|
+
handleWebhookPayload
|
|
4
|
+
} from "@dodopayments/core/webhook";
|
|
5
|
+
import { APIError, createAuthEndpoint } from "better-auth/api";
|
|
6
|
+
import { verifyWebhookPayload } from "@dodopayments/core/webhook";
|
|
7
|
+
var webhooks = (options) => (_dodopayments) => {
|
|
8
|
+
return {
|
|
9
|
+
dodopaymentsWebhooks: createAuthEndpoint(
|
|
10
|
+
"/dodopayments/webhooks",
|
|
11
|
+
{
|
|
12
|
+
method: "POST",
|
|
13
|
+
metadata: {
|
|
14
|
+
isAction: false
|
|
15
|
+
},
|
|
16
|
+
cloneRequest: true
|
|
17
|
+
},
|
|
18
|
+
async (ctx) => {
|
|
19
|
+
const { webhookKey } = options;
|
|
20
|
+
if (!ctx.request?.body) {
|
|
21
|
+
throw new APIError("INTERNAL_SERVER_ERROR");
|
|
22
|
+
}
|
|
23
|
+
const buf = await ctx.request.text();
|
|
24
|
+
let event;
|
|
25
|
+
try {
|
|
26
|
+
if (!webhookKey) {
|
|
27
|
+
throw new APIError("INTERNAL_SERVER_ERROR", {
|
|
28
|
+
message: "DodoPayments webhook webhookKey not found"
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
const headers = {
|
|
32
|
+
"webhook-id": ctx.request.headers.get("webhook-id"),
|
|
33
|
+
"webhook-timestamp": ctx.request.headers.get(
|
|
34
|
+
"webhook-timestamp"
|
|
35
|
+
),
|
|
36
|
+
"webhook-signature": ctx.request.headers.get(
|
|
37
|
+
"webhook-signature"
|
|
38
|
+
)
|
|
39
|
+
};
|
|
40
|
+
event = await verifyWebhookPayload({
|
|
41
|
+
webhookKey,
|
|
42
|
+
headers,
|
|
43
|
+
body: buf
|
|
44
|
+
});
|
|
45
|
+
} catch (err) {
|
|
46
|
+
if (err instanceof Error) {
|
|
47
|
+
ctx.context.logger.error(`Webhook Error: ${err.message}`);
|
|
48
|
+
throw new APIError("BAD_REQUEST", {
|
|
49
|
+
message: `Webhook Error: ${err.message}`
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
throw new APIError("BAD_REQUEST", {
|
|
53
|
+
message: `Webhook Error: ${err}`
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
try {
|
|
57
|
+
await handleWebhookPayload(event, options);
|
|
58
|
+
} catch (e) {
|
|
59
|
+
if (e instanceof Error) {
|
|
60
|
+
ctx.context.logger.error(
|
|
61
|
+
`DodoPayments webhook failed. Error: ${e.message}`
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
ctx.context.logger.error(
|
|
65
|
+
`DodoPayments webhook failed. Error: ${e}`
|
|
66
|
+
);
|
|
67
|
+
throw new APIError("BAD_REQUEST", {
|
|
68
|
+
message: "Webhook error: See server logs for more information."
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
return ctx.json({ received: true });
|
|
72
|
+
}
|
|
73
|
+
)
|
|
74
|
+
};
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
export {
|
|
78
|
+
webhooks
|
|
79
|
+
};
|
|
80
|
+
//# sourceMappingURL=chunk-HHIXOUFD.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/plugins/webhooks.ts"],"sourcesContent":["import type { DodoPayments } from \"dodopayments\";\nimport {\n handleWebhookPayload,\n WebhookHandlerConfig,\n} from \"@dodopayments/core/webhook\";\nimport { APIError, createAuthEndpoint } from \"better-auth/api\";\nimport { WebhookPayload } from \"@dodopayments/core/schemas\";\nimport { verifyWebhookPayload } from \"@dodopayments/core/webhook\";\nimport type { WebhookResponse } from \"../types\";\n\nexport const webhooks =\n (options: WebhookHandlerConfig) => (_dodopayments: DodoPayments) => {\n return {\n dodopaymentsWebhooks: createAuthEndpoint(\n \"/dodopayments/webhooks\",\n {\n method: \"POST\",\n metadata: {\n isAction: false,\n },\n cloneRequest: true,\n },\n async (ctx): Promise<WebhookResponse> => {\n const { webhookKey } = options;\n\n if (!ctx.request?.body) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\");\n }\n const buf = await ctx.request.text();\n let event: WebhookPayload;\n try {\n if (!webhookKey) {\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: \"DodoPayments webhook webhookKey not found\",\n });\n }\n\n const headers = {\n \"webhook-id\": ctx.request.headers.get(\"webhook-id\") as string,\n \"webhook-timestamp\": ctx.request.headers.get(\n \"webhook-timestamp\",\n ) as string,\n \"webhook-signature\": ctx.request.headers.get(\n \"webhook-signature\",\n ) as string,\n };\n\n event = await verifyWebhookPayload({\n webhookKey,\n headers,\n body: buf,\n });\n } catch (err: unknown) {\n if (err instanceof Error) {\n ctx.context.logger.error(`Webhook Error: ${err.message}`);\n throw new APIError(\"BAD_REQUEST\", {\n message: `Webhook Error: ${err.message}`,\n });\n }\n\n throw new APIError(\"BAD_REQUEST\", {\n message: `Webhook Error: ${err}`,\n });\n }\n\n try {\n await handleWebhookPayload(event, options);\n } catch (e: unknown) {\n if (e instanceof Error) {\n ctx.context.logger.error(\n `DodoPayments webhook failed. Error: ${e.message}`,\n );\n }\n\n ctx.context.logger.error(\n `DodoPayments webhook failed. Error: ${e}`,\n );\n\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Webhook error: See server logs for more information.\",\n });\n }\n\n return ctx.json({ received: true });\n },\n ),\n };\n };\n"],"mappings":";AACA;AAAA,EACE;AAAA,OAEK;AACP,SAAS,UAAU,0BAA0B;AAE7C,SAAS,4BAA4B;AAG9B,IAAM,WACX,CAAC,YAAkC,CAAC,kBAAgC;AAClE,SAAO;AAAA,IACL,sBAAsB;AAAA,MACpB;AAAA,MACA;AAAA,QACE,QAAQ;AAAA,QACR,UAAU;AAAA,UACR,UAAU;AAAA,QACZ;AAAA,QACA,cAAc;AAAA,MAChB;AAAA,MACA,OAAO,QAAkC;AACvC,cAAM,EAAE,WAAW,IAAI;AAEvB,YAAI,CAAC,IAAI,SAAS,MAAM;AACtB,gBAAM,IAAI,SAAS,uBAAuB;AAAA,QAC5C;AACA,cAAM,MAAM,MAAM,IAAI,QAAQ,KAAK;AACnC,YAAI;AACJ,YAAI;AACF,cAAI,CAAC,YAAY;AACf,kBAAM,IAAI,SAAS,yBAAyB;AAAA,cAC1C,SAAS;AAAA,YACX,CAAC;AAAA,UACH;AAEA,gBAAM,UAAU;AAAA,YACd,cAAc,IAAI,QAAQ,QAAQ,IAAI,YAAY;AAAA,YAClD,qBAAqB,IAAI,QAAQ,QAAQ;AAAA,cACvC;AAAA,YACF;AAAA,YACA,qBAAqB,IAAI,QAAQ,QAAQ;AAAA,cACvC;AAAA,YACF;AAAA,UACF;AAEA,kBAAQ,MAAM,qBAAqB;AAAA,YACjC;AAAA,YACA;AAAA,YACA,MAAM;AAAA,UACR,CAAC;AAAA,QACH,SAAS,KAAc;AACrB,cAAI,eAAe,OAAO;AACxB,gBAAI,QAAQ,OAAO,MAAM,kBAAkB,IAAI,OAAO,EAAE;AACxD,kBAAM,IAAI,SAAS,eAAe;AAAA,cAChC,SAAS,kBAAkB,IAAI,OAAO;AAAA,YACxC,CAAC;AAAA,UACH;AAEA,gBAAM,IAAI,SAAS,eAAe;AAAA,YAChC,SAAS,kBAAkB,GAAG;AAAA,UAChC,CAAC;AAAA,QACH;AAEA,YAAI;AACF,gBAAM,qBAAqB,OAAO,OAAO;AAAA,QAC3C,SAAS,GAAY;AACnB,cAAI,aAAa,OAAO;AACtB,gBAAI,QAAQ,OAAO;AAAA,cACjB,uCAAuC,EAAE,OAAO;AAAA,YAClD;AAAA,UACF;AAEA,cAAI,QAAQ,OAAO;AAAA,YACjB,uCAAuC,CAAC;AAAA,UAC1C;AAEA,gBAAM,IAAI,SAAS,eAAe;AAAA,YAChC,SAAS;AAAA,UACX,CAAC;AAAA,QACH;AAEA,eAAO,IAAI,KAAK,EAAE,UAAU,KAAK,CAAC;AAAA,MACpC;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
// src/plugins/portal.ts
|
|
2
|
+
import { APIError } from "better-auth/api";
|
|
3
|
+
import { sessionMiddleware } from "better-auth/api";
|
|
4
|
+
import { createAuthEndpoint } from "better-auth/plugins";
|
|
5
|
+
import { z } from "zod/v3";
|
|
6
|
+
var portal = () => (dodopayments) => {
|
|
7
|
+
return {
|
|
8
|
+
dodoPortal: createAuthEndpoint(
|
|
9
|
+
"/dodopayments/customer/portal",
|
|
10
|
+
{
|
|
11
|
+
method: "GET",
|
|
12
|
+
use: [sessionMiddleware]
|
|
13
|
+
},
|
|
14
|
+
async (ctx) => {
|
|
15
|
+
if (!ctx.context.session?.user.id) {
|
|
16
|
+
throw new APIError("BAD_REQUEST", {
|
|
17
|
+
message: "User not found"
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
if (!ctx.context.session?.user.emailVerified) {
|
|
21
|
+
throw new APIError("UNAUTHORIZED", {
|
|
22
|
+
message: "User email not verified"
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
try {
|
|
26
|
+
const customers = await dodopayments.customers.list({
|
|
27
|
+
email: ctx.context.session?.user.email
|
|
28
|
+
});
|
|
29
|
+
let customer = customers.items[0];
|
|
30
|
+
if (!customer) {
|
|
31
|
+
customer = await createCustomer(
|
|
32
|
+
dodopayments,
|
|
33
|
+
ctx.context.session.user.email,
|
|
34
|
+
ctx.context.session.user.name
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
const customerSession = await dodopayments.customers.customerPortal.create(
|
|
38
|
+
customer.customer_id
|
|
39
|
+
);
|
|
40
|
+
return ctx.json({
|
|
41
|
+
url: customerSession.link,
|
|
42
|
+
redirect: true
|
|
43
|
+
});
|
|
44
|
+
} catch (e) {
|
|
45
|
+
if (e instanceof Error) {
|
|
46
|
+
ctx.context.logger.error(
|
|
47
|
+
`DodoPayments customer portal creation failed. Error: ${e.message}`
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
throw new APIError("INTERNAL_SERVER_ERROR", {
|
|
51
|
+
message: "Customer portal creation failed"
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
),
|
|
56
|
+
dodoSubscriptions: createAuthEndpoint(
|
|
57
|
+
"/dodopayments/customer/subscriptions/list",
|
|
58
|
+
{
|
|
59
|
+
method: "GET",
|
|
60
|
+
query: z.object({
|
|
61
|
+
page: z.coerce.number().optional(),
|
|
62
|
+
limit: z.coerce.number().optional(),
|
|
63
|
+
status: z.enum([
|
|
64
|
+
"active",
|
|
65
|
+
"cancelled",
|
|
66
|
+
"on_hold",
|
|
67
|
+
"pending",
|
|
68
|
+
"failed",
|
|
69
|
+
"expired"
|
|
70
|
+
]).optional()
|
|
71
|
+
}).optional(),
|
|
72
|
+
use: [sessionMiddleware]
|
|
73
|
+
},
|
|
74
|
+
async (ctx) => {
|
|
75
|
+
if (!ctx.context.session.user.id) {
|
|
76
|
+
throw new APIError("BAD_REQUEST", {
|
|
77
|
+
message: "User not found"
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
if (!ctx.context.session?.user.emailVerified) {
|
|
81
|
+
throw new APIError("UNAUTHORIZED", {
|
|
82
|
+
message: "User email not verified"
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
try {
|
|
86
|
+
const customers = await dodopayments.customers.list({
|
|
87
|
+
email: ctx.context.session?.user.email
|
|
88
|
+
});
|
|
89
|
+
let customer = customers.items[0];
|
|
90
|
+
if (!customer) {
|
|
91
|
+
customer = await createCustomer(
|
|
92
|
+
dodopayments,
|
|
93
|
+
ctx.context.session.user.email,
|
|
94
|
+
ctx.context.session.user.name
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
const subscriptions = await dodopayments.subscriptions.list({
|
|
98
|
+
customer_id: customer.customer_id,
|
|
99
|
+
// page number is 0-indexed
|
|
100
|
+
page_number: ctx.query?.page ? ctx.query.page - 1 : void 0,
|
|
101
|
+
page_size: ctx.query?.limit,
|
|
102
|
+
status: ctx.query?.status
|
|
103
|
+
});
|
|
104
|
+
return ctx.json({ items: subscriptions.items });
|
|
105
|
+
} catch (e) {
|
|
106
|
+
if (e instanceof Error) {
|
|
107
|
+
ctx.context.logger.error(
|
|
108
|
+
`DodoPayments subscriptions list failed. Error: ${e.message}`
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
throw new APIError("INTERNAL_SERVER_ERROR", {
|
|
112
|
+
message: "DodoPayments subscriptions list failed"
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
),
|
|
117
|
+
dodoPayments: createAuthEndpoint(
|
|
118
|
+
"/dodopayments/customer/payments/list",
|
|
119
|
+
{
|
|
120
|
+
method: "GET",
|
|
121
|
+
query: z.object({
|
|
122
|
+
page: z.coerce.number().optional(),
|
|
123
|
+
limit: z.coerce.number().optional(),
|
|
124
|
+
status: z.enum([
|
|
125
|
+
"succeeded",
|
|
126
|
+
"failed",
|
|
127
|
+
"cancelled",
|
|
128
|
+
"processing",
|
|
129
|
+
"requires_customer_action",
|
|
130
|
+
"requires_merchant_action",
|
|
131
|
+
"requires_payment_method",
|
|
132
|
+
"requires_confirmation",
|
|
133
|
+
"requires_capture",
|
|
134
|
+
"partially_captured",
|
|
135
|
+
"partially_captured_and_capturable"
|
|
136
|
+
]).optional()
|
|
137
|
+
}).optional(),
|
|
138
|
+
use: [sessionMiddleware]
|
|
139
|
+
},
|
|
140
|
+
async (ctx) => {
|
|
141
|
+
if (!ctx.context.session.user.id) {
|
|
142
|
+
throw new APIError("BAD_REQUEST", {
|
|
143
|
+
message: "User not found"
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
if (!ctx.context.session?.user.emailVerified) {
|
|
147
|
+
throw new APIError("UNAUTHORIZED", {
|
|
148
|
+
message: "User email not verified"
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
try {
|
|
152
|
+
const customers = await dodopayments.customers.list({
|
|
153
|
+
email: ctx.context.session?.user.email
|
|
154
|
+
});
|
|
155
|
+
let customer = customers.items[0];
|
|
156
|
+
if (!customer) {
|
|
157
|
+
customer = await createCustomer(
|
|
158
|
+
dodopayments,
|
|
159
|
+
ctx.context.session.user.email,
|
|
160
|
+
ctx.context.session.user.name
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
const payments = await dodopayments.payments.list({
|
|
164
|
+
customer_id: customer.customer_id,
|
|
165
|
+
// page number is 0-indexed
|
|
166
|
+
page_number: ctx.query?.page ? ctx.query.page - 1 : void 0,
|
|
167
|
+
page_size: ctx.query?.limit,
|
|
168
|
+
status: ctx.query?.status
|
|
169
|
+
});
|
|
170
|
+
return ctx.json({ items: payments.items });
|
|
171
|
+
} catch (e) {
|
|
172
|
+
if (e instanceof Error) {
|
|
173
|
+
ctx.context.logger.error(
|
|
174
|
+
`DodoPayments orders list failed. Error: ${e.message}`
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
throw new APIError("INTERNAL_SERVER_ERROR", {
|
|
178
|
+
message: "Orders list failed"
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
)
|
|
183
|
+
};
|
|
184
|
+
};
|
|
185
|
+
async function createCustomer(dodopayments, email, name) {
|
|
186
|
+
const customer = await dodopayments.customers.create({
|
|
187
|
+
email,
|
|
188
|
+
name
|
|
189
|
+
});
|
|
190
|
+
return customer;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export {
|
|
194
|
+
portal
|
|
195
|
+
};
|
|
196
|
+
//# sourceMappingURL=chunk-J55PDPLE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/plugins/portal.ts"],"sourcesContent":["import type { DodoPayments } from \"dodopayments\";\nimport { APIError } from \"better-auth/api\";\nimport { sessionMiddleware } from \"better-auth/api\";\nimport { createAuthEndpoint } from \"better-auth/plugins\";\nimport { z } from \"zod/v3\";\nimport {\n CustomerPortalResponse,\n PaymentItems,\n SubscriptionItems,\n} from \"../types\";\n\nexport const portal = () => (dodopayments: DodoPayments) => {\n return {\n dodoPortal: createAuthEndpoint(\n \"/dodopayments/customer/portal\",\n {\n method: \"GET\",\n use: [sessionMiddleware],\n },\n async (ctx): Promise<CustomerPortalResponse> => {\n if (!ctx.context.session?.user.id) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"User not found\",\n });\n }\n\n if (!ctx.context.session?.user.emailVerified) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: \"User email not verified\",\n });\n }\n\n try {\n const customers = await dodopayments.customers.list({\n email: ctx.context.session?.user.email,\n });\n let customer = customers.items[0];\n\n if (!customer) {\n // upsert the customer, if they don't exist in DodoPayments\n customer = await createCustomer(\n dodopayments,\n ctx.context.session.user.email,\n ctx.context.session.user.name,\n );\n }\n\n const customerSession =\n await dodopayments.customers.customerPortal.create(\n customer.customer_id,\n );\n\n return ctx.json({\n url: customerSession.link,\n redirect: true,\n });\n } catch (e: unknown) {\n if (e instanceof Error) {\n ctx.context.logger.error(\n `DodoPayments customer portal creation failed. Error: ${e.message}`,\n );\n }\n\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: \"Customer portal creation failed\",\n });\n }\n },\n ),\n dodoSubscriptions: createAuthEndpoint(\n \"/dodopayments/customer/subscriptions/list\",\n {\n method: \"GET\",\n query: z\n .object({\n page: z.coerce.number().optional(),\n limit: z.coerce.number().optional(),\n status: z\n .enum([\n \"active\",\n \"cancelled\",\n \"on_hold\",\n \"pending\",\n \"failed\",\n \"expired\",\n ])\n .optional(),\n })\n .optional(),\n use: [sessionMiddleware],\n },\n async (ctx): Promise<SubscriptionItems> => {\n if (!ctx.context.session.user.id) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"User not found\",\n });\n }\n\n if (!ctx.context.session?.user.emailVerified) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: \"User email not verified\",\n });\n }\n\n try {\n const customers = await dodopayments.customers.list({\n email: ctx.context.session?.user.email,\n });\n let customer = customers.items[0];\n\n if (!customer) {\n // upsert the customer, if they don't exist in DodoPayments\n customer = await createCustomer(\n dodopayments,\n ctx.context.session.user.email,\n ctx.context.session.user.name,\n );\n }\n\n const subscriptions = await dodopayments.subscriptions.list({\n customer_id: customer.customer_id,\n // page number is 0-indexed\n page_number: ctx.query?.page ? ctx.query.page - 1 : undefined,\n page_size: ctx.query?.limit,\n status: ctx.query?.status,\n });\n\n return ctx.json({ items: subscriptions.items });\n } catch (e: unknown) {\n if (e instanceof Error) {\n ctx.context.logger.error(\n `DodoPayments subscriptions list failed. Error: ${e.message}`,\n );\n }\n\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: \"DodoPayments subscriptions list failed\",\n });\n }\n },\n ),\n dodoPayments: createAuthEndpoint(\n \"/dodopayments/customer/payments/list\",\n {\n method: \"GET\",\n query: z\n .object({\n page: z.coerce.number().optional(),\n limit: z.coerce.number().optional(),\n status: z\n .enum([\n \"succeeded\",\n \"failed\",\n \"cancelled\",\n \"processing\",\n \"requires_customer_action\",\n \"requires_merchant_action\",\n \"requires_payment_method\",\n \"requires_confirmation\",\n \"requires_capture\",\n \"partially_captured\",\n \"partially_captured_and_capturable\",\n ])\n .optional(),\n })\n .optional(),\n use: [sessionMiddleware],\n },\n async (ctx): Promise<PaymentItems> => {\n if (!ctx.context.session.user.id) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"User not found\",\n });\n }\n\n if (!ctx.context.session?.user.emailVerified) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: \"User email not verified\",\n });\n }\n\n try {\n const customers = await dodopayments.customers.list({\n email: ctx.context.session?.user.email,\n });\n let customer = customers.items[0];\n\n if (!customer) {\n // upsert the customer, if they don't exist in DodoPayments\n customer = await createCustomer(\n dodopayments,\n ctx.context.session.user.email,\n ctx.context.session.user.name,\n );\n }\n\n const payments = await dodopayments.payments.list({\n customer_id: customer.customer_id,\n // page number is 0-indexed\n page_number: ctx.query?.page ? ctx.query.page - 1 : undefined,\n page_size: ctx.query?.limit,\n status: ctx.query?.status,\n });\n\n return ctx.json({ items: payments.items });\n } catch (e: unknown) {\n if (e instanceof Error) {\n ctx.context.logger.error(\n `DodoPayments orders list failed. Error: ${e.message}`,\n );\n }\n\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: \"Orders list failed\",\n });\n }\n },\n ),\n };\n};\n\nasync function createCustomer(\n dodopayments: DodoPayments,\n email: string,\n name: string,\n) {\n const customer = await dodopayments.customers.create({\n email,\n name,\n });\n\n return customer;\n}\n"],"mappings":";AACA,SAAS,gBAAgB;AACzB,SAAS,yBAAyB;AAClC,SAAS,0BAA0B;AACnC,SAAS,SAAS;AAOX,IAAM,SAAS,MAAM,CAAC,iBAA+B;AAC1D,SAAO;AAAA,IACL,YAAY;AAAA,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AAW,IAAI,OAAO;AAAA,YACtB,QAAQ,IAAI,OAAO;AAAA,UACrB,CAAC;AAED,iBAAO,IAAI,KAAK,EAAE,OAAO,SAAS,MAAM,CAAC;AAAA,QAC3C,SAAS,GAAY;AACnB,cAAI,aAAa,OAAO;AACtB,gBAAI,QAAQ,OAAO;AAAA,cACjB,2CAA2C,EAAE,OAAO;AAAA,YACtD;AAAA,UACF;AAEA,gBAAM,IAAI,SAAS,yBAAyB;AAAA,YAC1C,SAAS;AAAA,UACX,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAEA,eAAe,eACb,cACA,OACA,MACA;AACA,QAAM,WAAW,MAAM,aAAa,UAAU,OAAO;AAAA,IACnD;AAAA,IACA;AAAA,EACF,CAAC;AAED,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// src/plugins/checkout.ts
|
|
2
|
+
import { APIError, getSessionFromCtx } from "better-auth/api";
|
|
3
|
+
import { createAuthEndpoint } from "better-auth/plugins";
|
|
4
|
+
import { z } from "zod/v3";
|
|
5
|
+
import {
|
|
6
|
+
buildCheckoutUrl,
|
|
7
|
+
checkoutSessionPayloadSchema,
|
|
8
|
+
dynamicCheckoutBodySchema
|
|
9
|
+
} from "@dodopayments/core/checkout";
|
|
10
|
+
var checkout = (checkoutOptions = {}) => (dodopayments) => {
|
|
11
|
+
return {
|
|
12
|
+
/**
|
|
13
|
+
* @deprecated
|
|
14
|
+
*/
|
|
15
|
+
dodoCheckout: createAuthEndpoint(
|
|
16
|
+
"/dodopayments/checkout",
|
|
17
|
+
{
|
|
18
|
+
method: "POST",
|
|
19
|
+
body: dynamicCheckoutBodySchema.extend({
|
|
20
|
+
slug: z.string().optional(),
|
|
21
|
+
referenceId: z.string().optional()
|
|
22
|
+
}),
|
|
23
|
+
requireRequest: true
|
|
24
|
+
},
|
|
25
|
+
async (ctx) => {
|
|
26
|
+
const session = await getSessionFromCtx(ctx);
|
|
27
|
+
let dodoPaymentsProductId;
|
|
28
|
+
if (ctx.body?.slug) {
|
|
29
|
+
const resolvedProducts = typeof checkoutOptions.products === "function" ? await checkoutOptions.products() : checkoutOptions.products;
|
|
30
|
+
const productId = resolvedProducts?.find(
|
|
31
|
+
(product) => product.slug === ctx.body.slug
|
|
32
|
+
)?.productId;
|
|
33
|
+
if (!productId) {
|
|
34
|
+
throw new APIError("BAD_REQUEST", {
|
|
35
|
+
message: "Product not found"
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
dodoPaymentsProductId = productId;
|
|
39
|
+
} else {
|
|
40
|
+
dodoPaymentsProductId = ctx.body.product_id;
|
|
41
|
+
}
|
|
42
|
+
if (checkoutOptions.authenticatedUsersOnly && !session?.user.id) {
|
|
43
|
+
throw new APIError("UNAUTHORIZED", {
|
|
44
|
+
message: "You must be logged in to checkout"
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
try {
|
|
48
|
+
const checkoutUrl = await buildCheckoutUrl({
|
|
49
|
+
body: {
|
|
50
|
+
...ctx.body,
|
|
51
|
+
product_id: dodoPaymentsProductId,
|
|
52
|
+
customer: {
|
|
53
|
+
email: session?.user.email,
|
|
54
|
+
name: session?.user.name,
|
|
55
|
+
...ctx.body.customer
|
|
56
|
+
},
|
|
57
|
+
product_cart: dodoPaymentsProductId ? [
|
|
58
|
+
{
|
|
59
|
+
product_id: dodoPaymentsProductId,
|
|
60
|
+
quantity: 1
|
|
61
|
+
}
|
|
62
|
+
] : void 0,
|
|
63
|
+
metadata: ctx.body.referenceId ? {
|
|
64
|
+
referenceId: ctx.body.referenceId,
|
|
65
|
+
...ctx.body.metadata
|
|
66
|
+
} : ctx.body.metadata
|
|
67
|
+
},
|
|
68
|
+
bearerToken: dodopayments.bearerToken,
|
|
69
|
+
environment: dodopayments.baseURL.includes("test") ? "test_mode" : "live_mode",
|
|
70
|
+
returnUrl: checkoutOptions.successUrl ? new URL(
|
|
71
|
+
checkoutOptions.successUrl,
|
|
72
|
+
ctx.request?.url
|
|
73
|
+
).toString() : void 0,
|
|
74
|
+
type: "dynamic"
|
|
75
|
+
});
|
|
76
|
+
const redirectUrl = new URL(checkoutUrl);
|
|
77
|
+
return ctx.json({
|
|
78
|
+
url: redirectUrl.toString(),
|
|
79
|
+
redirect: true
|
|
80
|
+
});
|
|
81
|
+
} catch (e) {
|
|
82
|
+
if (e instanceof Error) {
|
|
83
|
+
ctx.context.logger.error(
|
|
84
|
+
`DodoPayments checkout creation failed. Error: ${e.message}`
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
throw new APIError("INTERNAL_SERVER_ERROR", {
|
|
88
|
+
message: "Checkout creation failed"
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
),
|
|
93
|
+
dodoCheckoutSession: createAuthEndpoint(
|
|
94
|
+
"/dodopayments/checkout-session",
|
|
95
|
+
{
|
|
96
|
+
method: "POST",
|
|
97
|
+
body: checkoutSessionPayloadSchema.extend({
|
|
98
|
+
slug: z.string().optional(),
|
|
99
|
+
referenceId: z.string().optional()
|
|
100
|
+
}).partial({
|
|
101
|
+
product_cart: true
|
|
102
|
+
}),
|
|
103
|
+
requireRequest: true
|
|
104
|
+
},
|
|
105
|
+
async (ctx) => {
|
|
106
|
+
const session = await getSessionFromCtx(ctx);
|
|
107
|
+
let dodoPaymentsProductId;
|
|
108
|
+
if (ctx.body?.slug) {
|
|
109
|
+
const resolvedProducts = typeof checkoutOptions.products === "function" ? await checkoutOptions.products() : checkoutOptions.products;
|
|
110
|
+
const productId = resolvedProducts?.find(
|
|
111
|
+
(product) => product.slug === ctx.body.slug
|
|
112
|
+
)?.productId;
|
|
113
|
+
if (!productId) {
|
|
114
|
+
throw new APIError("BAD_REQUEST", {
|
|
115
|
+
message: "Product not found"
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
dodoPaymentsProductId = productId;
|
|
119
|
+
}
|
|
120
|
+
if (checkoutOptions.authenticatedUsersOnly && !session?.user.id) {
|
|
121
|
+
throw new APIError("UNAUTHORIZED", {
|
|
122
|
+
message: "You must be logged in to checkout"
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
const product_cart = dodoPaymentsProductId ? [{ product_id: dodoPaymentsProductId, quantity: 1 }] : ctx.body.product_cart;
|
|
126
|
+
if (!product_cart || product_cart.length === 0) {
|
|
127
|
+
throw new APIError("BAD_REQUEST", {
|
|
128
|
+
message: "Neither product_cart nor slug was provided"
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
try {
|
|
132
|
+
const checkoutUrl = await buildCheckoutUrl({
|
|
133
|
+
sessionPayload: {
|
|
134
|
+
...ctx.body,
|
|
135
|
+
product_cart,
|
|
136
|
+
customer: {
|
|
137
|
+
email: session?.user.email,
|
|
138
|
+
name: session?.user.name,
|
|
139
|
+
...ctx.body.customer
|
|
140
|
+
},
|
|
141
|
+
metadata: ctx.body.referenceId ? {
|
|
142
|
+
referenceId: ctx.body.referenceId,
|
|
143
|
+
...ctx.body.metadata
|
|
144
|
+
} : ctx.body.metadata,
|
|
145
|
+
return_url: checkoutOptions.successUrl ? new URL(
|
|
146
|
+
checkoutOptions.successUrl,
|
|
147
|
+
ctx.request?.url
|
|
148
|
+
).toString() : void 0
|
|
149
|
+
},
|
|
150
|
+
bearerToken: dodopayments.bearerToken,
|
|
151
|
+
environment: dodopayments.baseURL.includes("test") ? "test_mode" : "live_mode",
|
|
152
|
+
type: "session"
|
|
153
|
+
});
|
|
154
|
+
const redirectUrl = new URL(checkoutUrl);
|
|
155
|
+
return ctx.json({
|
|
156
|
+
url: redirectUrl.toString(),
|
|
157
|
+
redirect: true
|
|
158
|
+
});
|
|
159
|
+
} catch (e) {
|
|
160
|
+
if (e instanceof Error) {
|
|
161
|
+
ctx.context.logger.error(
|
|
162
|
+
`DodoPayments checkout creation failed. Error: ${e.message}`
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
throw new APIError("INTERNAL_SERVER_ERROR", {
|
|
166
|
+
message: "Checkout session creation failed"
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
)
|
|
171
|
+
};
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
export {
|
|
175
|
+
checkout
|
|
176
|
+
};
|
|
177
|
+
//# sourceMappingURL=chunk-O3BTJOIO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/plugins/checkout.ts"],"sourcesContent":["import type DodoPayments from \"dodopayments\";\nimport { APIError, getSessionFromCtx } from \"better-auth/api\";\nimport { createAuthEndpoint } from \"better-auth/plugins\";\nimport { z } from \"zod/v3\";\nimport type { CreateCheckoutResponse, Product } from \"../types\";\nimport {\n buildCheckoutUrl,\n checkoutSessionPayloadSchema,\n dynamicCheckoutBodySchema,\n} from \"@dodopayments/core/checkout\";\n\nexport interface CheckoutOptions {\n /**\n * Optional list of slug -> productId mappings for easy slug checkouts\n */\n products?: Product[] | (() => Promise<Product[]>);\n /**\n * Checkout Success URL\n */\n successUrl?: string;\n /**\n * Only allow authenticated customers to checkout\n */\n authenticatedUsersOnly?: boolean;\n}\n\nexport const checkout =\n (checkoutOptions: CheckoutOptions = {}) =>\n (dodopayments: DodoPayments) => {\n return {\n /**\n * @deprecated\n */\n dodoCheckout: createAuthEndpoint(\n \"/dodopayments/checkout\",\n {\n method: \"POST\",\n body: dynamicCheckoutBodySchema.extend({\n slug: z.string().optional(),\n referenceId: z.string().optional(),\n }),\n requireRequest: true,\n },\n async (ctx): Promise<CreateCheckoutResponse> => {\n const session = await getSessionFromCtx(ctx);\n\n let dodoPaymentsProductId: string | undefined;\n\n if (ctx.body?.slug) {\n const resolvedProducts =\n typeof checkoutOptions.products === \"function\"\n ? await checkoutOptions.products()\n : checkoutOptions.products;\n\n const productId = resolvedProducts?.find(\n (product) => product.slug === ctx.body.slug,\n )?.productId;\n\n if (!productId) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Product not found\",\n });\n }\n\n dodoPaymentsProductId = productId;\n } else {\n dodoPaymentsProductId = ctx.body.product_id;\n }\n\n if (checkoutOptions.authenticatedUsersOnly && !session?.user.id) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: \"You must be logged in to checkout\",\n });\n }\n\n try {\n const checkoutUrl = await buildCheckoutUrl({\n body: {\n ...ctx.body,\n product_id: dodoPaymentsProductId,\n customer: {\n email: session?.user.email,\n name: session?.user.name,\n ...ctx.body.customer,\n },\n product_cart: dodoPaymentsProductId\n ? [\n {\n product_id: dodoPaymentsProductId,\n quantity: 1,\n },\n ]\n : undefined,\n metadata: ctx.body.referenceId\n ? {\n referenceId: ctx.body.referenceId,\n ...ctx.body.metadata,\n }\n : ctx.body.metadata,\n },\n bearerToken: dodopayments.bearerToken,\n environment: dodopayments.baseURL.includes(\"test\")\n ? \"test_mode\"\n : \"live_mode\",\n returnUrl: checkoutOptions.successUrl\n ? new URL(\n checkoutOptions.successUrl,\n ctx.request?.url,\n ).toString()\n : undefined,\n type: \"dynamic\",\n });\n\n const redirectUrl = new URL(checkoutUrl);\n\n return ctx.json({\n url: redirectUrl.toString(),\n redirect: true,\n });\n } catch (e: unknown) {\n if (e instanceof Error) {\n ctx.context.logger.error(\n `DodoPayments checkout creation failed. Error: ${e.message}`,\n );\n }\n\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: \"Checkout creation failed\",\n });\n }\n },\n ),\n dodoCheckoutSession: createAuthEndpoint(\n \"/dodopayments/checkout-session\",\n {\n method: \"POST\",\n body: checkoutSessionPayloadSchema\n .extend({\n slug: z.string().optional(),\n referenceId: z.string().optional(),\n })\n .partial({\n product_cart: true,\n }),\n requireRequest: true,\n },\n async (ctx): Promise<CreateCheckoutResponse> => {\n const session = await getSessionFromCtx(ctx);\n\n let dodoPaymentsProductId: string | undefined;\n\n if (ctx.body?.slug) {\n const resolvedProducts =\n typeof checkoutOptions.products === \"function\"\n ? await checkoutOptions.products()\n : checkoutOptions.products;\n\n const productId = resolvedProducts?.find(\n (product) => product.slug === ctx.body.slug,\n )?.productId;\n\n if (!productId) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Product not found\",\n });\n }\n\n dodoPaymentsProductId = productId;\n }\n\n if (checkoutOptions.authenticatedUsersOnly && !session?.user.id) {\n throw new APIError(\"UNAUTHORIZED\", {\n message: \"You must be logged in to checkout\",\n });\n }\n\n // Ensure we have a product_cart\n const product_cart = dodoPaymentsProductId\n ? [{ product_id: dodoPaymentsProductId, quantity: 1 }]\n : ctx.body.product_cart;\n\n if (!product_cart || product_cart.length === 0) {\n throw new APIError(\"BAD_REQUEST\", {\n message: \"Neither product_cart nor slug was provided\",\n });\n }\n\n try {\n const checkoutUrl = await buildCheckoutUrl({\n sessionPayload: {\n ...ctx.body,\n product_cart,\n customer: {\n email: session?.user.email,\n name: session?.user.name,\n ...ctx.body.customer,\n },\n metadata: ctx.body.referenceId\n ? {\n referenceId: ctx.body.referenceId,\n ...ctx.body.metadata,\n }\n : ctx.body.metadata,\n return_url: checkoutOptions.successUrl\n ? new URL(\n checkoutOptions.successUrl,\n ctx.request?.url,\n ).toString()\n : undefined,\n },\n bearerToken: dodopayments.bearerToken,\n environment: dodopayments.baseURL.includes(\"test\")\n ? \"test_mode\"\n : \"live_mode\",\n type: \"session\",\n });\n\n const redirectUrl = new URL(checkoutUrl);\n\n return ctx.json({\n url: redirectUrl.toString(),\n redirect: true,\n });\n } catch (e: unknown) {\n if (e instanceof Error) {\n ctx.context.logger.error(\n `DodoPayments checkout creation failed. Error: ${e.message}`,\n );\n }\n\n throw new APIError(\"INTERNAL_SERVER_ERROR\", {\n message: \"Checkout session creation failed\",\n });\n }\n },\n ),\n };\n };\n"],"mappings":";AACA,SAAS,UAAU,yBAAyB;AAC5C,SAAS,0BAA0B;AACnC,SAAS,SAAS;AAElB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAiBA,IAAM,WACX,CAAC,kBAAmC,CAAC,MACrC,CAAC,iBAA+B;AAC9B,SAAO;AAAA;AAA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iD,EAAE,OAAO;AAAA,YAC5D;AAAA,UACF;AAEA,gBAAM,IAAI,SAAS,yBAAyB;AAAA,YAC1C,SAAS;AAAA,UACX,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client.ts"],"sourcesContent":["import type { BetterAuthClientPlugin } from \"better-auth\";\nimport type { dodopayments } from \"./index\";\n\nexport const dodopaymentsClient = () => {\n return {\n id: \"dodopayments-client\",\n $InferServerPlugin: {} as ReturnType<typeof dodopayments>,\n } satisfies BetterAuthClientPlugin;\n};\n"],"mappings":";AAGO,IAAM,qBAAqB,MAAM;AACtC,SAAO;AAAA,IACL,IAAI;AAAA,IACJ,oBAAoB,CAAC;AAAA,EACvB;AACF;","names":[]}
|
package/dist/client.cjs
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
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/client.ts
|
|
21
|
+
var client_exports = {};
|
|
22
|
+
__export(client_exports, {
|
|
23
|
+
dodopaymentsClient: () => dodopaymentsClient
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(client_exports);
|
|
26
|
+
var dodopaymentsClient = () => {
|
|
27
|
+
return {
|
|
28
|
+
id: "dodopayments-client",
|
|
29
|
+
$InferServerPlugin: {}
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
33
|
+
0 && (module.exports = {
|
|
34
|
+
dodopaymentsClient
|
|
35
|
+
});
|
|
36
|
+
//# sourceMappingURL=client.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client.ts"],"sourcesContent":["import type { BetterAuthClientPlugin } from \"better-auth\";\nimport type { dodopayments } from \"./index\";\n\nexport const dodopaymentsClient = () => {\n return {\n id: \"dodopayments-client\",\n $InferServerPlugin: {} as ReturnType<typeof dodopayments>,\n } satisfies BetterAuthClientPlugin;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAGO,IAAM,qBAAqB,MAAM;AACtC,SAAO;AAAA,IACL,IAAI;AAAA,IACJ,oBAAoB,CAAC;AAAA,EACvB;AACF;","names":[]}
|