pay 2.2.2 → 2.4.3

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of pay might be problematic. Click here for more details.

Files changed (47) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +142 -9
  3. data/Rakefile +2 -4
  4. data/app/controllers/pay/payments_controller.rb +2 -0
  5. data/app/controllers/pay/webhooks/braintree_controller.rb +1 -1
  6. data/app/controllers/pay/webhooks/paddle_controller.rb +36 -0
  7. data/app/mailers/pay/user_mailer.rb +14 -35
  8. data/app/models/pay/application_record.rb +6 -1
  9. data/app/models/pay/charge.rb +7 -0
  10. data/app/models/pay/subscription.rb +23 -8
  11. data/app/views/pay/user_mailer/payment_action_required.html.erb +1 -1
  12. data/app/views/pay/user_mailer/receipt.html.erb +6 -6
  13. data/app/views/pay/user_mailer/refund.html.erb +6 -6
  14. data/app/views/pay/user_mailer/subscription_renewing.html.erb +1 -1
  15. data/config/locales/en.yml +137 -0
  16. data/config/routes.rb +1 -0
  17. data/db/migrate/20200603134434_add_data_to_pay_models.rb +22 -0
  18. data/lib/pay.rb +9 -41
  19. data/lib/pay/billable.rb +14 -9
  20. data/lib/pay/braintree/billable.rb +21 -15
  21. data/lib/pay/braintree/charge.rb +7 -3
  22. data/lib/pay/braintree/subscription.rb +22 -8
  23. data/lib/pay/engine.rb +7 -0
  24. data/lib/pay/errors.rb +73 -0
  25. data/lib/pay/paddle.rb +38 -0
  26. data/lib/pay/paddle/billable.rb +95 -0
  27. data/lib/pay/paddle/charge.rb +39 -0
  28. data/lib/pay/paddle/subscription.rb +68 -0
  29. data/lib/pay/paddle/webhooks.rb +1 -0
  30. data/lib/pay/paddle/webhooks/signature_verifier.rb +115 -0
  31. data/lib/pay/paddle/webhooks/subscription_cancelled.rb +18 -0
  32. data/lib/pay/paddle/webhooks/subscription_created.rb +59 -0
  33. data/lib/pay/paddle/webhooks/subscription_payment_refunded.rb +21 -0
  34. data/lib/pay/paddle/webhooks/subscription_payment_succeeded.rb +43 -0
  35. data/lib/pay/paddle/webhooks/subscription_updated.rb +37 -0
  36. data/lib/pay/receipts.rb +6 -6
  37. data/lib/pay/stripe.rb +3 -0
  38. data/lib/pay/stripe/billable.rb +10 -4
  39. data/lib/pay/stripe/charge.rb +6 -2
  40. data/lib/pay/stripe/subscription.rb +21 -7
  41. data/lib/pay/stripe/webhooks/charge_refunded.rb +2 -2
  42. data/lib/pay/stripe/webhooks/charge_succeeded.rb +7 -7
  43. data/lib/pay/stripe/webhooks/payment_action_required.rb +7 -8
  44. data/lib/pay/stripe/webhooks/subscription_created.rb +1 -1
  45. data/lib/pay/stripe/webhooks/subscription_renewing.rb +4 -3
  46. data/lib/pay/version.rb +1 -1
  47. metadata +32 -40
@@ -2,6 +2,9 @@ module Pay
2
2
  class Charge < ApplicationRecord
3
3
  self.table_name = Pay.chargeable_table
4
4
 
5
+ # Only serialize for non-json columns
6
+ serialize :data unless json_column?("data")
7
+
5
8
  # Associations
6
9
  belongs_to :owner, polymorphic: true
7
10
 
@@ -39,5 +42,9 @@ module Pay
39
42
  def paypal?
40
43
  braintree? && card_type == "PayPal"
41
44
  end
45
+
46
+ def paddle?
47
+ processor == "paddle"
48
+ end
42
49
  end
43
50
  end
@@ -2,7 +2,10 @@ module Pay
2
2
  class Subscription < ApplicationRecord
3
3
  self.table_name = Pay.subscription_table
4
4
 
