Module: StripeMock::RequestHandlers::Subscriptions

Included in:
Instance
Defined in:
lib/stripe_mock/request_handlers/subscriptions.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/stripe_mock/request_handlers/subscriptions.rb', line 5

def Subscriptions.included(klass)
  klass.add_handler 'get /v1/subscriptions', :retrieve_subscriptions
  klass.add_handler 'post /v1/subscriptions', :create_subscription
  klass.add_handler 'get /v1/subscriptions/(.*)', :retrieve_subscription
  klass.add_handler 'post /v1/subscriptions/(.*)', :update_subscription
  klass.add_handler 'delete /v1/subscriptions/(.*)', :cancel_subscription

  klass.add_handler 'post /v1/customers/(.*)/subscription(?:s)?', :create_customer_subscription
  klass.add_handler 'get /v1/customers/(.*)/subscription(?:s)?/(.*)', :retrieve_customer_subscription
  klass.add_handler 'get /v1/customers/(.*)/subscription(?:s)?', :retrieve_customer_subscriptions
  klass.add_handler 'post /v1/customers/(.*)subscription(?:s)?/(.*)', :update_subscription
  klass.add_handler 'delete /v1/customers/(.*)/subscription(?:s)?/(.*)', :cancel_subscription
end

Instance Method Details

#cancel_subscription(route, method_url, params, headers) ⇒ Object



317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
# File 'lib/stripe_mock/request_handlers/subscriptions.rb', line 317

def cancel_subscription(route, method_url, params, headers)
   = headers && headers[:stripe_account] || Stripe.api_key
  route =~ method_url

  subscription_id = $2 ? $2 : $1
  subscription = assert_existence :subscription, subscription_id, subscriptions[subscription_id]

  customer_id = subscription[:customer]
  customer = assert_existence :customer, customer_id, customers[][customer_id]

  cancel_params = { canceled_at: Time.now.utc.to_i }
  cancelled_at_period_end = (params[:at_period_end] == true)
  if cancelled_at_period_end
    cancel_params[:cancel_at_period_end] = true
  else
    cancel_params[:status] = 'canceled'
    cancel_params[:cancel_at_period_end] = false
    cancel_params[:ended_at] = Time.now.utc.to_i
  end

  subscription.merge!(cancel_params)

  unless cancelled_at_period_end
    delete_subscription_from_customer customer, subscription
  end

  subscription
end

#create_customer_subscription(route, method_url, params, headers) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/stripe_mock/request_handlers/subscriptions.rb', line 37

def create_customer_subscription(route, method_url, params, headers)
   = headers && headers[:stripe_account] || Stripe.api_key
  route =~ method_url

  subscription_plans = get_subscription_plans_from_params(params)
  customer = assert_existence :customer, $1, customers[][$1]

  if params[:source]
    new_card = get_card_by_token(params.delete(:source))
    add_card_to_object(:customer, new_card, customer)
    customer[:default_source] = new_card[:id]
  end

  subscription = Data.mock_subscription({ id: (params[:id] || new_id('su')) })
  subscription = resolve_subscription_changes(subscription, subscription_plans, customer, params)

  # Ensure customer has card to charge if plan has no trial and is not free
  # Note: needs updating for subscriptions with multiple plans
  verify_card_present(customer, subscription_plans.first, subscription, params)

  if params[:coupon]
    coupon_id = params[:coupon]

    # assert_existence returns 404 error code but Stripe returns 400
    # coupon = assert_existence :coupon, coupon_id, coupons[coupon_id]

    coupon = coupons[coupon_id]

    if coupon
      add_coupon_to_object(subscription, coupon)
    else
      raise Stripe::InvalidRequestError.new("No such coupon: #{coupon_id}", 'coupon', http_status: 400)
    end
  end

  if params[:promotion_code]
    promotion_code_id = params[:promotion_code]

    promotion_code = promotion_codes[promotion_code_id]

    unless promotion_code
      raise Stripe::InvalidRequestError.new("No such promotion code: #{promotion_code_id}", 'promotion_code', http_status: 400)
    end
  end

  subscriptions[subscription[:id]] = subscription
  add_subscription_to_customer(customer, subscription)

  subscriptions[subscription[:id]]
end

#create_subscription(route, method_url, params, headers) ⇒ Object



88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/stripe_mock/request_handlers/subscriptions.rb', line 88

