Module: BetterAuth::Stripe::PluginFactory

Defined in:
lib/better_auth/stripe/plugin_factory.rb

Class Method Summary collapse

Class Method Details

.build(options = {}) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/better_auth/stripe/plugin_factory.rb', line 10

def build(options = {})
  config = BetterAuth::Plugins.normalize_hash(options)
  BetterAuth::Plugin.new(
    id: "stripe",
    version: BetterAuth::Stripe::VERSION,
    init: ->(ctx) { {context: {schema: BetterAuth::Schema.auth_tables(ctx.options)}} },
    schema: BetterAuth::Stripe::Schema.schema(config),
    endpoints: BetterAuth::Stripe::Routes.endpoints(config),
    error_codes: BetterAuth::Stripe::ERROR_CODES,
    options: config.merge(database_hooks: database_hooks(config), organization_hooks: BetterAuth::Stripe::OrganizationHooks.hooks(config))
  )
end

.database_hooks(config) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/better_auth/stripe/plugin_factory.rb', line 23

def database_hooks(config)
  return {} unless config[:create_customer_on_sign_up]

  {
    user: {
      create: {
        before: lambda do |data, hook_ctx|
          next unless data["email"] && !data["stripeCustomerId"]

          data["id"] ||= SecureRandom.hex(16)
          customer = BetterAuth::Plugins.stripe_find_or_create_user_customer(config, data, nil, hook_ctx)
          {data: {id: data["id"], stripeCustomerId: BetterAuth::Stripe::Utils.id(customer)}}
        rescue
          nil
        end
      },
      update: {
        after: lambda do |user, _ctx|
          next unless user && user["stripeCustomerId"]

          customer = BetterAuth::Stripe::Utils.client(config).customers.retrieve(user["stripeCustomerId"])
          next if BetterAuth::Stripe::Utils.fetch(customer, "deleted")
          next if BetterAuth::Stripe::Utils.fetch(customer, "email") == user["email"]

          BetterAuth::Stripe::Utils.client(config).customers.update(user["stripeCustomerId"], email: user["email"])
        rescue
          nil
        end
      }
    }
  }
end