5
- STATUSES = %w[incomplete incomplete_expired trialing active past_due canceled unpaid]
5
+ STATUSES = %w[incomplete incomplete_expired trialing active past_due canceled unpaid paused]
6
+
7
+ # Only serialize for non-json columns
8
+ serialize :data unless json_column?("data")
6
9
 
7
10
  # Associations
8
11
  belongs_to :owner, polymorphic: true
@@ -26,6 +29,15 @@ module Pay
26
29
 
27
30
  attribute :prorate, :boolean, default: true
28
31
 
32
+ # Helpers for payment processors
33
+ %w[braintree stripe paddle].each do |processor_name|
34
+ define_method "#{processor_name}?" do
35
+ processor == processor_name
36
+ end
37
+
38
+ scope processor_name, -> { where(processor: processor_name) }
39
+ end
40
+
29
41
  def no_prorate
30
42
  self.prorate = false
31
43
  end
@@ -47,7 +59,8 @@ module Pay
47
59
  end
48
60
 
49
61
  def on_grace_period?
50
- canceled? && Time.zone.now < ends_at
62
+ return unless processor?
63
+ send("#{processor}_on_grace_period?")
51
64
  end
52
65
 
53
66
  def active?
@@ -66,6 +79,14 @@ module Pay
66
79
  past_due? || incomplete?
67
80
  end
68
81
 
82
+ def paused?
83
+ send("#{processor}_paused?")
84
+ end
85
+
86
+ def pause
87
+ send("#{processor}_pause")
88
+ end
89
+
69
90
  def cancel
70
91
  send("#{processor}_cancel")
71
92
  end
@@ -75,13 +96,7 @@ module Pay
75
96
  end
76
97
 
77
98
  def resume
78
- unless on_grace_period?
79
- raise StandardError,
80
- "You can only resume subscriptions within their grace period."
81
- end
82
-
83
99
  send("#{processor}_resume")
84
-
85
100
  update(ends_at: nil, status: "active")
86
101
  self
87
102
  end
@@ -1,6 +1,6 @@
1
1
  <h3>Extra confirmation is needed to process your payment</h3>
2
2
  <p>Your <%= Pay.business_name %> subscription requires confirmation to process your payment to continue access.</p>
3
3
 
4
- <p>You may confirm your payment via your account. If you have any questions, please hit reply and let us know.</p>
4
+ <p><%= link_to "Click here to confirm your payment", pay.payment_url(params[:payment_intent_id]) %>. If you have any questions, please hit reply and let us know.</p>
5
5
 
6
6
  <p>- The <%= Pay.business_name %> Team</p>
@@ -5,13 +5,13 @@ Questions? Please reply to this email.<br/>
5
5
  ------------------------------------<br/>
6
6
  RECEIPT - SUBSCRIPTION<br/>
7
7
  <br/>
8
- Amount: USD <%= ActionController::Base.helpers.number_to_currency(@charge.amount / 100.0) %><br/>
8
+ Amount: USD <%= ActionController::Base.helpers.number_to_currency(params[:charge].amount / 100.0) %><br/>
9
9
  <br/>
10
- Charged to: <%= @charge.charged_to %><br/>
11
- Transaction ID: <%= @charge.id %><br/>
12
- Date: <%= @charge.created_at %><br/>
13
- <% if @charge.owner.extra_billing_info? %>
14
- <%= @charge.owner.extra_billing_info %><br/>
10
+ Charged to: <%= params[:charge].charged_to %><br/>
11
+ Transaction ID: <%= params[:charge].id %><br/>
12
+ Date: <%= params[:charge].created_at %><br/>
13
+ <% if params[:charge].owner.extra_billing_info? %>
14
+ <%= params[:charge].owner.extra_billing_info %><br/>
15
15
  <% end %>
16
16
  <br/>
17
17
  <br/>
@@ -6,13 +6,13 @@ Questions? Please reply to this email.<br/>
6
6
  ------------------------------------<br/>
7
7
  RECEIPT - REFUND<br/>
8
8
  <br/>