def create_subscription(route, method_url, params, headers)
   = headers && headers[:stripe_account] || Stripe.api_key
  if headers && headers[:idempotency_key]
    if subscriptions.any?
      original_subscription = subscriptions.values.find { |c| c[:idempotency_key] == headers[:idempotency_key]}
      return subscriptions[original_subscription[:id]] if original_subscription
    end
  end
  route =~ method_url

  subscription_plans = get_subscription_plans_from_params(params)

  customer = params[:customer]
  customer_id = customer.is_a?(Stripe::Customer) ? customer[:id] : customer.to_s
  customer = assert_existence :customer, customer_id, customers[][customer_id]

  if params[:source]
    new_card = get_card_by_token(params.delete(:source))
    add_card_to_object(:customer, new_card, customer)
    customer[:default_source] = new_card[:id]
  end

  allowed_params = %w(id customer application_fee_percent coupon items metadata plan quantity source tax_percent trial_end trial_period_days current_period_start created prorate billing_cycle_anchor billing days_until_due idempotency_key enable_incomplete_payments cancel_at_period_end default_tax_rates payment_behavior pending_invoice_item_interval default_payment_method collection_method off_session trial_from_plan proration_behavior backdate_start_date transfer_data expand automatic_tax payment_settings trial_settings promotion_code)
  unknown_params = params.keys - allowed_params.map(&:to_sym)
  if unknown_params.length > 0
    raise Stripe::InvalidRequestError.new("Received unknown parameter: #{unknown_params.join}", unknown_params.first.to_s, http_status: 400)
  end

  subscription = Data.mock_subscription({ id: (params[:id] || new_id('su')) })
  subscription = resolve_subscription_changes(subscription, subscription_plans, customer, params)
  if headers[:idempotency_key]
    subscription[:idempotency_key] = headers[:idempotency_key]
  end

  # Ensure customer has card to charge if plan has no trial and is not free
  # Note: needs updating for subscriptions with multiple plans
  verify_card_present(customer, subscription_plans.first, subscription, params)

  if params[:coupon] && params[:promotion_code]
    raise Stripe::InvalidRequestError.new("You may only specify one of these parameters: coupon, promotion_code", "coupon", http_status: 400)
  end

  if params[:coupon]
    coupon_id = params[:coupon]

    # assert_existence returns 404 error code but Stripe returns 400
    # coupon = assert_existence :coupon, coupon_id, coupons[coupon_id]

    coupon = coupons[coupon_id]

    if coupon
      add_coupon_to_object(subscription, coupon)
    else
      raise Stripe::InvalidRequestError.new("No such coupon: #{coupon_id}", 'coupon', http_status: 400)
    end
  end

  if params[:promotion_code]
    promotion_code_id = params[:promotion_code]

    promotion_code = promotion_codes[promotion_code_id]

    unless promotion_code
      raise Stripe::InvalidRequestError.new("No such promotion code: #{promotion_code_id}", 'promotion_code', http_status: 400)
    end
  end

  if params[:trial_period_days]
    subscription[:status] = 'trialing'
  end

  if params[:payment_behavior] == 'default_incomplete'
    subscription[:status] = 'incomplete'
  end

  if params[:cancel_at_period_end]
    subscription[:cancel_at_period_end] = true
    subscription[:canceled_at] = Time.now.utc.to_i
  end

  if params[:transfer_data] && !params[:transfer_data].empty?
    throw Stripe::InvalidRequestError.new(missing_param_message("transfer_data[destination]")) unless params[:transfer_data][:destination]
    subscription[:transfer_data] = params[:transfer_data].dup
    subscription[:transfer_data][:amount_percent] ||= 100
  end

  if (s = params[:expand]&.find { |s| s.start_with? 'latest_invoice' })
    payment_intent = nil
    unless subscription[:status] == 'trialing'
      intent_status = subscription[:status] == 'incomplete' ? 'requires_payment_method' : 'succeeded'
      intent = Data.mock_payment_intent({
        status: intent_status,
        amount: subscription[:plan][:amount],
        currency: subscription[:plan][:currency]
      })
      payment_intent = s.include?('latest_invoice.payment_intent') ? intent : intent.id
    end
    invoice = Data.mock_invoice([], { payment_intent: payment_intent })
    subscription[:latest_invoice] = invoice
  end

  subscriptions[subscription[:id]] = subscription
  add_subscription_to_customer(customer, subscription)

  subscriptions[subscription[:id]]
end

#retrieve_customer_subscription(route, method_url, params, headers) ⇒ Object



19
20
21
22
23
24
25
26
27
# File 'lib/stripe_mock/request_handlers/subscriptions.rb', line 19

def retrieve_customer_subscription(route, method_url, params, headers)
   = headers && headers[:stripe_account] || Stripe.api_key
  route =~ method_url

  customer = assert_existence :customer, $1, customers[][$1]
  subscription = get_customer_subscription(customer, $2)

  assert_existence :subscription, $2, subscription
end

#retrieve_customer_subscriptions(route, method_url, params, headers) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/stripe_mock/request_handlers/subscriptions.rb', line 29

