reji 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (68) hide show
  1. checksums.yaml +7 -0
  2. data/.editorconfig +14 -0
  3. data/.gitattributes +4 -0
  4. data/.gitignore +15 -0
  5. data/.travis.yml +28 -0
  6. data/Appraisals +17 -0
  7. data/Gemfile +8 -0
  8. data/Gemfile.lock +133 -0
  9. data/LICENSE +20 -0
  10. data/README.md +1285 -0
  11. data/Rakefile +21 -0
  12. data/app/controllers/reji/payment_controller.rb +31 -0
  13. data/app/controllers/reji/webhook_controller.rb +170 -0
  14. data/app/views/payment.html.erb +228 -0
  15. data/app/views/receipt.html.erb +250 -0
  16. data/bin/setup +12 -0
  17. data/config/routes.rb +6 -0
  18. data/gemfiles/rails_5.0.gemfile +13 -0
  19. data/gemfiles/rails_5.1.gemfile +13 -0
  20. data/gemfiles/rails_5.2.gemfile +13 -0
  21. data/gemfiles/rails_6.0.gemfile +13 -0
  22. data/lib/generators/reji/install/install_generator.rb +69 -0
  23. data/lib/generators/reji/install/templates/db/migrate/add_reji_to_users.rb.erb +16 -0
  24. data/lib/generators/reji/install/templates/db/migrate/create_subscription_items.rb.erb +19 -0
  25. data/lib/generators/reji/install/templates/db/migrate/create_subscriptions.rb.erb +22 -0
  26. data/lib/generators/reji/install/templates/reji.rb +36 -0
  27. data/lib/reji.rb +75 -0
  28. data/lib/reji/billable.rb +13 -0
  29. data/lib/reji/concerns/interacts_with_payment_behavior.rb +33 -0
  30. data/lib/reji/concerns/manages_customer.rb +113 -0
  31. data/lib/reji/concerns/manages_invoices.rb +136 -0
  32. data/lib/reji/concerns/manages_payment_methods.rb +202 -0
  33. data/lib/reji/concerns/manages_subscriptions.rb +91 -0
  34. data/lib/reji/concerns/performs_charges.rb +36 -0
  35. data/lib/reji/concerns/prorates.rb +38 -0
  36. data/lib/reji/configuration.rb +59 -0
  37. data/lib/reji/engine.rb +4 -0
  38. data/lib/reji/errors.rb +66 -0
  39. data/lib/reji/invoice.rb +243 -0
  40. data/lib/reji/invoice_line_item.rb +98 -0
  41. data/lib/reji/payment.rb +61 -0
  42. data/lib/reji/payment_method.rb +32 -0
  43. data/lib/reji/subscription.rb +567 -0
  44. data/lib/reji/subscription_builder.rb +206 -0
  45. data/lib/reji/subscription_item.rb +97 -0
  46. data/lib/reji/tax.rb +48 -0
  47. data/lib/reji/version.rb +5 -0
  48. data/reji.gemspec +32 -0
  49. data/spec/dummy/app/models/user.rb +21 -0
  50. data/spec/dummy/application.rb +53 -0
  51. data/spec/dummy/config/database.yml +11 -0
  52. data/spec/dummy/db/schema.rb +40 -0
  53. data/spec/feature/charges_spec.rb +67 -0
  54. data/spec/feature/customer_spec.rb +23 -0
  55. data/spec/feature/invoices_spec.rb +73 -0
  56. data/spec/feature/multiplan_subscriptions_spec.rb +319 -0
  57. data/spec/feature/payment_methods_spec.rb +149 -0
  58. data/spec/feature/pending_updates_spec.rb +77 -0
  59. data/spec/feature/subscriptions_spec.rb +650 -0
  60. data/spec/feature/webhooks_spec.rb +162 -0
  61. data/spec/spec_helper.rb +27 -0
  62. data/spec/support/feature_helpers.rb +39 -0
  63. data/spec/unit/customer_spec.rb +54 -0
  64. data/spec/unit/invoice_line_item_spec.rb +72 -0
  65. data/spec/unit/invoice_spec.rb +192 -0
  66. data/spec/unit/payment_spec.rb +33 -0
  67. data/spec/unit/subscription_spec.rb +103 -0
  68. metadata +237 -0
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: c9ff3b5ea9665bfe6095a9ec7e30875db051e82db49173788d201257f8274212
4
+ data.tar.gz: 30e9965771a6c7d1c0bcd3f8171840ec7c884cdf77cbaa6804eee1c521883aa9
5
+ SHA512:
6
+ metadata.gz: 4bd93a8d4f8ae5a2049e1ef62e8b0ddbb89773fb89725f7fc60f5194f33e4c6137a48dd989c6d8913fcb42e7d51545296f3ba269f9ba5218bce89f54eedb97e1
7
+ data.tar.gz: e22ad7b72c9d266da14d864921f4f1e4dff365b24d46490077e3af6153ffd08a8cde164d431bce0e948e7bb67720f3558bc31f6e0df8d379b625c3c0e198558b
@@ -0,0 +1,14 @@
1
+ root = true
2
+
3
+ [*]
4
+ indent_style = space
5
+ indent_size = 2
6
+ end_of_line = lf
7
+ charset = utf-8
8
+ insert_final_newline = true
9
+
10
+ [*.md]
11
+ trim_trailing_whitespace = false
12
+
13
+ [*.{yml,yaml}]
14
+ indent_size = 2
@@ -0,0 +1,4 @@
1
+ # may be useful in hiding large schema changes in pull request diffs (but not
2
+ # using it for now)
3
+ spec/*.json binary
4
+ spec/*.yaml binary
@@ -0,0 +1,15 @@
1
+ !.keep
2
+ *.DS_Store
3
+ *.swo
4
+ *.swp
5
+ *~
6
+ .bundle
7
+ db/*.sqlite3
8
+ gemfiles/*.lock
9
+ gemfiles/vendor/
10
+ log/*.log
11
+ pkg
12
+ tmp/
13
+ doc/
14
+ .yardoc/
15
+ coverage/
@@ -0,0 +1,28 @@
1
+ cache: bundler
2
+
3
+ language:
4
+ - ruby
5
+
6
+ rvm:
7
+ - 2.4.9
8
+ - 2.5.7
9
+ - 2.6.5
10
+ - 2.7.0
11
+
12
+ gemfile:
13
+ - gemfiles/rails_5.0.gemfile
14
+ - gemfiles/rails_5.1.gemfile
15
+ - gemfiles/rails_5.2.gemfile
16
+ - gemfiles/rails_6.0.gemfile
17
+
18
+ install:
19
+ - "bin/setup"
20
+
21
+ branches:
22
+ only:
23
+ - master
24
+
25
+ matrix:
26
+ exclude:
27
+ - rvm: 2.4.9
28
+ gemfile: gemfiles/rails_6.0.gemfile
@@ -0,0 +1,17 @@
1
+ appraise 'rails_5.0' do
2
+ gem 'railties', '~> 5.0'
3
+ gem 'rspec-rails', '~> 3.1'
4
+ gem 'sqlite3', '~> 1.3.13'
5
+ end
6
+
7
+ appraise 'rails_5.1' do
8
+ gem 'railties', '~> 5.1'
9
+ end
10
+
11
+ appraise 'rails_5.2' do
12
+ gem 'railties', '~> 5.2'
13
+ end
14
+
15
+ appraise 'rails_6.0' do
16
+ gem 'railties', '~> 6.0'
17
+ end
data/Gemfile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ gemspec
6
+
7
+ gem 'appraisal'
8
+ gem 'pry', require: false
@@ -0,0 +1,133 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ reji (1.0.0)
5
+ actionmailer (>= 5.0)
6
+ activerecord (>= 5.0)
7
+ money (>= 6.0)
8
+ railties (>= 5.0)
9
+ stripe (>= 5.0)
10
+ wicked_pdf
11
+ wkhtmltopdf-binary
12
+
13
+ GEM
14
+ remote: https://rubygems.org/
15
+ specs:
16
+ actionmailer (6.0.3.2)
17
+ actionpack (= 6.0.3.2)
18
+ actionview (= 6.0.3.2)
19
+ activejob (= 6.0.3.2)
20
+ mail (~> 2.5, >= 2.5.4)
21
+ rails-dom-testing (~> 2.0)
22
+ actionpack (6.0.3.2)
23
+ actionview (= 6.0.3.2)
24
+ activesupport (= 6.0.3.2)
25
+ rack (~> 2.0, >= 2.0.8)
26
+ rack-test (>= 0.6.3)
27
+ rails-dom-testing (~> 2.0)
28
+ rails-html-sanitizer (~> 1.0, >= 1.2.0)
29
+ actionview (6.0.3.2)
30
+ activesupport (= 6.0.3.2)
31
+ builder (~> 3.1)
32
+ erubi (~> 1.4)
33
+ rails-dom-testing (~> 2.0)
34
+ rails-html-sanitizer (~> 1.1, >= 1.2.0)
35
+ activejob (6.0.3.2)
36
+ activesupport (= 6.0.3.2)
37
+ globalid (>= 0.3.6)
38
+ activemodel (6.0.3.2)
39
+ activesupport (= 6.0.3.2)
40
+ activerecord (6.0.3.2)
41
+ activemodel (= 6.0.3.2)
42
+ activesupport (= 6.0.3.2)
43
+ activesupport (6.0.3.2)
44
+ concurrent-ruby (~> 1.0, >= 1.0.2)
45
+ i18n (>= 0.7, < 2)
46
+ minitest (~> 5.1)
47
+ tzinfo (~> 1.1)
48
+ zeitwerk (~> 2.2, >= 2.2.2)
49
+ appraisal (2.3.0)
50
+ bundler
51
+ rake
52
+ thor (>= 0.14.0)
53
+ builder (3.2.4)
54
+ coderay (1.1.3)
55
+ concurrent-ruby (1.1.7)
56
+ crass (1.0.6)
57
+ diff-lcs (1.4.4)
58
+ erubi (1.9.0)
59
+ globalid (0.4.2)
60
+ activesupport (>= 4.2.0)
61
+ i18n (1.8.5)
62
+ concurrent-ruby (~> 1.0)
63
+ loofah (2.7.0)
64
+ crass (~> 1.0.2)
65
+ nokogiri (>= 1.5.9)
66
+ mail (2.7.1)
67
+ mini_mime (>= 0.1.1)
68
+ method_source (1.0.0)
69
+ mini_mime (1.0.2)
70
+ mini_portile2 (2.4.0)
71
+ minitest (5.14.2)
72
+ money (6.13.8)
73
+ i18n (>= 0.6.4, <= 2)
74
+ nokogiri (1.10.10)
75
+ mini_portile2 (~> 2.4.0)
76
+ pry (0.13.1)
77
+ coderay (~> 1.1)
78
+ method_source (~> 1.0)
79
+ rack (2.2.3)
80
+ rack-test (1.1.0)
81
+ rack (>= 1.0, < 3)
82
+ rails-dom-testing (2.0.3)
83
+ activesupport (>= 4.2.0)
84
+ nokogiri (>= 1.6)
85
+ rails-html-sanitizer (1.3.0)
86
+ loofah (~> 2.3)
87
+ railties (6.0.3.2)
88
+ actionpack (= 6.0.3.2)
89
+ activesupport (= 6.0.3.2)
90
+ method_source
91
+ rake (>= 0.8.7)
92
+ thor (>= 0.20.3, < 2.0)
93
+ rake (13.0.1)
94
+ rspec-core (3.9.2)
95
+ rspec-support (~> 3.9.3)
96
+ rspec-expectations (3.9.2)
97
+ diff-lcs (>= 1.2.0, < 2.0)
98
+ rspec-support (~> 3.9.0)
99
+ rspec-mocks (3.9.1)
100
+ diff-lcs (>= 1.2.0, < 2.0)
101
+ rspec-support (~> 3.9.0)
102
+ rspec-rails (4.0.1)
103
+ actionpack (>= 4.2)
104
+ activesupport (>= 4.2)
105
+ railties (>= 4.2)
106
+ rspec-core (~> 3.9)
107
+ rspec-expectations (~> 3.9)
108
+ rspec-mocks (~> 3.9)
109
+ rspec-support (~> 3.9)
110
+ rspec-support (3.9.3)
111
+ sqlite3 (1.4.2)
112
+ stripe (5.25.0)
113
+ thor (1.0.1)
114
+ thread_safe (0.3.6)
115
+ tzinfo (1.2.7)
116
+ thread_safe (~> 0.1)
117
+ wicked_pdf (2.1.0)
118
+ activesupport
119
+ wkhtmltopdf-binary (0.12.6.3)
120
+ zeitwerk (2.4.0)
121
+
122
+ PLATFORMS
123
+ ruby
124
+
125
+ DEPENDENCIES
126
+ appraisal
127
+ pry
128
+ reji!
129
+ rspec-rails (~> 4.0.1)
130
+ sqlite3 (~> 1.4.2)
131
+
132
+ BUNDLED WITH
133
+ 2.1.4
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright 2020 Cuong Giang
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,1285 @@
1
+ # Rails Reji
2
+
3
+ - [Introduction](#introduction)
4
+ - [Installation](#installation)
5
+ - [Configuration](#configuration)
6
+ - [Billable Model](#billable-model)
7
+ - [API Keys](#api-keys)
8
+ - [Currency Configuration](#currency-configuration)
9
+ - [Quickstart](#quickstart)
10
+ - [Customers](#customers)
11
+ - [Retrieving Customers](#retrieving-customers)
12
+ - [Creating Customers](#creating-customers)
13
+ - [Updating Customers](#updating-customers)
14
+ - [Billing Portal](#billing-portal)
15
+ - [Payment Methods](#payment-methods)
16
+ - [Storing Payment Methods](#storing-payment-methods)
17
+ - [Retrieving Payment Methods](#retrieving-payment-methods)
18
+ - [Determining If A User Has A Payment Method](#check-for-a-payment-method)
19
+ - [Updating The Default Payment Method](#updating-the-default-payment-method)
20
+ - [Adding Payment Methods](#adding-payment-methods)
21
+ - [Deleting Payment Methods](#deleting-payment-methods)
22
+ - [Subscriptions](#subscriptions)
23
+ - [Creating Subscriptions](#creating-subscriptions)
24
+ - [Checking Subscription Status](#checking-subscription-status)
25
+ - [Changing Plans](#changing-plans)
26
+ - [Subscription Quantity](#subscription-quantity)
27
+ - [Multiplan Subscriptions](#multiplan-subscriptions)
28
+ - [Subscription Taxes](#subscription-taxes)
29
+ - [Subscription Anchor Date](#subscription-anchor-date)
30
+ - [Cancelling Subscriptions](#cancelling-subscriptions)
31
+ - [Resuming Subscriptions](#resuming-subscriptions)
32
+ - [Subscription Trials](#subscription-trials)
33
+ - [With Payment Method Up Front](#with-payment-method-up-front)
34
+ - [Without Payment Method Up Front](#without-payment-method-up-front)
35
+ - [Extending Trials](#extending-trials)
36
+ - [Handling Stripe Webhooks](#handling-stripe-webhooks)
37
+ - [Defining Webhook Event Handlers](#defining-webhook-event-handlers)
38
+ - [Failed Subscriptions](#handling-failed-subscriptions)
39
+ - [Verifying Webhook Signatures](#verifying-webhook-signatures)
40
+ - [Single Charges](#single-charges)
41
+ - [Simple Charge](#simple-charge)
42
+ - [Charge With Invoice](#charge-with-invoice)
43
+ - [Refunding Charges](#refunding-charges)
44
+ - [Invoices](#invoices)
45
+ - [Retrieving Invoices](#retrieving-invoices)
46
+ - [Generating Invoice PDFs](#generating-invoice-pdfs)
47
+ - [Handling Failed Payments](#handling-failed-payments)
48
+ - [Stripe SDK](#stripe-sdk)
49
+ - [Testing](#testing)
50
+ - [License](#license)
51
+
52
+ <a name="introduction"></a>
53
+ ## Introduction
54
+
55
+ Reji provides an expressive, fluent interface to [Stripe's](https://stripe.com) subscription billing services for your Rails applications. It handles almost all of the boilerplate subscription billing code you are dreading writing. In addition to basic subscription management, Reji can handle coupons, swapping subscription, subscription "quantities", cancellation grace periods, and even generate invoice PDFs.
56
+
57
+ <a name="installation"></a>
58
+ ## Installation
59
+
60
+ Reji is a Rails gem tested against Rails `>= 5.0` and Ruby `>= 2.4.0`.
61
+
62
+ > To prevent breaking changes, Reji uses a fixed Stripe API version. Reji currently utilizes Stripe API version `2020-08-27`. The Stripe API version will be updated on minor releases in order to make use of new Stripe features and improvements.
63
+
64
+ You can add it to your Gemfile with:
65
+
66
+ ```bash
67
+ gem 'reji'
68
+ ```
69
+
70
+ Run the bundle command to install it.
71
+
72
+ > To ensure Reji properly handles all Stripe events, remember to [set up Reji's webhook handling](#handling-stripe-webhooks).
73
+
74
+ After you install Reji, you need to run the generator:
75
+
76
+ ```bash
77
+ rails generate reji:install
78
+ ```
79
+
80
+ The Reji install generator:
81
+
82
+ * Creates an initializer file to allow further configuration.
83
+ * Creates migration files that add several columns to your `users` table as well as create a new `subscriptions` table to hold all of your customer's subscriptions.
84
+
85
+ #### Database Migrations
86
+
87
+ Remember to migrate your database after installing the gem. The Reji migrations will add several columns to your `users` table as well as create a new `subscriptions` table to hold all of your customer's subscriptions:
88
+
89
+ ```bash
90
+ rails db:migrate
91
+ ```
92
+
93
+ > Stripe recommends that any column used for storing Stripe identifiers should be case-sensitive. Therefore, you should ensure the column collation for the `stripe_id` column is set to, for example, `utf8_bin` in MySQL. More info can be found [in the Stripe documentation](https://stripe.com/docs/upgrades#what-changes-does-stripe-consider-to-be-backwards-compatible).
94
+
95
+ <a name="configuration"></a>
96
+ ## Configuration
97
+
98
+ <a name="billable-model"></a>
99
+ ### Billable Model
100
+
101
+ Before using Reji, add the `Billable` concern to your model definition. This concern provides various methods to allow you to perform common billing tasks, such as creating subscriptions, applying coupons, and updating payment method information:
102
+
103
+ ```ruby
104
+ class User < ApplicationRecord
105
+ include Reji::Billable
106
+ end
107
+ ```
108
+
109
+ Reji assumes your Billable model will be the `User` class. If you wish to change this you can specify a different model by setting the `REJI_MODEL` environment variable:
110
+
111
+ ```sh
112
+ REJI_MODEL=User
113
+ ```
114
+
115
+ > If you're using a model other than `User` model, you'll need to publish and alter the [migrations](#installation) provided to match your alternative model's table name.
116
+
117
+ <a name="api-keys"></a>
118
+ ### API Keys
119
+
120
+ Next, you should configure your Stripe keys in your environment variables. You can retrieve your Stripe API keys from the Stripe control panel.
121
+
122
+ ```sh
123
+ STRIPE_KEY=your-stripe-key
124
+ STRIPE_SECRET=your-stripe-secret
125
+ ```
126
+
127
+ <a name="currency-configuration"></a>
128
+ ### Currency Configuration
129
+
130
+ The default Reji currency is United States Dollars (USD). You can change the default currency by setting the `REJI_CURRENCY` environment variable:
131
+
132
+ ```sh
133
+ REJI_CURRENCY=eur
134
+ ```
135
+
136
+ <a name="quickstart"></a>
137
+ ## Quickstart
138
+
139
+ With Reji, subscriptions will be much simpler in your Rails application:
140
+
141
+ ```ruby
142
+ class Api::SubscriptionController < ApplicationController
143
+ def store
144
+ begin
145
+ current_user.new_subscription('default', params[:stripe_plan]).add
146
+ rescue Stripe::InvalidRequestError => e
147
+ render json: { stripe_plan: e.error.message }, status: 422
148
+ end
149
+ end
150
+
151
+ def update
152
+ begin
153
+ current_user.subscription('default').swap(params[:stripe_plan])
154
+ rescue Stripe::InvalidRequestError => e
155
+ render json: { stripe_plan: e.error.message }, status: 422
156
+ end
157
+ end
158
+
159
+ def destroy
160
+ current_user.subscription('default').cancel
161
+ end
162
+ end
163
+ ```
164
+
165
+ <a name="customers"></a>
166
+ ## Customers
167
+
168
+ <a name="retrieving-customers"></a>
169
+ ### Retrieving Customers
170
+
171
+ You can retrieve a customer by their Stripe ID using the `Reji.find_billable` method. This will return an instance of the Billable model:
172
+
173
+ ```ruby
174
+ user = Reji.find_billable(stripe_id)
175
+ ```
176
+
177
+ <a name="creating-customers"></a>
178
+ ### Creating Customers
179
+
180
+ Occasionally, you may wish to create a Stripe customer without beginning a subscription. You may accomplish this using the `create_as_stripe_customer` method:
181
+
182
+ ```ruby
183
+ stripe_customer = user.create_as_stripe_customer
184
+ ```
185
+
186
+ Once the customer has been created in Stripe, you may begin a subscription at a later date. You can also use an optional `options` array to pass in any additional parameters which are supported by the Stripe API:
187
+
188
+ ```ruby
189
+ stripe_customer = user.create_as_stripe_customer(options)
190
+ ```
191
+
192
+ You may use the `as_stripe_customer` method if you want to return the customer object if the billable entity is already a customer within Stripe:
193
+
194
+ ```ruby
195
+ stripe_customer = user.as_stripe_customer
196
+ ```
197
+
198
+ The `create_or_get_stripe_customer` method may be used if you want to return the customer object but are not sure whether the billable entity is already a customer within Stripe. This method will create a new customer in Stripe if one does not already exist:
199
+
200
+ ```ruby
201
+ stripe_customer = user.create_or_get_stripe_customer
202
+ ```
203
+
204
+ <a name="updating-customers"></a>
205
+ ### Updating Customers
206
+
207
+ Occasionally, you may wish to update the Stripe customer directly with additional information. You may accomplish this using the `update_stripe_customer` method:
208
+
209
+ ```ruby
210
+ stripe_customer = user.update_stripe_customer(options)
211
+ ```
212
+
213
+ <a name="billing-portal"></a>
214
+ ### Billing Portal
215
+
216
+ Stripe offers [an easy way to set up a billing portal](https://stripe.com/docs/billing/subscriptions/customer-portal) so your customer can manage their subscription, payment methods, and view their billing history. You can redirect your users to the billing portal using the `billing_portal_url` method from a controller:
217
+
218
+ ```ruby
219
+ def billing_portal
220
+ redirect_to user.billing_portal_url
221
+ end
222
+ ```
223
+
224
+ By default, when the user is finished managing their subscription, they can return to the root `/` url of your application. You may provide a custom URL the user should return to by passing the URL as an argument to the `billing_portal_url` method:
225
+
226
+ ```ruby
227
+ def billing_portal
228
+ redirect_to user.billing_portal_url('/billing')
229
+ end
230
+ ```
231
+
232
+ <a name="payment-methods"></a>
233
+ ## Payment Methods
234
+
235
+ <a name="storing-payment-methods"></a>
236
+ ### Storing Payment Methods
237
+
238
+ In order to create subscriptions or perform "one off" charges with Stripe, you will need to store a payment method and retrieve its identifier from Stripe. The approach used to accomplish differs based on whether you plan to use the payment method for subscriptions or single charges, so we will examine both below.
239
+
240
+ #### Payment Methods For Subscriptions
241
+
242
+ When storing credit cards to a customer for future use, the Stripe Setup Intents API must be used to securely gather the customer's payment method details. A "Setup Intent" indicates to Stripe the intention to charge a customer's payment method. Reji's `Billable` concern includes the `create_setup_intent` to easily create a new Setup Intent. You should call this method from a controller that will render the form which gathers your customer's payment method details:
243
+
244
+ ```ruby
245
+ @intent = user.create_setup_intent
246
+ render 'update-payment-method'
247
+ ```
248
+
249
+ After you have created the Setup Intent and passed it to the view, you should attach its secret to the element that will gather the payment method. For example, consider this "update payment method" form:
250
+
251
+ ```html
252
+ <input id="card-holder-name" type="text">
253
+
254
+ <!-- Stripe Elements Placeholder -->
255
+ <div id="card-element"></div>
256
+
257
+ <button id="card-button" data-secret="<%= intent.client_secret %>">
258
+ Update Payment Method
259
+ </button>
260
+ ```
261
+
262
+ Next, the Stripe.js library may be used to attach a Stripe Element to the form and securely gather the customer's payment details:
263
+
264
+ ```html
265
+ <script src="https://js.stripe.com/v3/"></script>
266
+
267
+ <script>
268
+ const stripe = Stripe('stripe-public-key');
269
+
270
+ const elements = stripe.elements();
271
+ const cardElement = elements.create('card');
272
+
273
+ cardElement.mount('#card-element');
274
+ </script>
275
+ ```
276
+
277
+ Next, the card can be verified and a secure "payment method identifier" can be retrieved from Stripe using [Stripe's `confirmCardSetup` method](https://stripe.com/docs/js/setup_intents/confirm_card_setup):
278
+
279
+ ```js
280
+ const cardHolderName = document.getElementById('card-holder-name');
281
+ const cardButton = document.getElementById('card-button');
282
+ const clientSecret = cardButton.dataset.secret;
283
+
284
+ cardButton.addEventListener('click', async (e) => {
285
+ const { setupIntent, error } = await stripe.confirmCardSetup(
286
+ clientSecret, {
287
+ payment_method: {
288
+ card: cardElement,
289
+ billing_details: { name: cardHolderName.value }
290
+ }
291
+ }
292
+ );
293
+
294
+ if (error) {
295
+ // Display "error.message" to the user...
296
+ } else {
297
+ // The card has been verified successfully...
298
+ }
299
+ });
300
+ ```
301
+
302
+ After the card has been verified by Stripe, you may pass the resulting `setupIntent.payment_method` identifier to your Rails application, where it can be attached to the customer. The payment method can either be [added as a new payment method](#adding-payment-methods) or [used to update the default payment method](#updating-the-default-payment-method). You can also immediately use the payment method identifier to [create a new subscription](#creating-subscriptions).
303
+
304
+ > If you would like more information about Setup Intents and gathering customer payment details please [review this overview provided by Stripe](https://stripe.com/docs/payments/save-and-reuse#ruby).
305
+
306
+ #### Payment Methods For Single Charges
307
+
308
+ Of course, when making a single charge against a customer's payment method we'll only need to use a payment method identifier a single time. Due to Stripe limitations, you may not use the stored default payment method of a customer for single charges. You must allow the customer to enter their payment method details using the Stripe.js library. For example, consider the following form:
309
+
310
+ ```html
311
+ <input id="card-holder-name" type="text">
312
+
313
+ <!-- Stripe Elements Placeholder -->
314
+ <div id="card-element"></div>
315
+
316
+ <button id="card-button">
317
+ Process Payment
318
+ </button>
319
+ ```
320
+
321
+ Next, the Stripe.js library may be used to attach a Stripe Element to the form and securely gather the customer's payment details:
322
+
323
+ ```html
324
+ <script src="https://js.stripe.com/v3/"></script>
325
+
326
+ <script>
327
+ const stripe = Stripe('stripe-public-key');
328
+
329
+ const elements = stripe.elements();
330
+ const cardElement = elements.create('card');
331
+
332
+ cardElement.mount('#card-element');
333
+ </script>
334
+ ```
335
+
336
+ Next, the card can be verified and a secure "payment method identifier" can be retrieved from Stripe using [Stripe's `createPaymentMethod` method](https://stripe.com/docs/stripe-js/reference#stripe-create-payment-method):
337
+
338
+ ```js
339
+ const cardHolderName = document.getElementById('card-holder-name');
340
+ const cardButton = document.getElementById('card-button');
341
+
342
+ cardButton.addEventListener('click', async (e) => {
343
+ const { paymentMethod, error } = await stripe.createPaymentMethod(
344
+ 'card', cardElement, {
345
+ billing_details: { name: cardHolderName.value }
346
+ }
347
+ );
348
+
349
+ if (error) {
350
+ // Display "error.message" to the user...
351
+ } else {
352
+ // The card has been verified successfully...
353
+ }
354
+ });
355
+ ```
356
+
357
+ If the card is verified successfully, you may pass the `paymentMethod.id` to your Rails application and process a [single charge](#simple-charge).
358
+
359
+ <a name="retrieving-payment-methods"></a>
360
+ ### Retrieving Payment Methods
361
+
362
+ The `payment_methods` method on the Billable model instance returns a collection of `Reji::PaymentMethod` instances:
363
+
364
+ ```ruby
365
+ payment_methods = user.payment_methods
366
+ ```
367
+
368
+ To retrieve the default payment method, the `default_payment_method` method may be used:
369
+
370
+ ```ruby
371
+ payment_method = user.default_payment_method
372
+ ```
373
+
374
+ You can also retrieve a specific payment method that is owned by the Billable model using the `find_payment_method` method:
375
+
376
+ ```ruby
377
+ payment_method = user.find_payment_method(payment_method_id)
378
+ ```
379
+
380
+ <a name="check-for-a-payment-method"></a>
381
+ ### Determining If A User Has A Payment Method
382
+
383
+ To determine if a Billable model has a default payment method attached to their account, use the `has_default_payment_method` method:
384
+
385
+ ```ruby
386
+ if user.has_default_payment_method
387
+ #
388
+ end
389
+ ```
390
+
391
+ To determine if a Billable model has at least one payment method attached to their account, use the `has_payment_method` method:
392
+
393
+ ```ruby
394
+ if user.has_payment_method
395
+ #
396
+ end
397
+ ```
398
+
399
+ <a name="updating-the-default-payment-method"></a>
400
+ ### Updating The Default Payment Method
401
+
402
+ The `update_default_payment_method` method may be used to update a customer's default payment method information. This method accepts a Stripe payment method identifier and will assign the new payment method as the default billing payment method:
403
+
404
+ ```ruby
405
+ user.update_default_payment_method(payment_method)
406
+ ```
407
+
408
+ To sync your default payment method information with the customer's default payment method information in Stripe, you may use the `update_default_payment_method_from_stripe` method:
409
+
410
+ ```ruby
411
+ user.update_default_payment_method_from_stripe
412
+ ```
413
+
414
+ > The default payment method on a customer can only be used for invoicing and creating new subscriptions. Due to limitations from Stripe, it may not be used for single charges.
415
+
416
+ <a name="adding-payment-methods"></a>
417
+ ### Adding Payment Methods
418
+
419
+ To add a new payment method, you may call the `add_payment_method` method on the billable user, passing the payment method identifier:
420
+
421
+ ```ruby
422
+ user.add_payment_method(payment_method)
423
+ ```
424
+
425
+ > To learn how to retrieve payment method identifiers please review the [payment method storage documentation](#storing-payment-methods).
426
+
427
+ <a name="deleting-payment-methods"></a>
428
+ ### Deleting Payment Methods
429
+
430
+ To delete a payment method, you may call the `delete` method on the `Reji::PaymentMethod` instance you wish to delete:
431
+
432
+ ```ruby
433
+ payment_method.delete
434
+ ```
435
+
436
+ The `delete_payment_methods` method will delete all of the payment method information for the Billable model:
437
+
438
+ ```ruby
439
+ user.delete_payment_methods
440
+ ```
441
+
442
+ > If a user has an active subscription, you should prevent them from deleting their default payment method.
443
+
444
+ <a name="subscriptions"></a>
445
+ ## Subscriptions
446
+
447
+ <a name="creating-subscriptions"></a>
448
+ ### Creating Subscriptions
449
+
450
+ To create a subscription, first retrieve an instance of your billable model, which typically will be an instance of `User`. Once you have retrieved the model instance, you may use the `new_subscription` method to create the model's subscription:
451
+
452
+ ```ruby
453
+ user = User.find(1)
454
+ user.new_subscription('default', 'price_premium').create(payment_method)
455
+ ```
456
+
457
+ The first argument passed to the `new_subscription` method should be the name of the subscription. If your application only offers a single subscription, you might call this `default` or `primary`. The second argument is the specific plan the user is subscribing to. This value should correspond to the plan's price identifier in Stripe.
458
+
459
+ The `create` method, which accepts [a Stripe payment method identifier](#storing-payment-methods) or Stripe `PaymentMethod` object, will begin the subscription as well as update your database with the customer ID and other relevant billing information.
460
+
461
+ > Passing a payment method identifier directly to the `create` subscription method will also automatically add it to the user's stored payment methods.
462
+
463
+ #### Quantities
464
+
465
+ If you would like to set a specific quantity for the plan when creating the subscription, you may use the `quantity` method:
466
+
467
+ ```ruby
468
+ user.new_subscription('default', 'price_monthly')
469
+ .quantity(5)
470
+ .create(payment_method)
471
+ ```
472
+
473
+ #### Additional Details
474
+
475
+ If you would like to specify additional customer or subscription details, you may do so by passing them as the second and third arguments to the `create` method:
476
+
477
+ ```ruby
478
+ user.new_subscription('default', 'price_monthly').create(payment_method, {
479
+ :email => email,
480
+ }, {
481
+ :metadata => {:note => 'Some extra information.'},
482
+ })
483
+ ```
484
+
485
+ To learn more about the additional fields supported by Stripe, check out Stripe's documentation on [customer creation](https://stripe.com/docs/api#create_customer) and [subscription creation](https://stripe.com/docs/api/subscriptions/create).
486
+
487
+ #### Coupons
488
+
489
+ If you would like to apply a coupon when creating the subscription, you may use the `with_coupon` method:
490
+
491
+ ```ruby
492
+ user.new_subscription('default', 'price_monthly')
493
+ .with_coupon('code')
494
+ .create(payment_method)
495
+ ```
496
+
497
+ #### Adding Subscriptions
498
+
499
+ If you would like to add a subscription to a customer who already has a default payment method set you can use the `add` method when using the `new_subscription` method:
500
+
501
+ ```ruby
502
+ user = User.find(1)
503
+ user.new_subscription('default', 'price_premium').add
504
+ ```
505
+
506
+ <a name="checking-subscription-status"></a>
507
+ ### Checking Subscription Status
508
+
509
+ Once a user is subscribed to your application, you may easily check their subscription status using a variety of convenient methods. First, the `subscribed` method returns `true` if the user has an active subscription, even if the subscription is currently within its trial period:
510
+
511
+ ```ruby
512
+ if user.subscribed('default')
513
+ #
514
+ end
515
+ ```
516
+
517
+ If you would like to determine if a user is still within their trial period, you may use the `on_trial` method. This method can be useful for displaying a warning to the user that they are still on their trial period:
518
+
519
+ ```ruby
520
+ if user.subscription('default').on_trial
521
+ #
522
+ end
523
+ ```
524
+
525
+ The `subscribed_to_plan` method may be used to determine if the user is subscribed to a given plan based on a given Stripe Price ID. In this example, we will determine if the user's `default` subscription is actively subscribed to the `monthly` plan:
526
+
527
+ ```ruby
528
+ if user.subscribed_to_plan('price_monthly', 'default')
529
+ #
530
+ end
531
+ ```
532
+
533
+ By passing an array to the `subscribed_to_plan` method, you may determine if the user's `default` subscription is actively subscribed to the `monthly` or the `yearly` plan:
534
+
535
+ ```ruby
536
+ if user.subscribed_to_plan(['price_monthly', 'price_yearly'], 'default')
537
+ #
538
+ end
539
+ ```
540
+
541
+ The `recurring` method may be used to determine if the user is currently subscribed and is no longer within their trial period:
542
+
543
+ ```ruby
544
+ if user.subscription('default').recurring
545
+ #
546
+ end
547
+ ```
548
+
549
+ #### Cancelled Subscription Status
550
+
551
+ To determine if the user was once an active subscriber, but has cancelled their subscription, you may use the `cancelled` method:
552
+
553
+ ```ruby
554
+ if user.subscription('default').cancelled
555
+ #
556
+ end
557
+ ```
558
+
559
+ You may also determine if a user has cancelled their subscription, but are still on their "grace period" until the subscription fully expires. For example, if a user cancels a subscription on March 5th that was originally scheduled to expire on March 10th, the user is on their "grace period" until March 10th. Note that the `subscribed` method still returns `true` during this time:
560
+
561
+ ```ruby
562
+ if user.subscription('default').on_grace_period
563
+ #
564
+ end
565
+ ```
566
+
567
+ To determine if the user has cancelled their subscription and is no longer within their "grace period", you may use the `ended` method:
568
+
569
+ ```ruby
570
+ if user.subscription('default').ended
571
+ #
572
+ end
573
+ ```
574
+
575
+ #### Subscription Scopes
576
+
577
+ Most subscription states are also available as query scopes so that you may easily query your database for subscriptions that are in a given state:
578
+
579
+ ```ruby
580
+ # Get all active subscriptions...
581
+ subscriptions = Reji::Subscription.active
582
+
583
+ # Get all of the cancelled subscriptions for a user...
584
+ subscriptions = user.subscriptions.cancelled
585
+ ```
586
+
587
+ A complete list of available scopes is available below:
588
+
589
+ ```ruby
590
+ Reji::Subscription.active
591
+ Reji::Subscription.cancelled
592
+ Reji::Subscription.ended
593
+ Reji::Subscription.incomplete
594
+ Reji::Subscription.not_cancelled
595
+ Reji::Subscription.not_on_grace_period
596
+ Reji::Subscription.not_on_trial
597
+ Reji::Subscription.on_grace_period
598
+ Reji::Subscription.on_trial
599
+ Reji::Subscription.past_due
600
+ Reji::Subscription.recurring
601
+ ```
602
+
603
+ <a name="incomplete-and-past-due-status"></a>
604
+ #### Incomplete and Past Due Status
605
+
606
+ If a subscription requires a secondary payment action after creation the subscription will be marked as `incomplete`. Subscription statuses are stored in the `stripe_status` column of Reji's `subscriptions` database table.
607
+
608
+ Similarly, if a secondary payment action is required when swapping plans the subscription will be marked as `past_due`. When your subscription is in either of these states it will not be active until the customer has confirmed their payment. Checking if a subscription has an incomplete payment can be done using the `has_incomplete_payment` method on the Billable model or a subscription instance:
609
+
610
+ ```ruby
611
+ if user.has_incomplete_payment('default')
612
+ #
613
+ end
614
+
615
+ if user.subscription('default').has_incomplete_payment
616
+ #
617
+ end
618
+ ```
619
+
620
+ When a subscription has an incomplete payment, you should direct the user to Reji's payment confirmation page, passing the `latest_payment` identifier. You may use the `latest_payment` method available on subscription instance to retrieve this identifier:
621
+
622
+ ```html
623
+ <a href="/stripe/payment/<%= subscription.latest_payment.id %>">
624
+ Please confirm your payment.
625
+ </a>
626
+ ```
627
+
628
+ If you would like the subscription to still be considered active when it's in a `past_due` state, you may use the `keep_past_due_subscriptions_active` method provided by Reji:
629
+
630
+ ```ruby
631
+ Reji.keep_past_due_subscriptions_active
632
+ ```
633
+
634
+ > When a subscription is in an `incomplete` state it cannot be changed until the payment is confirmed. Therefore, the `swap` and `update_quantity` methods will throw an exception when the subscription is in an `incomplete` state.
635
+
636
+ <a name="changing-plans"></a>
637
+ ### Changing Plans
638
+
639
+ After a user is subscribed to your application, they may occasionally want to change to a new subscription plan. To swap a user to a new subscription, pass the plan's price identifier to the `swap` method:
640
+
641
+ ```ruby
642
+ user = User.find(1)
643
+ user.subscription('default').swap('provider-price-id')
644
+ ```
645
+
646
+ If the user is on trial, the trial period will be maintained. Also, if a "quantity" exists for the subscription, that quantity will also be maintained.
647
+
648
+ If you would like to swap plans and cancel any trial period the user is currently on, you may use the `skip_trial` method:
649
+
650
+ ```ruby
651
+ user.subscription('default')
652
+ .skip_trial
653
+ .swap('provider-price-id')
654
+ ```
655
+
656
+ If you would like to swap plans and immediately invoice the user instead of waiting for their next billing cycle, you may use the `swap_and_invoice` method:
657
+
658
+ ```ruby
659
+ user = User.find(1)
660
+ user.subscription('default').swap_and_invoice('provider-price-id')
661
+ ```
662
+
663
+ #### Prorations
664
+
665
+ By default, Stripe prorates charges when swapping between plans. The `no_prorate` method may be used to update the subscription's without prorating the charges:
666
+
667
+ ```ruby
668
+ user.subscription('default').no_prorate.swap('provider-price-id')
669
+ ```
670
+
671
+ For more information on subscription proration, consult the [Stripe documentation](https://stripe.com/docs/billing/subscriptions/prorations).
672
+
673
+ > Executing the `no_prorate` method before the `swap_and_invoice` method will have no affect on proration. An invoice will always be issued.
674
+
675
+ <a name="subscription-quantity"></a>
676
+ ### Subscription Quantity
677
+
678
+ Sometimes subscriptions are affected by "quantity". For example, your application might charge $10 per month **per user** on an account. To easily increment or decrement your subscription quantity, use the `increment_quantity` and `decrement_quantity` methods:
679
+
680
+ ```ruby
681
+ user = User.find(1)
682
+
683
+ user.subscription('default').increment_quantity
684
+
685
+ # Add five to the subscription's current quantity...
686
+ user.subscription('default').increment_quantity(5)
687
+
688
+ user.subscription('default').decrement_quantity
689
+
690
+ # Subtract five to the subscription's current quantity...
691
+ user.subscription('default').decrement_quantity(5)
692
+ ```
693
+
694
+ Alternatively, you may set a specific quantity using the `update_quantity` method:
695
+
696
+ ```ruby
697
+ user.subscription('default').update_quantity(10)
698
+ ```
699
+
700
+ The `no_prorate` method may be used to update the subscription's quantity without prorating the charges:
701
+
702
+ ```ruby
703
+ user.subscription('default').no_prorate.update_quantity(10)
704
+ ```
705
+
706
+ For more information on subscription quantities, consult the [Stripe documentation](https://stripe.com/docs/subscriptions/quantities).
707
+
708
+ > Please note that when working with multiplan subscriptions, an extra "plan" parameter is required for the above quantity methods.
709
+
710
+ <a name="multiplan-subscriptions"></a>
711
+ ### Multiplan Subscriptions
712
+
713
+ [Multiplan subscriptions](https://stripe.com/docs/billing/subscriptions/multiplan) allow you to assign multiple billing plans to a single subscription. For example, imagine you are building a customer service "helpdesk" application that has a base subscription of $10 per month, but offers a live chat add-on plan for an additional $15 per month:
714
+
715
+ ```ruby
716
+ user = User.find(1)
717
+ user.new_subscription('default', [
718
+ 'price_monthly',
719
+ 'chat-plan',
720
+ ]).create(payment_method)
721
+ ```
722
+
723
+ Now the customer will have two plans on their `default` subscription. Both plans will be charged for on their respective billing intervals. You can also use the `quantity` method to indicate the specific quantity for each plan:
724
+
725
+ ```ruby
726
+ user = User.find(1)
727
+ user.new_subscription('default', ['price_monthly', 'chat-plan'])
728
+ .quantity(5, 'chat-plan')
729
+ .create(payment_method)
730
+ ```
731
+
732
+ Or, you may dynamically add the extra plan and its quantity using the `plan` method:
733
+
734
+ ```ruby
735
+ user = User.find(1)
736
+ user.new_subscription('default', 'price_monthly')
737
+ .plan('chat-plan', 5)
738
+ .create(payment_method)
739
+ ```
740
+
741
+ Alternatively, you may add a new plan to an existing subscription at a later time:
742
+
743
+ ```ruby
744
+ user = User.find(1)
745
+ user.subscription('default').add_plan('chat-plan')
746
+ ```
747
+
748
+ The example above will add the new plan and the customer will be billed for it on their next billing cycle. If you would like to bill the customer immediately you may use the `add_plan_and_invoice` method:
749
+
750
+ ```ruby
751
+ user.subscription('default').add_plan_and_invoice('chat-plan')
752
+ ```
753
+
754
+ If you would like to add a plan with a specific quantity, you can pass the quantity as the second parameter of the `add_plan` or `add_plan_and_invoice` methods:
755
+
756
+ ```ruby
757
+ user = User.find(1)
758
+ user.subscription('default').add_plan('chat-plan', 5)
759
+ ```
760
+
761
+ You may remove plans from subscriptions using the `remove_plan` method:
762
+
763
+ ```ruby
764
+ user.subscription('default').remove_plan('chat-plan')
765
+ ```
766
+
767
+ > You may not remove the last plan on a subscription. Instead, you should simply cancel the subscription.
768
+
769
+ ### Swapping
770
+
771
+ You may also change the plans attached to a multiplan subscription. For example, imagine you're on a `basic-plan` subscription with a `chat-plan` add-on and you want to upgrade to the `pro-plan` plan:
772
+
773
+ ```ruby
774
+ user = User.find(1)
775
+ user.subscription('default').swap(['pro-plan', 'chat-plan'])
776
+ ```
777
+
778
+ When executing the code above, the underlying subscription item with the `basic-plan` is deleted and the one with the `chat-plan` is preserved. Additionally, a new subscription item for the new `pro-plan` is created.
779
+
780
+ If you want to swap a single plan on a subscription, you may do so using the `swap` method on the subscription item itself. This approach is useful if you, for example, want to preserve all of the existing metadata on the subscription item.
781
+
782
+ ```ruby
783
+ user = User.find(1)
784
+ user.subscription('default')
785
+ .find_item_or_fail('basic-plan')
786
+ .swap('pro-plan')
787
+ ```
788
+
789
+ #### Proration
790
+
791
+ By default, Stripe will prorate charges when adding or removing plans from a subscription. If you would like to make a plan adjustment without proration, you should chain the `no_prorate` method onto your plan operation:
792
+
793
+ ```ruby
794
+ user.subscription('default').no_prorate.remove_plan('chat-plan')
795
+ ```
796
+
797
+ #### Quantities
798
+
799
+ If you would like to update quantities on individual subscription plans, you may do so using the [existing quantity methods](#subscription-quantity) and passing the name of the plan as an additional argument to the method:
800
+
801
+ ```ruby
802
+ user = User.find(1)
803
+
804
+ user.subscription('default').increment_quantity(5, 'chat-plan')
805
+
806
+ user.subscription('default').decrement_quantity(3, 'chat-plan')
807
+
808
+ user.subscription('default').update_quantity(10, 'chat-plan')
809
+ ```
810
+
811
+ > When you have multiple plans set on a subscription the `stripe_plan` and `quantity` attributes on the `Subscription` model will be `null`. To access the individual plans, you should use the `items` relationship available on the `Subscription` model.
812
+
813
+ #### Subscription Items
814
+
815
+ When a subscription has multiple plans, it will have multiple subscription "items" stored in your database's `subscription_items` table. You may access these via the `items` relationship on the subscription:
816
+
817
+ ```ruby
818
+ user = User.find(1)
819
+
820
+ subscription_item = user.subscription('default').items.first
821
+
822
+ # Retrieve the Stripe plan and quantity for a specific item...
823
+ stripe_plan = subscription_item.stripe_plan
824
+ quantity = subscription_item.quantity
825
+ ```
826
+
827
+ You can also retrieve a specific plan using the `find_item_or_fail` method:
828
+
829
+ ```ruby
830
+ user = User.find(1)
831
+ subscription_item = user.subscription('default').find_item_or_fail('chat-plan')
832
+ ```
833
+
834
+ <a name="subscription-taxes"></a>
835
+ ### Subscription Taxes
836
+
837
+ To specify the tax rates a user pays on a subscription, implement the `tax_rates` method on your billable model, and return an array with the Tax Rate IDs. You can define these tax rates in [your Stripe dashboard](https://dashboard.stripe.com/test/tax-rates):
838
+
839
+ ```ruby
840
+ def tax_rates
841
+ ['tax-rate-id']
842
+ end
843
+ ```
844
+
845
+ The `tax_rates` method enables you to apply a tax rate on a model-by-model basis, which may be helpful for a user base that spans multiple countries and tax rates. If you're working with multiplan subscriptions you can define different tax rates for each plan by implementing a `plan_tax_rates` method on your billable model:
846
+
847
+ ```ruby
848
+ def plan_tax_rates
849
+ [
850
+ 'plan-id' => ['tax-rate-id'],
851
+ ]
852
+ end
853
+ ```
854
+
855
+ > The `tax_rates` method only applies to subscription charges. If you use Reji to make "one off" charges, you will need to manually specify the tax rate at that time.
856
+
857
+ #### Syncing Tax Rates
858
+
859
+ When changing the hard-coded Tax Rate IDs returned by the `tax_rates` method, the tax settings on any existing subscriptions for the user will remain the same. If you wish to update the tax value for existing subscriptions with the returned `tax_tax_rates` values, you should call the `sync_tax_rates` method on the user's subscription instance:
860
+
861
+ ```ruby
862
+ user.subscription('default').sync_tax_rates
863
+ ```
864
+
865
+ This will also sync any subscription item tax rates so make sure you also properly change the `plan_tax_rates` method.
866
+
867
+ #### Tax Exemption
868
+
869
+ Reji also offers methods to determine if the customer is tax exempt by calling the Stripe API. The `is_not_tax_exempt`, `is_tax_exempt`, and `reverse_charge_applies` methods are available on the billable model:
870
+
871
+ ```ruby
872
+ user = User.find(1)
873
+ user.is_tax_exempt
874
+ user.is_not_tax_exempt
875
+ user.reverse_charge_applies
876
+ ```
877
+
878
+ These methods are also available on any `Reji::Invoice` object. However, when calling these methods on an `Invoice` object the methods will determine the exemption status at the time the invoice was created.
879
+
880
+ <a name="subscription-anchor-date"></a>
881
+ ### Subscription Anchor Date
882
+
883
+ By default, the billing cycle anchor is the date the subscription was created, or if a trial period is used, the date that the trial ends. If you would like to modify the billing anchor date, you may use the `anchor_billing_cycle_on` method:
884
+
885
+ ```ruby
886
+ user = User.find(1)
887
+
888
+ anchor = Time.now.at_beginning_of_month.next_month
889
+
890
+ user.new_subscription('default', 'price_premium')
891
+ .anchor_billing_cycle_on(anchor.to_i)
892
+ .create(payment_method)
893
+ ```
894
+
895
+ For more information on managing subscription billing cycles, consult the [Stripe billing cycle documentation](https://stripe.com/docs/billing/subscriptions/billing-cycle)
896
+
897
+ <a name="cancelling-subscriptions"></a>
898
+ ### Cancelling Subscriptions
899
+
900
+ To cancel a subscription, call the `cancel` method on the user's subscription:
901
+
902
+ ```ruby
903
+ user.subscription('default').cancel
904
+ ```
905
+
906
+ When a subscription is cancelled, Reji will automatically set the `ends_at` column in your database. This column is used to know when the `subscribed` method should begin returning `false`. For example, if a customer cancels a subscription on March 1st, but the subscription was not scheduled to end until March 5th, the `subscribed` method will continue to return `true` until March 5th.
907
+
908
+ You may determine if a user has cancelled their subscription but are still on their "grace period" using the `on_grace_period` method:
909
+
910
+ ```ruby
911
+ if user.subscription('default').on_grace_period
912
+ #
913
+ end
914
+ ```
915
+
916
+ If you wish to cancel a subscription immediately, call the `cancel_now` method on the user's subscription:
917
+
918
+ ```ruby
919
+ user.subscription('default').cancel_now
920
+ ```
921
+
922
+ <a name="resuming-subscriptions"></a>
923
+ ### Resuming Subscriptions
924
+
925
+ If a user has cancelled their subscription and you wish to resume it, use the `resume` method. The user **must** still be on their grace period in order to resume a subscription:
926
+
927
+ ```ruby
928
+ user.subscription('default').resume
929
+ ```
930
+
931
+ If the user cancels a subscription and then resumes that subscription before the subscription has fully expired, they will not be billed immediately. Instead, their subscription will be re-activated, and they will be billed on the original billing cycle.
932
+
933
+ <a name="subscription-trials"></a>
934
+ ## Subscription Trials
935
+
936
+ <a name="with-payment-method-up-front"></a>
937
+ ### With Payment Method Up Front
938
+
939
+ If you would like to offer trial periods to your customers while still collecting payment method information up front, you should use the `trial_days` method when creating your subscriptions:
940
+
941
+ ```ruby
942
+ user = User.find(1)
943
+ user.new_subscription('default', 'price_monthly')
944
+ .trial_days(10)
945
+ .create(payment_method)
946
+ ```
947
+
948
+ This method will set the trial period ending date on the subscription record within the database, as well as instruct Stripe to not begin billing the customer until after this date. When using the `trial_days` method, Reji will overwrite any default trial period configured for the plan in Stripe.
949
+
950
+ > If the customer's subscription is not cancelled before the trial ending date they will be charged as soon as the trial expires, so you should be sure to notify your users of their trial ending date.
951
+
952
+ The `trial_until` method allows you to provide a `Time` instance to specify when the trial period should end:
953
+
954
+ ```ruby
955
+ user.new_subscription('default', 'price_monthly')
956
+ .trial_until(Time.now + 10.days)
957
+ .create(payment_method)
958
+ ```
959
+
960
+ You may determine if the user is within their trial period using either the `on_trial` method of the user instance, or the `on_trial` method of the subscription instance. The two examples below are identical:
961
+
962
+ ```ruby
963
+ if user.on_trial('default')
964
+ #
965
+ end
966
+
967
+ if user.subscription('default').on_trial
968
+ #
969
+ end
970
+ ```
971
+
972
+ #### Defining Trial Days In Stripe / Reji
973
+
974
+ You may choose to define how many trial days your plan's receive in the Stripe dashboard or always pass them explicitly using Reji. If you choose to define your plan's trial days in Stripe you should be aware that new subscriptions, including new subscriptions for a customer that had a subscription in the past, will always receive a trial period unless you explicitly call the `trial_days(0)` method.
975
+
976
+ <a name="without-payment-method-up-front"></a>
977
+ ### Without Payment Method Up Front
978
+
979
+ If you would like to offer trial periods without collecting the user's payment method information up front, you may set the `trial_ends_at` column on the user record to your desired trial ending date. This is typically done during user registration:
980
+
981
+ ```ruby
982
+ user = User.create({
983
+ # Populate other user properties...
984
+ :trial_ends_at => Time.now + 10.days,
985
+ })
986
+ ```
987
+
988
+ Reji refers to this type of trial as a "generic trial", since it is not attached to any existing subscription. The `on_trial` method on the `User` instance will return `true` if the current date is not past the value of `trial_ends_at`:
989
+
990
+ ```ruby
991
+ if user.on_trial
992
+ # User is within their trial period...
993
+ end
994
+ ```
995
+
996
+ You may also use the `on_generic_trial` method if you wish to know specifically that the user is within their "generic" trial period and has not created an actual subscription yet:
997
+
998
+ ```ruby
999
+ if user.on_generic_trial
1000
+ # User is within their "generic" trial period...
1001
+ end
1002
+ ```
1003
+
1004
+ Once you are ready to create an actual subscription for the user, you may use the `new_subscription` method as usual:
1005
+
1006
+ ```ruby
1007
+ user = User.find(1)
1008
+ user.new_subscription('default', 'price_monthly').create(payment_method)
1009
+ ```
1010
+
1011
+ <a name="extending-trials"></a>
1012
+ ### Extending Trials
1013
+
1014
+ The `extend_trial` method allows you to extend the trial period of a subscription after it's been created:
1015
+
1016
+ ```ruby
1017
+ # End the trial 7 days from now...
1018
+ subscription.extend_trial(
1019
+ Time.now + 7.days
1020
+ )
1021
+
1022
+ # Add an additional 5 days to the trial...
1023
+ subscription.extend_trial(
1024
+ Time.at(subscription.trial_ends_at) + 5.days
1025
+ )
1026
+ ```
1027
+
1028
+ If the trial has already expired and the customer is already being billed for the subscription, you can still offer them an extended trial. The time spent within the trial period will be deducted from the customer's next invoice.
1029
+
1030
+ <a name="handling-stripe-webhooks"></a>
1031
+ ## Handling Stripe Webhooks
1032
+
1033
+ > You may use [the Stripe CLI](https://stripe.com/docs/stripe-cli) to help test webhooks during local development.
1034
+
1035
+ Stripe can notify your application of a variety of events via webhooks. By default, a route that points to Reji's webhook controller is configured. This controller will handle all incoming webhook requests.
1036
+
1037
+ By default, this controller will automatically handle cancelling subscriptions that have too many failed charges (as defined by your Stripe settings), customer updates, customer deletions, subscription updates; however, as we'll soon discover, you can extend this controller to handle any webhook event you like.
1038
+
1039
+ To ensure your application can handle Stripe webhooks, be sure to configure the webhook URL in the Stripe control panel. By default, Reji's webhook controller listens to the `/stripe/webhook` URL path. The full list of all webhooks you should configure in the Stripe control panel are:
1040
+
1041
+ - `customer.subscription.updated`
1042
+ - `customer.subscription.deleted`
1043
+ - `customer.updated`
1044
+ - `customer.deleted`
1045
+
1046
+ > Make sure you protect incoming requests with Reji's included [webhook signature verification](#verifying-webhook-signatures).
1047
+
1048
+ <a name="defining-webhook-event-handlers"></a>
1049
+ ### Defining Webhook Event Handlers
1050
+
1051
+ Reji automatically handles subscription cancellation on failed charges, but if you have additional webhook events you would like to handle, extend the Webhook controller. Your method names should correspond to Reji's expected convention, specifically, methods should be prefixed with `handle` and the "snake case" name of the webhook you wish to handle. For example, if you wish to handle the `invoice.payment_succeeded` webhook, you should add a `handle_invoice_payment_succeeded` method to the controller:
1052
+
1053
+ ```ruby
1054
+ class WebhookController < Reji::WebhookController
1055
+ def handle_invoice_payment_succeeded(payload)
1056
+ # Handle The Event
1057
+ end
1058
+ end
1059
+ ```
1060
+
1061
+ Next, define a route to your Reji controller within your `config/routes.rb` file. This will overwrite the default shipped route:
1062
+
1063
+ ```ruby
1064
+ post 'stripe/webhook', to: 'webhook#handle_webhook', as: 'webhook
1065
+ ```
1066
+
1067
+ <a name="handling-failed-subscriptions"></a>
1068
+ ### Failed Subscriptions
1069
+
1070
+ What if a customer's credit card expires? No worries - Reji's Webhook controller will cancel the customer's subscription for you. Failed payments will automatically be captured and handled by the controller. The controller will cancel the customer's subscription when Stripe determines the subscription has failed (normally after three failed payment attempts).
1071
+
1072
+ <a name="verifying-webhook-signatures"></a>
1073
+ ### Verifying Webhook Signatures
1074
+
1075
+ To secure your webhooks, you may use [Stripe's webhook signatures](https://stripe.com/docs/webhooks/signatures). For convenience, Reji automatically includes a filter which validates that the incoming Stripe webhook request is valid.
1076
+
1077
+ To enable webhook verification, ensure that the `STRIPE_WEBHOOK_SECRET` environment variable is set. The webhook `secret` may be retrieved from your Stripe account dashboard.
1078
+
1079
+ <a name="single-charges"></a>
1080
+ ## Single Charges
1081
+
1082
+ <a name="simple-charge"></a>
1083
+ ### Simple Charge
1084
+
1085
+ > The `charge` method accepts the amount you would like to charge in the **lowest denominator of the currency used by your application**.
1086
+
1087
+ If you would like to make a "one off" charge against a subscribed customer's payment method, you may use the `charge` method on a billable model instance. You'll need to [provide a payment method identifier](#storing-payment-methods) as the second argument:
1088
+
1089
+ ```ruby
1090
+ # Stripe Accepts Charges In Cents...
1091
+ stripe_charge = user.charge(100, payment_method)
1092
+ ```
1093
+
1094
+ The `charge` method accepts an array as its third argument, allowing you to pass any options you wish to the underlying Stripe charge creation. Consult the Stripe documentation regarding the options available to you when creating charges:
1095
+
1096
+ ```ruby
1097
+ user.charge(100, payment_method, {:custom_option => value})
1098
+ ```
1099
+
1100
+ You may also use the `charge` method without an underlying customer or user:
1101
+
1102
+ ```ruby
1103
+ stripe_charge = User.new.charge(100, payment_method)
1104
+ ```
1105
+
1106
+ The `charge` method will throw an exception if the charge fails. If the charge is successful, an instance of `Reji::Payment` will be returned from the method:
1107
+
1108
+ ```ruby
1109
+ begin
1110
+ payment = user.charge(100, payment_method)
1111
+ rescue => e
1112
+ #
1113
+ end
1114
+ ```
1115
+
1116
+ <a name="charge-with-invoice"></a>
1117
+ ### Charge With Invoice
1118
+
1119
+ Sometimes you may need to make a one-time charge but also generate an invoice for the charge so that you may offer a PDF receipt to your customer. The `invoice_for` method lets you do just that. For example, let's invoice the customer $5.00 for a "One Time Fee":
1120
+
1121
+ ```ruby
1122
+ # Stripe Accepts Charges In Cents...
1123
+ user.invoice_for('One Time Fee', 500)
1124
+ ```
1125
+
1126
+ The invoice will be charged immediately against the user's default payment method. The `invoice_for` method also accepts an array as its third argument. This array contains the billing options for the invoice item. The fourth argument accepted by the method is also an array. This final argument accepts the billing options for the invoice itself:
1127
+
1128
+ ```ruby
1129
+ user.invoice_for('Stickers', 500, {
1130
+ :quantity => 50,
1131
+ }, {
1132
+ :default_tax_rates => ['tax-rate-id'],
1133
+ })
1134
+ ```
1135
+
1136
+ > The `invoice_for` method will create a Stripe invoice which will retry failed billing attempts. If you do not want invoices to retry failed charges, you will need to close them using the Stripe API after the first failed charge.
1137
+
1138
+ <a name="refunding-charges"></a>
1139
+ ### Refunding Charges
1140
+
1141
+ If you need to refund a Stripe charge, you may use the `refund` method. This method accepts the Stripe Payment Intent ID as its first argument:
1142
+
1143
+ ```ruby
1144
+ payment = user.charge(100, payment_method)
1145
+ user.refund(payment.id)
1146
+ ```
1147
+
1148
+ <a name="invoices"></a>
1149
+ ## Invoices
1150
+
1151
+ <a name="retrieving-invoices"></a>
1152
+ ### Retrieving Invoices
1153
+
1154
+ You may easily retrieve an array of a billable model's invoices using the `invoices` method:
1155
+
1156
+ ```ruby
1157
+ invoices = user.invoices
1158
+
1159
+ # Include pending invoices in the results...
1160
+ invoices = user.invoices_including_pending
1161
+ ```
1162
+
1163
+ You may use the `find_invoice` method to retrieve a specific invoice:
1164
+
1165
+ ```ruby
1166
+ invoice = user.find_invoice(invoice_id)
1167
+ ```
1168
+
1169
+ #### Displaying Invoice Information
1170
+
1171
+ When listing the invoices for the customer, you may use the invoice's helper methods to display the relevant invoice information. For example, you may wish to list every invoice in a table, allowing the user to easily download any of them:
1172
+
1173
+ ```html
1174
+ <table>
1175
+ <% invoices.each do |invoice| %>
1176
+ <tr>
1177
+ <td><%= invoice.date %></td>
1178
+ <td><%= invoice.total %></td>
1179
+ <td><a href="/user/invoice/<%= invoice.id %>">Download</a></td>
1180
+ </tr>
1181
+ <% end %>
1182
+ </table>
1183
+ ```
1184
+
1185
+ <a name="generating-invoice-pdfs"></a>
1186
+ ### Generating Invoice PDFs
1187
+
1188
+ From within a controller, use the `download_invoice` method to generate a PDF download data of the invoice:
1189
+
1190
+ ```ruby
1191
+ class InvoicesController < ApplicationController
1192
+ before_action :authenticate_user!
1193
+
1194
+ def download
1195
+ response = current_user.download_invoice(params[:id], {
1196
+ :vendor => 'Your Company',
1197
+ :product => 'Your Product',
1198
+ })
1199
+
1200
+ send_data response[:data],
1201
+ :disposition => "inline; filename=#{response[:filename]}.pdf",
1202
+ :type => 'application/pdf'
1203
+ end
1204
+ end
1205
+ ```
1206
+
1207
+ The `download_invoice` method also allows for an optional custom filename as the third parameter. This filename will automatically be suffixed with `.pdf` for you:
1208
+
1209
+ ```ruby
1210
+ response = current_user.download_invoice(params[:id], {
1211
+ :vendor => 'Your Company',
1212
+ :product => 'Your Product',
1213
+ }, 'my-invoice')
1214
+ ```
1215
+
1216
+ <a name="handling-failed-payments"></a>
1217
+ ## Handling Failed Payments
1218
+
1219
+ Sometimes, payments for subscriptions or single charges can fail. When this happens, Reji will throw an `IncompletePaymentError` exception that informs you that this happened. After catching this exception, you have two options on how to proceed.
1220
+
1221
+ First, you could redirect your customer to the dedicated payment confirmation page which is included with Reji. This page already has an associated route that is registered via Reji's service provider. So, you may catch the `IncompletePaymentError` exception and redirect to the payment confirmation page:
1222
+
1223
+ ```ruby
1224
+ begin
1225
+ subscription = user.new_subscription('default', plan_id).create(payment_method)
1226
+ rescue Reji::IncompletePaymentError => e
1227
+ redirect_to "/stripe/payment/#{e.payment.id}?redirect=/"
1228
+ end
1229
+ ```
1230
+
1231
+ On the payment confirmation page, the customer will be prompted to enter their credit card info again and perform any additional actions required by Stripe, such as "3D Secure" confirmation. After confirming their payment, the user will be redirected to the URL provided by the `redirect` parameter specified above. Upon redirection, `message` (string) and `success` (integer) query string variables will be added to the URL.
1232
+
1233
+ Alternatively, you could allow Stripe to handle the payment confirmation for you. In this case, instead of redirecting to the payment confirmation page, you may [setup Stripe's automatic billing emails](https://dashboard.stripe.com/account/billing/automatic) in your Stripe dashboard. However, if a `IncompletePaymentError` exception is caught, you should still inform the user they will receive an email with further payment confirmation instructions.
1234
+
1235
+ Payment exceptions may be thrown for the following methods: `charge`, `invoice_for`, and `invoice` on the `Billable` user. When handling subscriptions, the `create` method on the `SubscriptionBuilder`, and the `increment_and_invoice` and `swap_and_invoice` methods on the `Subscription` model may throw exceptions.
1236
+
1237
+ There are currently two types of payment exceptions which extend `IncompletePaymentError`. You can catch these separately if needed so that you can customize the user experience:
1238
+
1239
+ <div class="content-list" markdown="1">
1240
+ - `PaymentActionRequiredError`: this indicates that Stripe requires extra verification in order to confirm and process a payment.
1241
+ - `PaymentFailureError`: this indicates that a payment failed for various other reasons, such as being out of available funds.
1242
+ </div>
1243
+
1244
+ #### Incomplete and Past Due State
1245
+
1246
+ When a payment needs additional confirmation, the subscription will remain in an `incomplete` or `past_due` state as indicated by its `stripe_status` database column. Reji will automatically activate the customer's subscription via a webhook as soon as payment confirmation is complete.
1247
+
1248
+ For more information on `incomplete` and `past_due` states, please refer to [our additional documentation](#incomplete-and-past-due-status).
1249
+
1250
+ <a name="stripe-sdk"></a>
1251
+ ## Stripe SDK
1252
+
1253
+ Many of Reji's objects are wrappers around Stripe SDK objects. If you would like to interact with the Stripe objects directly, you may conveniently retrieve them using the `as_stripe` method:
1254
+
1255
+ ```ruby
1256
+ stripe_subscription = subscription.as_stripe_subscription
1257
+ stripe_subscription.application_fee_percent = 5
1258
+ stripe_subscription.save
1259
+ ```
1260
+
1261
+ You may also use the `update_stripe_subscription` method to update the Stripe subscription directly:
1262
+
1263
+ ```ruby
1264
+ subscription.update_stripe_subscription({:application_fee_percent => 5})
1265
+ ```
1266
+
1267
+ <a name="testing"></a>
1268
+ ## Testing
1269
+
1270
+ When testing an application that uses Reji, you may mock the actual HTTP requests to the Stripe API; however, this requires you to partially re-implement Reji's own behavior. Therefore, we recommend allowing your tests to hit the actual Stripe API. While this is slower, it provides more confidence that your application is working as expected and any slow tests may be placed within their own testing group. You also should only focus on testing the subscription and payment flow of your own application and not every underlying Reji behavior
1271
+
1272
+ You will need to set the Stripe testing secret environment variable in order to run the Reji tests.
1273
+
1274
+ ```bash
1275
+ STRIPE_SECRET=sk_test_<your-key> rake spec
1276
+ ```
1277
+
1278
+ Whenever you interact with Reji while testing, it will send actual API requests to your Stripe testing environment. For convenience, you should pre-fill your Stripe testing account with subscriptions / plans that you may then use during testing.
1279
+
1280
+ > In order to test a variety of billing scenarios, such as credit card denials and failures, you may use the vast range of [testing card numbers and tokens](https://stripe.com/docs/testing) provided by Stripe.
1281
+
1282
+ <a name="license"></a>
1283
+ ## License
1284
+
1285
+ Reji is open-sourced software licensed under the MIT license.