9
- Amount: USD <%= ActionController::Base.helpers.number_to_currency(@charge.amount / 100.0) %><br/>
9
+ Amount: USD <%= ActionController::Base.helpers.number_to_currency(params[:charge].amount / 100.0) %><br/>
10
10
  <br/>
11
- Refunded to: <%= @charge.charged_to %><br/>
12
- Transaction ID: <%= @charge.id %><br/>
13
- Date: <%= @charge.created_at %><br/>
14
- <% if @charge.owner.extra_billing_info? %>
15
- <%= @charge.owner.extra_billing_info %><br/>
11
+ Refunded to: <%= params[:charge].charged_to %><br/>
12
+ Transaction ID: <%= params[:charge].id %><br/>
13
+ Date: <%= params[:charge].created_at %><br/>
14
+ <% if params[:charge].owner.extra_billing_info? %>
15
+ <%= params[:charge].owner.extra_billing_info %><br/>
16
16
  <% end %>
17
17
  <br/>
18
18
  <br/>
@@ -1,5 +1,5 @@
1
1
  <h3>Your upcoming subscription renewal</h3>
2
- <p>This is just a friendly reminder that your <%= Pay.business_name %> subscription will renew automatically on <%= @subscription %>.</p>
2
+ <p>This is just a friendly reminder that your <%= Pay.business_name %> subscription will renew automatically on <%= l params[:date].to_date, format: :long %>.</p>
3
3
 
4
4
  <p>You may manage your subscription via your account. If you have any questions, please hit reply and let us know.</p>
5
5
 
@@ -15,3 +15,140 @@ en:
15
15
  success: The payment was successful.
16
16
  all_rights_reserved: All rights reserved.
17
17
  back: Go back