def retrieve_customer_subscriptions(route, method_url, params, headers)
   = headers && headers[:stripe_account] || Stripe.api_key
  route =~ method_url

  customer = assert_existence :customer, $1, customers[][$1]
  customer[:subscriptions]
end

#retrieve_subscription(route, method_url, params, headers) ⇒ Object



195
196
197
198
199
# File 'lib/stripe_mock/request_handlers/subscriptions.rb', line 195

def retrieve_subscription(route, method_url, params, headers)
  route =~ method_url

  assert_existence :subscription, $1, subscriptions[$1]
end

#retrieve_subscriptions(route, method_url, params, headers) ⇒ Object



201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/stripe_mock/request_handlers/subscriptions.rb', line 201

def retrieve_subscriptions(route, method_url, params, headers)
  # stripe_account = headers && headers[:stripe_account] || Stripe.api_key
  route =~ method_url

  subs = subscriptions.values

  case params[:status]
  when nil
    subs = subs.filter {|subscription| subscription[:status] != "canceled"}
  when "all"
    # Include all subscriptions
  else
    subs = subs.filter {|subscription| subscription[:status] == params[:status]}
  end
  if params[:current_period_end]
    subs = filter_by_timestamp(subs, field: :current_period_end, value: params[:current_period_end])
  end
  if params[:current_period_start]
    subs = filter_by_timestamp(subs, field: :current_period_start, value: params[:current_period_start])
  end

  Data.mock_list_object(subs, params)
end

#update_subscription(route, method_url, params, headers) ⇒ Object



225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/stripe_mock/request_handlers/subscriptions.rb', line 225

def update_subscription(route, method_url, params, headers)
   = headers && headers[:stripe_account] || Stripe.api_key
  route =~ method_url

  if params[:billing_cycle_anchor] == 'now'
    params[:billing_cycle_anchor] = Time.now.utc.to_i
  end

  subscription_id = $2 ? $2 : $1
  subscription = assert_existence :subscription, subscription_id, subscriptions[subscription_id]
  verify_active_status(subscription)

  customer_id = subscription[:customer]
  customer = assert_existence :customer, customer_id, customers[][customer_id]

  if params[:source]
    new_card = get_card_by_token(params.delete(:source))
    add_card_to_object(:customer, new_card, customer)
    customer[:default_source] = new_card[:id]
  end

  subscription_plans = get_subscription_plans_from_params(params)

  # subscription plans are not being updated but load them for the response
  if subscription_plans.empty?
    subscription_plans = subscription[:items][:data].map { |item| item[:plan] }
  end

  if params[:coupon]
    coupon_id = params[:coupon]

    # assert_existence returns 404 error code but Stripe returns 400
    # coupon = assert_existence :coupon, coupon_id, coupons[coupon_id]

    coupon = coupons[coupon_id]
    if coupon
      add_coupon_to_object(subscription, coupon)
    elsif coupon_id == ""
      subscription[:discount] = nil
    else
      raise Stripe::InvalidRequestError.new("No such coupon: #{coupon_id}", 'coupon', http_status: 400)
    end
  end

  if params[:promotion_code]
    promotion_code_id = params[:promotion_code]

    promotion_code = promotion_codes[promotion_code_id]

    if promotion_code
      # You can't apply a promotion code with amount restrictions on the Customer object or on a subscription
      # update API call
      if promotion_code[:restrictions][:minimum_amount]
        raise Stripe::InvalidRequestError.new(
          "This promotion code cannot be redeemed on a subcription update because it uses the `minimum_amount` restriction.",
          "promotion_code",
          http_status: 400
        )
      end
    else
      raise Stripe::InvalidRequestError.new("No such promotion code: #{promotion_code_id}", 'promotion_code', http_status: 400)
    end
  end

  if params[:trial_period_days]
    subscription[:status] = 'trialing'
  end

  if params[:cancel_at_period_end]
    subscription[:cancel_at_period_end] = true
    subscription[:canceled_at] = Time.now.utc.to_i
  elsif params.has_key?(:cancel_at_period_end)
    subscription[:cancel_at_period_end] = false
    subscription[:canceled_at] = nil
  end

  params[:current_period_start] = subscription[:current_period_start]
  params[:trial_end] = params[:trial_end] || subscription[:trial_end]

  plan_amount_was = subscription.dig(:plan, :amount)

  subscription = resolve_subscription_changes(subscription, subscription_plans, customer, params)

  verify_card_present(customer, subscription_plans.first, subscription, params) if plan_amount_was == 0 && subscription.dig(:plan, :amount) && subscription.dig(:plan, :amount) > 0

  # delete the old subscription, replace with the new subscription
  customer[:subscriptions][:data].reject! { |sub| sub[:id] == subscription[:id] }
  customer[:subscriptions][:data] << subscription

  subscription
end