UNPKG

@dodopayments/better-auth

Version:

A Better Auth plugin for integrating Dodo Payments into your authentication flow.

64 lines (63 loc) 2.4 kB
import { APIError } from "better-auth/api"; export const onUserCreate = (options) => async (user, ctx) => { if (ctx && options.createCustomerOnSignUp) { try { const customers = await options.client.customers.list({ email: user.email, }); const existingCustomer = customers.items[0]; if (existingCustomer) { if (existingCustomer.email !== user.email) { await options.client.customers.update(existingCustomer.customer_id, { name: user.name, }); } } else { // TODO: Add metadata to customer object via // getCustomerCreateParams option when it becomes // available in the API await options.client.customers.create({ email: user.email, name: user.name, }); } } catch (e) { if (e instanceof Error) { throw new APIError("INTERNAL_SERVER_ERROR", { message: `DodoPayments customer creation failed. Error: ${e.message}`, }); } throw new APIError("INTERNAL_SERVER_ERROR", { message: `DodoPayments customer creation failed. Error: ${e}`, }); } } }; export const onUserUpdate = (options) => async (user, ctx) => { if (ctx && options.createCustomerOnSignUp) { try { const customers = await options.client.customers.list({ email: user.email, }); const existingCustomer = customers.items[0]; if (existingCustomer) { // TODO: Add metadata to customer object via // getCustomerCreateParams option when it becomes // available in the API await options.client.customers.update(existingCustomer.customer_id, { name: user.name, }); } } catch (e) { if (e instanceof Error) { ctx.context.logger.error(`DodoPayments customer update failed. Error: ${e.message}`); } else { ctx.context.logger.error(`DodoPayments customer update failed. Error: ${e}`); } } } };