18
+ receipt:
19
+ date: Date
20
+ account_billed: Account Billed
21
+ product: Product
22
+ amount: Amount
23
+ charged_to: Charged to
24
+ additional_info: Additional Info
25
+ errors:
26
+ action_required: "This payment attempt failed because additional action is required before it can be completed."
27
+ invalid_payment: "This payment attempt failed because of an invalid payment method."
28
+ email_required: "Email is required to create a customer"
29
+ no_processor: "No payment processor selected. Make sure to set the %{class_name}'s `processor` attribute to either 'stripe' or 'braintree'."
30
+ stripe:
31
+ errors:
32
+ account_already_exists: The email address provided for the creation of a deferred account already has an account associated with it. Use the OAuth flow to connect the existing account to your platform.
33
+ account_country_invalid_address: The country of the business address provided does not match the country of the account. Businesses must be located in the same country as the account.
34
+ account_invalid: The account ID provided as a value for the Stripe-Account header is invalid. Check that your requests are specifying a valid account ID.
35
+ account_number_invalid: The bank account number provided is invalid (e.g., missing digits). Bank account information varies from country to country. We recommend creating validations in your entry forms based on the bank account formats we provide.
36
+ alipay_upgrade_required: This method for creating Alipay payments is not supported anymore. Please upgrade your integration to use Sources instead.
37
+ amount_too_large: The specified amount is greater than the maximum amount allowed. Use a lower amount and try again.
38
+ amount_too_small: The specified amount is less than the minimum amount allowed. Use a higher amount and try again.
39
+ api_key_expired: The API key provided has expired. Obtain your current API keys from the Dashboard and update your integration to use them.
40
+ authentication_required: The payment requires authentication to proceed. If your customer is off session, notify your customer to return to your application and complete the payment. If you provided the error_on_requires_action parameter, then your customer should try another card that does not require authentication.
41
+ balance_insufficient: The transfer or payout could not be completed because the associated account does not have a sufficient balance available. Create a new transfer or payout using an amount less than or equal to the account’s available balance.
42
+ bank_account_declined: The bank account provided can not be used to charge, either because it is not verified yet or it is not supported.
43
+ bank_account_exists: The bank account provided already exists on the specified Customer object. If the bank account should also be attached to a different customer, include the correct customer ID when making the request again.
44
+ bank_account_unusable: The bank account provided cannot be used for payouts. A different bank account must be used.
45
+ bank_account_unverified: Your Connect platform is attempting to share an unverified bank account with a connected account.
46
+ bank_account_verification_failed: The bank account cannot be verified, either because the microdeposit amounts provided do not match the actual amounts, or because verification has failed too many times.
47
+ bitcoin_upgrade_required: This method for creating Bitcoin payments is not supported anymore. Please upgrade your integration to use Sources instead.
48
+ card_decline_rate_limit_exceeded: This card has been declined too many times. You can try to charge this card again after 24 hours. We suggest reaching out to your customer to make sure they have entered all of their information correctly and that there are no issues with their card.
49
+ card_declined: The card has been declined. When a card is declined, the error returned also includes the decline_code attribute with the reason why the card was declined. Refer to our decline codes documentation to learn more.
50
+ charge_already_captured: The charge you’re attempting to capture has already been captured. Update the request with an uncaptured charge ID.
51
+ charge_already_refunded: The charge you’re attempting to refund has already been refunded. Update the request to use the ID of a charge that has not been refunded.
52
+ charge_disputed: The charge you’re attempting to refund has been charged back. Check the disputes documentation to learn how to respond to the dispute.
53
+ charge_exceeds_source_limit: This charge would cause you to exceed your rolling-window processing limit for this source type. Please retry the charge later, or contact us to request a higher processing limit.
54
+ charge_expired_for_capture: The charge cannot be captured as the authorization has expired. Auth and capture charges must be captured within seven days.
55
+ charge_invalid_parameter: One or more provided parameters was not allowed for the given operation on the Charge. Check our API reference or the returned error message to see which values were not correct for that Charge.
56
+ clearing_code_unsupported: The clearing code provided is not supported.
57
+ country_code_invalid: The country code provided was invalid.
58
+ country_unsupported: Your platform attempted to create a custom account in a country that is not yet supported. Make sure that users can only sign up in countries supported by custom accounts.
59
+ coupon_expired: The coupon provided for a subscription or order has expired. Either create a new coupon, or use an existing one that is valid.
60
+ customer_max_payment_methods: The maximum number of PaymentMethods for this Customer has been reached. Either detach some PaymentMethods from this Customer or proceed with a different Customer.
61
+ customer_max_subscriptions: The maximum number of subscriptions for a customer has been reached. Contact us if you are receiving this error.
62
+ email_invalid: The email address is invalid (e.g., not properly formatted). Check that the email address is properly formatted and only includes allowed characters.
63
+ expired_card: The card has expired. Check the expiration date or use a different card.
64
+ idempotency_key_in_use: The idempotency key provided is currently being used in another request. This occurs if your integration is making duplicate requests simultaneously.
65
+ incorrect_address: The card’s address is incorrect. Check the card’s address or use a different card.
66
+ incorrect_cvc: The card’s security code is incorrect. Check the card’s security code or use a different card.
67
+ incorrect_number: The card number is incorrect. Check the card’s number or use a different card.
68
+ incorrect_zip: The card’s postal code is incorrect. Check the card’s postal code or use a different card.
69
+ instant_payouts_unsupported: This card is not eligible for Instant Payouts. Try a debit card from a supported bank.
70
+ intent_invalid_state: Intent is not the state that is rquired to perform the operation.
71
+ intent_verification_method_missing: Intent does not have verification method specified in its PaymentMethodOptions object.
72
+ invalid_card_type: The card provided as an external account is not supported for payouts. Provide a non-prepaid debit card instead.
73
+ invalid_characters: This value provided to the field contains characters that are unsupported by the field.
74
+ invalid_charge_amount: The specified amount is invalid. The charge amount must be a positive integer in the smallest currency unit, and not exceed the minimum or maximum amount.
75
+ invalid_cvc: The card’s security code is invalid. Check the card’s security code or use a different card.
76
+ invalid_expiry_month: The card’s expiration month is incorrect. Check the expiration date or use a different card.
77
+ invalid_expiry_year: The card’s expiration year is incorrect. Check the expiration date or use a different card.
78
+ invalid_number: The card number is invalid. Check the card details or use a different card.
79
+ invalid_source_usage: The source cannot be used because it is not in the correct state (e.g., a charge request is trying to use a source with a pending, failed, or consumed source). Check the status of the source you are attempting to use.
80
+ invoice_no_customer_line_items: An invoice cannot be generated for the specified customer as there are no pending invoice items. Check that the correct customer is being specified or create any necessary invoice items first.
81
+ invoice_no_payment_method_types: An invoice cannot be finalized because there are no payment method types available to process the payment. Your invoice template settings or the invoice’s payment_settings might be restricting which payment methods are available, or you might need to activate more payment methods in the Dashboard.
82
+ invoice_no_subscription_line_items: An invoice cannot be generated for the specified subscription as there are no pending invoice items. Check that the correct subscription is being specified or create any necessary invoice items first.
83
+ invoice_not_editable: The specified invoice can no longer be edited. Instead, consider creating additional invoice items that will be applied to the next invoice. You can either manually generate the next invoice or wait for it to be automatically generated at the end of the billing cycle.
84
+ invoice_payment_intent_requires_action: This payment requires additional user action before it can be completed successfully. Payment can be completed using the PaymentIntent associated with the invoice. See this page for more details.
85
+ invoice_upcoming_none: There is no upcoming invoice on the specified customer to preview. Only customers with active subscriptions or pending invoice items have invoices that can be previewed.
86
+ livemode_mismatch: Test and live mode API keys, requests, and objects are only available within the mode they are in.
87
+ lock_timeout: This object cannot be accessed right now because another API request or Stripe process is currently accessing it. If you see this error intermittently, retry the request. If you see this error frequently and are making multiple concurrent requests to a single object, make your requests serially or at a lower rate. See the rate limit documentation for more details.
88
+ missing: Both a customer and source ID have been provided, but the source has not been saved to the customer. To create a charge for a customer with a specified source, you must first save the card details.
89
+ not_allowed_on_standard_account: Transfers and payouts on behalf of a Standard connected account are not allowed.
90
+ order_creation_failed: The order could not be created. Check the order details and then try again.
91
+ order_required_settings: The order could not be processed as it is missing required information. Check the information provided and try again.
92
+ order_status_invalid: The order cannot be updated because the status provided is either invalid or does not follow the order lifecycle (e.g., an order cannot transition from created to fulfilled without first transitioning to paid).
93
+ order_upstream_timeout: The request timed out. Try again later.
94
+ out_of_inventory: The SKU is out of stock. If more stock is available, update the SKU’s inventory quantity and try again.
95
+ parameter_invalid_empty: One or more required values were not provided. Make sure requests include all required parameters.
96
+ parameter_invalid_integer: One or more of the parameters requires an integer, but the values provided were a different type. Make sure that only supported values are provided for each attribute. Refer to our API documentation to look up the type of data each attribute supports.
97
+ parameter_invalid_string_blank: One or more values provided only included whitespace. Check the values in your request and update any that contain only whitespace.
98
+ parameter_invalid_string_empty: One or more required string values is empty. Make sure that string values contain at least one character.
99
+ parameter_missing: One or more required values are missing. Check our API documentation to see which values are required to create or modify the specified resource.
100
+ parameter_unknown: The request contains one or more unexpected parameters. Remove these and try again.
101
+ parameters_exclusive: Two or more mutually exclusive parameters were provided. Check our API documentation or the returned error message to see which values are permitted when creating or modifying the specified resource.
102
+ payment_intent_action_required: The provided payment method requires customer actions to complete, but error_on_requires_action was set. If you’d like to add this payment method to your integration, we recommend that you first upgrade your integration to handle actions.
103
+ payment_intent_authentication_failure: The provided payment method has failed authentication. Provide a new payment method to attempt to fulfill this PaymentIntent again.
104
+ payment_intent_incompatible_payment_method: The PaymentIntent expected a payment method with different properties than what was provided.
105
+ payment_intent_invalid_parameter: One or more provided parameters was not allowed for the given operation on the PaymentIntent. Check our API reference or the returned error message to see which values were not correct for that PaymentIntent.
106
+ payment_intent_payment_attempt_failed: The latest payment attempt for the PaymentIntent has failed. Check the last_payment_error property on the PaymentIntent for more details, and provide a new payment method to attempt to fulfill this PaymentIntent again.
107
+ payment_intent_unexpected_state: The PaymentIntent’s state was incompatible with the operation you were trying to perform.
108
+ payment_method_invalid_parameter: Invalid parameter was provided in the payment method object. Check our API documentation or the returned error message for more context.
109
+ payment_method_provider_decline: The payment was declined by the issuer or customer. Check the last_payment_error property on the PaymentIntent for more details, and provide a new payment method to attempt to fulfill this PaymentIntent again.
110
+ payment_method_provider_timeout: The payment method failed due to a timeout. Check the last_payment_error property on the PaymentIntent for more details, and provide a new payment method to attempt to fulfill this PaymentIntent again.
111
+ payment_method_unactivated: The operation cannot be performed as the payment method used has not been activated. Activate the payment method in the Dashboard, then try again.
112
+ payment_method_unexpected_state: The provided payment method’s state was incompatible with the operation you were trying to perform. Confirm that the payment method is in an allowed state for the given operation before attempting to perform it.
113
+ payment_method_unsupported_type: The API only supports payment methods of certain types.
114
+ payouts_not_allowed: Payouts have been disabled on the connected account. Check the connected account’s status to see if any additional information needs to be provided, or if payouts have been disabled for another reason.
115
+ platform_api_key_expired: The API key provided by your Connect platform has expired. This occurs if your platform has either generated a new key or the connected account has been disconnected from the platform. Obtain your current API keys from the Dashboard and update your integration, or reach out to the user and reconnect the account.
116
+ postal_code_invalid: The postal code provided was incorrect.
117
+ processing_error: An error occurred while processing the card. Try again later or with a different payment method.
118
+ product_inactive: The product this SKU belongs to is no longer available for purchase.
119
+ rate_limit: Too many requests hit the API too quickly. We recommend an exponential backoff of your requests.
120
+ resource_already_exists: A resource with a user-specified ID (e.g., plan or coupon) already exists. Use a different, unique value for id and try again.
121
+ resource_missing: The ID provided is not valid. Either the resource does not exist, or an ID for a different resource has been provided.
122
+ routing_number_invalid: The bank routing number provided is invalid.
123
+ secret_key_required: The API key provided is a publishable key, but a secret key is required. Obtain your current API keys from the Dashboard and update your integration to use them.
124
+ sepa_unsupported_account: Your account does not support SEPA payments.
125
+ setup_attempt_failed: The latest setup attempt for the SetupIntent has failed. Check the last_setup_error property on the SetupIntent for more details, and provide a new payment method to attempt to set it up again.
126
+ setup_intent_authentication_failure: The provided payment method has failed authentication. Provide a new payment method to attempt to fulfill this SetupIntent again.
127
+ setup_intent_invalid_parameter: One or more provided parameters was not allowed for the given operation on the SetupIntent. Check our API reference or the returned error message to see which values were not correct for that SetupIntent.
128
+ setup_intent_unexpected_state: The SetupIntent’s state was incompatible with the operation you were trying to perform.
129
+ shipping_calculation_failed: Shipping calculation failed as the information provided was either incorrect or could not be verified.
130
+ sku_inactive: The SKU is inactive and no longer available for purchase. Use a different SKU, or make the current SKU active again.
131
+ state_unsupported: Occurs when providing the legal_entity information for a U.S. custom account, if the provided state is not supported. (This is mostly associated states and territories.)
132
+ tax_id_invalid: The tax ID number provided is invalid (e.g., missing digits). Tax ID information varies from country to country, but must be at least nine digits.
133
+ taxes_calculation_failed: Tax calculation for the order failed.
134
+ terminal_location_country_unsupported: Terminal is currently only available in some countries. Locations in your country cannot be created in livemode.
135
+ testmode_charges_only: Your account has not been activated and can only make test charges. Activate your account in the Dashboard to begin processing live charges.
136
+ tls_version_unsupported: Your integration is using an older version of TLS that is unsupported. You must be using TLS 1.2 or above.
137
+ token_already_used: The token provided has already been used. You must create a new token before you can retry this request.
138
+ token_in_use: The token provided is currently being used in another request. This occurs if your integration is making duplicate requests simultaneously.
139
+ transfers_not_allowed: The requested transfer cannot be created. Contact us if you are receiving this error.
140
+ upstream_order_creation_failed: The order could not be created. Check the order details and then try again.
141
+ url_invalid: The URL provided is invalid.
142
+ braintree:
143
+ authorization: "Either the data you submitted is malformed and does not match the API or the API key you used may not be authorized to perform this action."
144
+
145
+ pay:
146
+ user_mailer:
147
+ receipt:
148
+ subject: "Payment receipt"
149
+ refund:
150
+ subject: "Payment refunded"
151
+ subscription_renewing:
152
+ subject: "Your upcoming subscription renewal"
153
+ payment_action_required:
154
+ subject: "Confirm your payment"
data/config/routes.rb CHANGED
@@ -4,4 +4,5 @@ Pay::Engine.routes.draw do
4
4
  resources :payments, only: [:show], module: :pay
5
5
  post "webhooks/stripe", to: "stripe_event/webhook#event"
6
6
  post "webhooks/braintree", to: "pay/webhooks/braintree#create"
7
+ post "webhooks/paddle", to: "pay/webhooks/paddle#create"
7
8
  end
@@ -0,0 +1,22 @@
1
+ class AddDataToPayModels < ActiveRecord::Migration[4.2]
2
+ def change
3
+ add_column :pay_subscriptions, :data, data_column_type
4
+ add_column :pay_charges, :data, data_column_type
5
+ end
6
+
7
+ def data_column_type
8
+ default_hash = ActiveRecord::Base.configurations.default_hash
9
+
10
+ # Rails 6.1 uses a symbol key instead of a string
11
+ adapter = default_hash.dig(:adapter) || default_hash.dig("adapter")
12
+
13
+ case adapter
14
+ when "mysql2"
15
+ :json
16
+ when "postgresql"
17
+ :jsonb
18
+ else
19
+ :text
20
+ end
21
+ end
22
+ end
data/lib/pay.rb CHANGED
@@ -2,6 +2,7 @@ require "pay/engine"
2
2
  require "pay/billable"
3
3
  require "pay/receipts"
4
4
  require "pay/payment"
5
+ require "pay/errors"
5
6
 
6
7
  module Pay
7
8
  # Define who owns the subscription
@@ -12,6 +13,9 @@ module Pay
12
13
  @@billable_class = "User"
13
14
  @@billable_table = @@billable_class.tableize
14
15
 
16
+ mattr_accessor :model_parent_class
17
+ @@model_parent_class = "ApplicationRecord"
18
+
15
19
  mattr_accessor :chargeable_class
16
20
  mattr_accessor :chargeable_table
17
21
  @@chargeable_class = "Pay::Charge"
@@ -44,6 +48,11 @@ module Pay
44
48
  mattr_accessor :automount_routes
45
49
  @@automount_routes = true
46
50
 
51
+ mattr_accessor :default_product_name
52
+ @@default_product_name = "default"
53
+ mattr_accessor :default_plan_name
54
+ @@default_plan_name = "default"
55
+
47
56
  mattr_accessor :routes_path
48
57
  @@routes_path = "/pay"
49
58
 
@@ -98,45 +107,4 @@ module Pay
98
107
  business_address &&
99
108
  support_email
100
109
  end
101
-
102
- class Error < StandardError
103
- end
104
-
105
- class BraintreeError < Error
106
- attr_reader :result
107
-
108
- def initialize(result = nil)
109
- @result = result
110
- end
111
- end
112
-
113
- class BraintreeAuthorizationError < BraintreeError
114
- def message
115
- "Either the data you submitted is malformed and does not match the API or the API key you used may not be authorized to perform this action."
116
- end
117
- end
118
-
119
- class InvalidPaymentMethod < Error
120
- attr_reader :payment
121
-
122
- def initialize(payment)
123
- @payment = payment
124
- end
125
-
126
- def message
127
- "This payment attempt failed because of an invalid payment method."
128
- end
129
- end
130
-
131
- class ActionRequired < Error
132
- attr_reader :payment
133
-
134
- def initialize(payment)
135
- @payment = payment
136
- end
137
-
138
- def message
139
- "This payment attempt failed because additional action is required before it can be completed."
140
- end
141
- end
142
110
  end
data/lib/pay/billable.rb CHANGED
@@ -19,6 +19,7 @@ module Pay
19
19
  include Pay::Billable::SyncEmail
20
20
  include Pay::Stripe::Billable if defined? ::Stripe
21
21
  include Pay::Braintree::Billable if defined? ::Braintree
22
+ include Pay::Paddle::Billable if defined? ::PaddlePay
22
23
 
23
24
  has_many :charges, class_name: Pay.chargeable_class, foreign_key: :owner_id, inverse_of: :owner, as: :owner
24
25
  has_many :subscriptions, class_name: Pay.subscription_class, foreign_key: :owner_id, inverse_of: :owner, as: :owner
@@ -35,7 +36,7 @@ module Pay
35
36
 
36
37
  def customer
37
38
  check_for_processor
38
- raise Pay::Error, "Email is required to create a customer" if email.nil?
39
+ raise Pay::Error, I18n.t("errors.email_required") if email.nil?
39
40
 
40
41
  customer = send("#{processor}_customer")
41
42
  update_card(card_token) if card_token.present?
@@ -51,7 +52,7 @@ module Pay
51
52
  send("create_#{processor}_charge", amount_in_cents, options)
52
53
  end
53
54
 
54
- def subscribe(name: "default", plan: "default", **options)
55
+ def subscribe(name: Pay.default_product_name, plan: Pay.default_plan_name, **options)
55
56
  check_for_processor
56
57
  send("create_#{processor}_subscription", name, plan, options)
57
58
  end
@@ -62,7 +63,7 @@ module Pay
62
63
  send("update_#{processor}_card", token)
63
64
  end
64
65
 
65
- def on_trial?(name: "default", plan: nil)
66
+ def on_trial?(name: Pay.default_product_name, plan: nil)
66
67
  return true if default_generic_trial?(name, plan)
67
68
 
68
69
  sub = subscription(name: name)
@@ -80,7 +81,7 @@ module Pay
80
81
  send("#{processor}_subscription", subscription_id, options)
81
82
  end
82
83
 
83
- def subscribed?(name: "default", processor_plan: nil)
84
+ def subscribed?(name: Pay.default_product_name, processor_plan: nil)
84
85
  subscription = subscription(name: name)
85
86
 
86
87
  return false if subscription.nil?
@@ -89,13 +90,13 @@ module Pay
89
90
  subscription.active? && subscription.processor_plan == processor_plan
90
91
  end
91
92
 
92
- def on_trial_or_subscribed?(name: "default", processor_plan: nil)
93
+ def on_trial_or_subscribed?(name: Pay.default_product_name, processor_plan: nil)
93
94
  on_trial?(name: name, plan: processor_plan) ||
94
95
  subscribed?(name: name, processor_plan: processor_plan)
95
96
  end
96
97
 
97
- def subscription(name: "default")
98
- subscriptions.for_name(name).last
98
+ def subscription(name: Pay.default_product_name)
99
+ subscriptions.loaded? ? subscriptions.reverse.detect { |s| s.name == name } : subscriptions.for_name(name).last
99
100
  end
100
101
 
101
102
  def invoice!(options = {})
@@ -118,14 +119,18 @@ module Pay
118
119
  braintree? && card_type == "PayPal"
119
120
  end
120
121
 
121
- def has_incomplete_payment?(name: "default")
122
+ def paddle?
123
+ processor == "paddle"
124
+ end
125
+
126
+ def has_incomplete_payment?(name: Pay.default_product_name)
122
127
  subscription(name: name)&.has_incomplete_payment?
123
128
  end
124
129
 
125
130
  private
126
131
 
127
132
  def check_for_processor
128
- raise StandardError, "No payment processor selected. Make sure to set the #{self.class.name}'s `processor` attribute to either 'stripe' or 'braintree'." unless processor
133
+ raise StandardError, I18n.t("errors.no_processor", class_name: self.class.name) unless processor
129
134
  end
130
135
 
131
136
  # Used for creating a Pay::Subscription in the database