repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/braintree/braintree_card_type.rb
app/business/payments/charging/implementations/braintree/braintree_card_type.rb
# frozen_string_literal: true class BraintreeCardType CARD_TYPES = { "Visa" => CardType::VISA, "American Express" => CardType::AMERICAN_EXPRESS, "MasterCard" => CardType::MASTERCARD, "Discover" => CardType::DISCOVER, "JCB" => CardType::JCB, "Diners Club" => CardType::DINERS_CLUB, CardType::PAYPAL => CardType::PAYPAL }.freeze def self.to_card_type(braintree_card_type) type = CARD_TYPES[braintree_card_type] type = CardType::UNKNOWN if type.nil? type end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/braintree/braintree_charge.rb
app/business/payments/charging/implementations/braintree/braintree_charge.rb
# frozen_string_literal: true class BraintreeCharge < BaseProcessorCharge def initialize(braintree_charge, load_extra_details:) self.charge_processor_id = BraintreeChargeProcessor.charge_processor_id self.zip_check_result = nil self.id = braintree_charge.id self.status = braintree_charge.status.to_s.downcase self.refunded = braintree_charge.try(:refunded?) self.fee = nil currency = Currency::USD amount_cents = (braintree_charge.amount * 100).to_i self.flow_of_funds = FlowOfFunds.build_simple_flow_of_funds(currency, amount_cents) load_details_from_paypal(braintree_charge) if load_extra_details return unless braintree_charge.credit_card_details load_card_details(braintree_charge.credit_card_details) load_extra_card_details(braintree_charge.credit_card_details) if load_extra_details end private def load_card_details(braintree_credit_card) self.card_instance_id = braintree_credit_card.token self.card_last4 = braintree_credit_card.last_4 if braintree_credit_card.last_4.present? self.card_type = BraintreeCardType.to_card_type(braintree_credit_card.card_type) self.card_number_length = ChargeableVisual.get_card_length_from_card_type(card_type) if braintree_credit_card.card_type.present? self.card_expiry_month = braintree_credit_card.expiration_month if braintree_credit_card.expiration_month.present? self.card_expiry_year = braintree_credit_card.expiration_year if braintree_credit_card.expiration_year.present? self.card_country = Compliance::Countries.find_by_name(braintree_credit_card.country_of_issuance)&.alpha2 if braintree_credit_card.country_of_issuance.present? end def load_extra_card_details(braintree_credit_card) braintree_payment_method = Braintree::PaymentMethod.find(braintree_credit_card.token) if braintree_payment_method.is_a?(Braintree::CreditCard) self.card_fingerprint = braintree_payment_method.unique_number_identifier self.card_zip_code = braintree_payment_method.billing_address.postal_code if braintree_payment_method.billing_address elsif braintree_payment_method.is_a?(Braintree::PayPalAccount) self.card_fingerprint = PaypalCardFingerprint.build_paypal_fingerprint(braintree_payment_method.email) end rescue Braintree::ValidationsFailed, Braintree::ServerError, Braintree::NotFoundError => e raise ChargeProcessorInvalidRequestError.new(original_error: e) rescue *BraintreeExceptions::UNAVAILABLE => e raise ChargeProcessorUnavailableError.new(original_error: e) end def load_details_from_paypal(braintree_charge) paypal_txn_details = PayPal::SDK::Merchant::API.new.get_transaction_details( PayPal::SDK::Merchant::API.new.build_get_transaction_details( TransactionID: braintree_charge.paypal_details.capture_id)) self.disputed = paypal_txn_details.PaymentTransactionDetails.PaymentInfo.PaymentStatus.to_s.downcase == PaypalApiPaymentStatus::REVERSED.downcase end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/braintree/braintree_charge_intent.rb
app/business/payments/charging/implementations/braintree/braintree_charge_intent.rb
# frozen_string_literal: true class BraintreeChargeIntent < ChargeIntent def initialize(charge: nil) self.charge = charge end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/braintree/braintree_chargeable_base.rb
app/business/payments/charging/implementations/braintree/braintree_chargeable_base.rb
# frozen_string_literal: true class BraintreeChargeableBase attr_accessor :braintree_device_data attr_reader :payment_method_id def charge_processor_id BraintreeChargeProcessor.charge_processor_id end def prepare! raise NotImplementedError end def funding_type nil end def fingerprint return @card.unique_number_identifier if @card return PaypalCardFingerprint.build_paypal_fingerprint(@paypal.email) if @paypal nil end def last4 return @card.last_4 if @card nil end def visual return ChargeableVisual.build_visual(last4, number_length) if last4.present? && number_length.present? return @paypal.email if @paypal nil end def number_length return ChargeableVisual.get_card_length_from_card_type(card_type) if @card && card_type nil end def expiry_month @card.try(:expiration_month) end def expiry_year @card.try(:expiration_year) end def zip_code return @card.billing_address.postal_code if @card&.billing_address @zip_code end def card_type return BraintreeCardType.to_card_type(@card.card_type) if @card return CardType::PAYPAL if @paypal nil end def country BraintreeChargeCountry.to_card_country(@card.country_of_issuance) if @card end def reusable_token!(user) prepare! @customer = Braintree::Customer.update!(@customer.id, company: user.id) if user && user.id != @customer.company @customer.id rescue Braintree::ValidationsFailed, Braintree::ServerError => e raise ChargeProcessorInvalidRequestError.new(original_error: e) rescue *BraintreeExceptions::UNAVAILABLE => e raise ChargeProcessorUnavailableError.new(original_error: e) end def braintree_customer_id prepare! @customer.id end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/stripe/stripe_charge_processor.rb
app/business/payments/charging/implementations/stripe/stripe_charge_processor.rb
# frozen_string_literal: true class StripeChargeProcessor include StripeErrorHandler extend CurrencyHelper DISPLAY_NAME = "Stripe" # https://stripe.com/docs/api/charges/object#charge_object-status VALID_TRANSACTION_STATUSES = %w(succeeded pending).freeze # https://stripe.com/docs/api/refunds/create#create_refund-reason REFUND_REASON_FRAUDULENT = "fraudulent" MANDATE_PREFIX = "Mandate-" REQUEST_MANUAL_3DS_PARAMS = { payment_method_options: { card: { request_three_d_secure: "any" } } }.freeze private_constant :REQUEST_MANUAL_3DS_PARAMS def self.charge_processor_id "stripe" end def merchant_migrated?(merchant_account) merchant_account&.is_a_stripe_connect_account? end def get_chargeable_for_params(params, _gumroad_guid) zip_code = params[:cc_zipcode] if params[:cc_zipcode_required] product_permalink = params[:product_permalink] if params[:stripe_token].present? StripeChargeableToken.new(params[:stripe_token], zip_code, product_permalink:) elsif params[:stripe_payment_method_id].present? StripeChargeablePaymentMethod.new(params[:stripe_payment_method_id], customer_id: params[:stripe_customer_id], stripe_setup_intent_id: params[:stripe_setup_intent_id], zip_code:, product_permalink:) end end def get_chargeable_for_data(reusable_token, payment_method_id, fingerprint, stripe_setup_intent_id, stripe_payment_intent_id, last4, number_length, visual, expiry_month, expiry_year, card_type, country, zip_code = nil, merchant_account: nil) StripeChargeableCreditCard.new(merchant_account, reusable_token, payment_method_id, fingerprint, stripe_setup_intent_id, stripe_payment_intent_id, last4, number_length, visual, expiry_month, expiry_year, card_type, country, zip_code) end # Ref https://stripe.com/docs/api/charges/list # for details of all API parameters used in this method. def search_charge(purchase:) charges = if purchase.charged_using_stripe_connect_account? Stripe::Charge.list({ transfer_group: purchase.charge.present? ? purchase.charge.id_with_prefix : purchase.id }, { stripe_account: purchase.merchant_account.charge_processor_merchant_id }) else Stripe::Charge.list(transfer_group: purchase.charge.present? ? purchase.charge.id_with_prefix : purchase.id) end if charges.present? charges.data[0] else search_charge_by_metadata(purchase:) end end def search_charge_by_metadata(purchase:, last_charge_in_page: nil) charges = if last_charge_in_page purchase.charged_using_stripe_connect_account? ? Stripe::Charge.list({ created: { 'gte': purchase.created_at.to_i }, starting_after: last_charge_in_page, limit: 100 }, { stripe_account: purchase.merchant_account.charge_processor_merchant_id }) : Stripe::Charge.list(created: { 'gte': purchase.created_at.to_i }, starting_after: last_charge_in_page, limit: 100) else # List all charges from the 30 second window starting purchase.created_at, # and then look for purchase.external_id in the metadata # Increase the number of objects to be returned to 100. Limit can range between 1 and 100, and the default is 10. purchase.charged_using_stripe_connect_account? ? Stripe::Charge.list({ created: { 'gte': purchase.created_at.to_i, 'lte': purchase.created_at.to_i + 30 }, limit: 100 }, { stripe_account: purchase.merchant_account.charge_processor_merchant_id }) : Stripe::Charge.list(created: { 'gte': purchase.created_at.to_i, 'lte': purchase.created_at.to_i + 30 }, limit: 100) end find_charge_or_get_next_page(charges, purchase:) end def find_charge_or_get_next_page(charges, purchase:) if charges.present? charges.data.each do |charge| return charge if charge[:metadata].to_s.include?(purchase.external_id) end # Stripe returns charges in sorted order, with recent charges listed first. # So if there are more than 100 charges in the 30 second window, # we would need to fetch them in batches of 100 (newest to oldest) # until we find the charge or we run out of charges. search_charge_by_metadata(purchase:, last_charge_in_page: charges.data.last) if charges.has_more end end def get_charge(charge_id, merchant_account: nil) with_stripe_error_handler do if merchant_migrated? merchant_account begin charge = Stripe::Charge.retrieve({ id: charge_id, expand: %w[balance_transaction application_fee.balance_transaction] }, { stripe_account: merchant_account.charge_processor_merchant_id }) rescue StandardError => e Rails.logger.error("Falling back to retrieving charge from Gumroad due to #{e.inspect}") charge = Stripe::Charge.retrieve(id: charge_id, expand: %w[balance_transaction application_fee.balance_transaction]) end else charge = Stripe::Charge.retrieve(id: charge_id, expand: %w[balance_transaction application_fee.balance_transaction]) end get_charge_object(charge) end end def get_charge_object(charge) if charge[:transfer_data] destination_transfer = Stripe::Transfer.retrieve(id: charge.transfer) stripe_destination_payment = Stripe::Charge.retrieve({ id: destination_transfer.destination_payment, expand: %w[balance_transaction] }, { stripe_account: destination_transfer.destination }) end balance_transaction = charge.balance_transaction if balance_transaction.is_a?(String) merchant_account = Purchase.find(charge.transfer_group).merchant_account rescue nil balance_transaction = merchant_account&.is_a_stripe_connect_account? ? Stripe::BalanceTransaction.retrieve({ id: balance_transaction }, { stripe_account: merchant_account.charge_processor_merchant_id }) : Stripe::BalanceTransaction.retrieve({ id: balance_transaction }) end StripeCharge.new(charge, balance_transaction, charge.application_fee.try(:balance_transaction), stripe_destination_payment.try(:balance_transaction), destination_transfer) end def get_charge_intent(payment_intent_id, merchant_account: nil) with_stripe_error_handler do if merchant_migrated? merchant_account if merchant_account.charge_processor_merchant_id.blank? raise "Merchant Account #{merchant_account.external_id} assigned to user #{merchant_account.user.external_id} "\ "but has no Charge Processor Merchant ID." end payment_intent = Stripe::PaymentIntent.retrieve(payment_intent_id, { stripe_account: merchant_account.charge_processor_merchant_id }) else payment_intent = Stripe::PaymentIntent.retrieve(payment_intent_id) end StripeChargeIntent.new(payment_intent:, merchant_account:) end end def get_setup_intent(setup_intent_id, merchant_account: nil) with_stripe_error_handler do if merchant_migrated? merchant_account if merchant_account.charge_processor_merchant_id.blank? raise "Merchant Account #{merchant_account.external_id} assigned to user #{merchant_account.user.external_id} "\ "but has no Charge Processor Merchant ID." end setup_intent = Stripe::SetupIntent.retrieve(setup_intent_id, { stripe_account: merchant_account.charge_processor_merchant_id }) else setup_intent = Stripe::SetupIntent.retrieve(setup_intent_id) end StripeSetupIntent.new(setup_intent) end end def setup_future_charges!(merchant_account, chargeable, mandate_options: nil) params = { payment_method_types: ["card"], usage: "off_session" } params.merge!(chargeable.stripe_charge_params) params.merge!(mandate_options) if mandate_options.present? # Request 3DS manually when preparing future charges for all Indian cards. Ref: https://github.com/gumroad/web/issues/20783 chargeable.prepare! # loads the payment method's info, including card country params.deep_merge!(REQUEST_MANUAL_3DS_PARAMS) if chargeable.country == Compliance::Countries::IND.alpha2 with_stripe_error_handler do if merchant_migrated? merchant_account if merchant_account.charge_processor_merchant_id.blank? raise "Merchant Account #{merchant_account.external_id} assigned to user #{merchant_account.user.external_id} "\ "but has no Charge Processor Merchant ID." end setup_intent = Stripe::SetupIntent.create(params, { stripe_account: merchant_account.charge_processor_merchant_id }) elsif merchant_account.user if merchant_account.charge_processor_merchant_id.blank? raise "Merchant Account #{merchant_account.external_id} assigned to user #{merchant_account.user.external_id} "\ "but has no Charge Processor Merchant ID." end setup_intent = Stripe::SetupIntent.create(params) else setup_intent = Stripe::SetupIntent.create(params) end setup_intent.confirm if setup_intent.status == StripeIntentStatus::REQUIRES_CONFIRMATION StripeSetupIntent.new(setup_intent) end end def create_payment_intent_or_charge!(merchant_account, chargeable, amount_cents, amount_for_gumroad_cents, reference, description, metadata: nil, statement_description: nil, transfer_group: nil, off_session: true, setup_future_charges: false, mandate_options: nil) should_setup_future_usage = setup_future_charges && !off_session # attempting to set up future usage during an off-session charge will result in an invalid request params = { amount: amount_cents, currency: "usd", description:, metadata: metadata || { purchase: reference }, transfer_group:, payment_method_types: ["card"], off_session:, setup_future_usage: ("off_session" if should_setup_future_usage) } params.merge!(confirm: true) if off_session params.merge!(mandate_options) if mandate_options.present? params.merge!(chargeable.stripe_charge_params) # Off-session recurring charges on Indian cards use e-mandates: # https://stripe.com/docs/india-recurring-payments?integration=paymentIntents-setupIntents if off_session && chargeable.requires_mandate? mandate = get_mandate_id_from_chargeable(chargeable, merchant_account) params.merge!(mandate:) if mandate.present? end # Request 3DS manually when preparing future charges for all Indian cards. Ref: https://github.com/gumroad/web/issues/20783 params.deep_merge!(REQUEST_MANUAL_3DS_PARAMS) if should_setup_future_usage && chargeable.country == Compliance::Countries::IND.alpha2 if statement_description statement_description = statement_description.gsub(%r{[^A-Z0-9./\s]}i, "").to_s.strip[0...22] params[:statement_descriptor_suffix] = statement_description if statement_description.present? end with_stripe_error_handler do if merchant_migrated? merchant_account if merchant_account.charge_processor_merchant_id.blank? raise "Merchant Account #{merchant_account.external_id} assigned to user #{merchant_account.user.external_id} "\ "but has no Charge Processor Merchant ID." end params[:application_fee_amount] = amount_for_gumroad_cents payment_intent = Stripe::PaymentIntent.create(params, { stripe_account: merchant_account.charge_processor_merchant_id }) elsif merchant_account.user if merchant_account.charge_processor_merchant_id.blank? raise "Merchant Account #{merchant_account.external_id} assigned to user #{merchant_account.user.external_id} "\ "but has no Charge Processor Merchant ID." end params[:transfer_data] = { destination: merchant_account.charge_processor_merchant_id, amount: amount_cents - amount_for_gumroad_cents } payment_intent = Stripe::PaymentIntent.create(params) else payment_intent = Stripe::PaymentIntent.create(params) end payment_intent.confirm if payment_intent.status == StripeIntentStatus::REQUIRES_CONFIRMATION StripeChargeIntent.new(payment_intent:, merchant_account:) end end def confirm_payment_intent!(merchant_account, charge_intent_id) with_stripe_error_handler do if merchant_migrated? merchant_account if merchant_account.charge_processor_merchant_id.blank? raise "Merchant Account #{merchant_account.external_id} assigned to user #{merchant_account.user.external_id} "\ "but has no Charge Processor Merchant ID." end payment_intent = Stripe::PaymentIntent.retrieve(charge_intent_id, { stripe_account: merchant_account.charge_processor_merchant_id }) else payment_intent = Stripe::PaymentIntent.retrieve(charge_intent_id) end payment_intent.confirm unless payment_intent.status == StripeIntentStatus::SUCCESS StripeChargeIntent.new(payment_intent:, merchant_account:) end end # If payment intent is in cancelable state, cancels the payment intent. Otherwise, raises a ChargeProcessorError. def cancel_payment_intent!(merchant_account, charge_intent_id) with_stripe_error_handler do if merchant_migrated? merchant_account if merchant_account.charge_processor_merchant_id.blank? raise "Merchant Account #{merchant_account.external_id} assigned to user #{merchant_account.user.external_id} "\ "but has no Charge Processor Merchant ID." end payment_intent = Stripe::PaymentIntent.retrieve(charge_intent_id, { stripe_account: merchant_account.charge_processor_merchant_id }) else payment_intent = Stripe::PaymentIntent.retrieve(charge_intent_id) end payment_intent.cancel end end # If setup intent is in cancelable state, cancels the setup intent. Otherwise, raises a ChargeProcessorError. def cancel_setup_intent!(merchant_account, setup_intent_id) with_stripe_error_handler do if merchant_migrated? merchant_account if merchant_account.charge_processor_merchant_id.blank? raise "Merchant Account #{merchant_account.external_id} assigned to user #{merchant_account.user.external_id} "\ "but has no Charge Processor Merchant ID." end payment_intent = Stripe::SetupIntent.retrieve(setup_intent_id, { stripe_account: merchant_account.charge_processor_merchant_id }) else payment_intent = Stripe::SetupIntent.retrieve(setup_intent_id) end payment_intent.cancel end end def get_refund(refund_id, merchant_account: nil) with_stripe_error_handler do if merchant_migrated? merchant_account begin refund = Stripe::Refund.retrieve({ id: refund_id, expand: %w[balance_transaction] }, { stripe_account: merchant_account.charge_processor_merchant_id }) charge = Stripe::Charge.retrieve({ id: refund.charge, expand: %w[balance_transaction application_fee.refunds.data.balance_transaction] }, { stripe_account: merchant_account.charge_processor_merchant_id }) rescue StandardError => e Rails.logger.error("Falling back to retrieving refund from Gumroad due to #{e.inspect}") refund = Stripe::Refund.retrieve(id: refund_id, expand: %w[balance_transaction]) charge = Stripe::Charge.retrieve(id: refund.charge, expand: %w[balance_transaction application_fee.refunds.data.balance_transaction]) end else refund = Stripe::Refund.retrieve(id: refund_id, expand: %w[balance_transaction]) charge = Stripe::Charge.retrieve(id: refund.charge, expand: %w[balance_transaction application_fee.refunds.data.balance_transaction]) end destination = charge.destination if destination application_fee_refund = charge.application_fee.refunds.first if charge.application_fee destination_transfer = Stripe::Transfer.retrieve(id: charge.transfer) stripe_destination_payment = Stripe::Charge.retrieve({ id: destination_transfer.destination_payment, expand: %w[refunds.data.balance_transaction application_fee.refunds] }, { stripe_account: destination_transfer.destination }) destination_payment_refund = stripe_destination_payment.refunds.first if destination_payment_refund balance_transaction_id = destination_payment_refund.balance_transaction if balance_transaction_id.is_a?(String) destination_payment_refund_balance_transaction = Stripe::BalanceTransaction.retrieve(id: balance_transaction_id) else destination_payment_refund_balance_transaction = balance_transaction_id end end destination_payment_application_fee_refund = stripe_destination_payment.application_fee.refunds.first if stripe_destination_payment.application_fee end StripeChargeRefund.new(charge, refund, destination_payment_refund, refund.balance_transaction, application_fee_refund.try(:balance_transaction), destination_payment_refund_balance_transaction, destination_payment_application_fee_refund) end end def refund!(charge_id, amount_cents: nil, merchant_account: nil, reverse_transfer: true, is_for_fraud: nil, **_args) if merchant_migrated? merchant_account begin stripe_charge = Stripe::Charge.retrieve({ id: charge_id }, { stripe_account: merchant_account.charge_processor_merchant_id }) rescue StandardError => e Rails.logger.error "Falling back to retrieve from Gumroad account due to #{e.inspect}" stripe_charge = Stripe::Charge.retrieve(charge_id) end else stripe_charge = Stripe::Charge.retrieve(charge_id) end params = { charge: charge_id } params[:amount] = amount_cents if amount_cents.present? params[:reason] = REFUND_REASON_FRAUDULENT if is_for_fraud.present? # For Stripe-Connect: # Charges (which have a destination): # 1. Reverse the transfer that put the money into the creators account # 2. Refund Gumroad's fee to the creator # We don't reverse the transfer when refunding VAT to the customer, # as VAT amount is held by gumroad and not credited to the creator at the time of original charge. if stripe_charge.destination && reverse_transfer params[:reverse_transfer] = true params[:refund_application_fee] = true end if merchant_migrated? merchant_account begin params[:refund_application_fee] = false stripe_refund = Stripe::Refund.create(params, stripe_account: merchant_account.charge_processor_merchant_id) rescue StandardError => e Rails.logger.error "Falling back to retrieve from Gumroad account due to #{e.inspect}" stripe_refund = Stripe::Refund.create(params) end else stripe_refund = Stripe::Refund.create(params) end get_refund(stripe_refund.id, merchant_account:) rescue Stripe::InvalidRequestError => e raise ChargeProcessorAlreadyRefundedError.new("Stripe charge was already refunded. Stripe response: #{e.message}", original_error: e) unless e.message[/already been refunded/].nil? raise ChargeProcessorInvalidRequestError.new(original_error: e) rescue Stripe::APIConnectionError, Stripe::APIError => e raise ChargeProcessorUnavailableError.new("Stripe error while refunding a charge: #{e.message}", original_error: e) end def self.debit_stripe_account_for_refund_fee(credit:) return unless credit.present? return if credit.amount_cents == 0 return unless credit.merchant_account&.charge_processor_merchant_id.present? return unless credit.merchant_account.holder_of_funds == HolderOfFunds::STRIPE return if credit.merchant_account.country == Compliance::Countries::USA.alpha2 return if credit.fee_retention_refund&.debited_stripe_transfer.present? stripe_account_id = credit.merchant_account.charge_processor_merchant_id amount_cents = credit.amount_cents.abs # First, try and reverse an internal transfer made from gumroad platform account # to the connect account, if possible. transfers = credit.user.payments.completed .where(stripe_connect_account_id: stripe_account_id) .order(:created_at) .pluck(:stripe_internal_transfer_id) transfer_id = transfers.compact_blank.find do |tr_id| tr = Stripe::Transfer.retrieve(tr_id) rescue nil tr.present? && (tr.amount - tr.amount_reversed > amount_cents) end if transfer_id.present? transfer_reversal = Stripe::Transfer.create_reversal(transfer_id, { amount: amount_cents }) refund = credit.fee_retention_refund refund.update!(debited_stripe_transfer: transfer_reversal.id) if refund.present? destination_refund = Stripe::Refund.retrieve(transfer_reversal.destination_payment_refund, stripe_account: stripe_account_id) destination_balance_transaction = Stripe::BalanceTransaction.retrieve(destination_refund.balance_transaction, stripe_account: stripe_account_id) return destination_balance_transaction.net.abs end # If no eligible internal transfer was available, reverse a transfer associated with an old purchase. # Try and find a transfer older than 120 days. As disputes and refunds are not allowed after 120 days, it's safe to # reverse these transfers. transfers = Stripe::Transfer.list(destination: stripe_account_id, created: { 'lt': 120.days.ago.to_i }, limit: 100) transfer = transfers.find do |tr| tr.present? && (tr.amount - tr.amount_reversed > amount_cents) end if transfer.present? transfer_reversal = Stripe::Transfer.create_reversal(transfer.id, { amount: amount_cents }) refund = credit.fee_retention_refund refund.update!(debited_stripe_transfer: transfer_reversal.id) if refund.present? destination_refund = Stripe::Refund.retrieve(transfer_reversal.destination_payment_refund, stripe_account: stripe_account_id) destination_balance_transaction = Stripe::BalanceTransaction.retrieve(destination_refund.balance_transaction, stripe_account: stripe_account_id) destination_balance_transaction.net.abs end end def self.debit_stripe_account_for_australia_backtaxes(credit:) return unless credit.present? return if credit.amount_cents == 0 return unless credit.backtax_agreement&.jurisdiction == BacktaxAgreement::Jurisdictions::AUSTRALIA backtax_agreement = credit.backtax_agreement return if backtax_agreement.collected? owed_amount_cents_usd = credit.amount_cents.abs # Adjust the amount owed if only a partial amount of reversals completed (due to some Stripe failure) owed_amount_cents_usd -= backtax_agreement.backtax_collections.sum(:amount_cents_usd) if backtax_agreement.backtax_collections.size > 0 unless owed_amount_cents_usd > 0 backtax_agreement.update!(collected: true) return end if credit.merchant_account.holder_of_funds == HolderOfFunds::GUMROAD # No Stripe transfer needed. Record the backtax collection and return. ActiveRecord::Base.transaction do BacktaxCollection.create!( user: credit.user, backtax_agreement:, amount_cents: owed_amount_cents_usd, amount_cents_usd: owed_amount_cents_usd, currency: "usd", stripe_transfer_id: nil ) backtax_agreement.update!(collected: true) end return end return unless credit.merchant_account.holder_of_funds == HolderOfFunds::STRIPE return unless credit.merchant_account&.charge_processor_merchant_id.present? stripe_currency = credit.merchant_account.currency stripe_account_id = credit.merchant_account.charge_processor_merchant_id stripe_balance = Stripe::Balance.retrieve({ stripe_account: stripe_account_id }) stripe_available_object = stripe_balance.available.find { |stripe_object| stripe_object.currency == stripe_currency } stripe_pending_object = stripe_balance.pending.find { |stripe_object| stripe_object.currency == stripe_currency } stripe_balance_amount = stripe_available_object.amount + stripe_pending_object.amount if credit.merchant_account.country == Compliance::Countries::USA.alpha2 # Avoid debiting the customer's bank account if they haven't accumulated enough balance in their Gumroad-controlled Stripe account. return unless stripe_balance_amount > owed_amount_cents_usd # For US Gumroad-controlled Stripe accounts, we can make new debit transfers. # So we transfer the taxes owed amount from the creator's Gumroad-controlled Stripe account to Gumroad's Stripe account. transfer = Stripe::Transfer.create({ amount: owed_amount_cents_usd, currency: "usd", destination: STRIPE_PLATFORM_ACCOUNT_ID, }, { stripe_account: stripe_account_id }) ActiveRecord::Base.transaction do BacktaxCollection.create!( user: credit.user, backtax_agreement:, amount_cents: owed_amount_cents_usd, amount_cents_usd: owed_amount_cents_usd, currency: "usd", stripe_transfer_id: transfer.id ) backtax_agreement.update!(collected: true) end else # For non-US Gumroad-controlled Stripe accounts, we cannot make new debit transfers. # So we look to reverse historical transfers made from Gumroad's Stripe account to the creator's Gumroad-controlled Stripe account. # We look to reverse enough transfers to cover the total amount owed. # # The historical transfers could have been executed in usd, or the Stripe account's currency, depending on when they were executed. # The below algorithm will accumulate transfers of the same currency type — enough to cover the amount owed — and reverse them at the end. # All transfers to be reversed will have the same currency type, to avoid inaccuracies due to currency conversion. # Determine the owed amount in the Stripe account's currency. # Then, avoid debiting the customer's bank account if they haven't accumulated enough balance in their Gumroad-controlled Stripe account. owed_amount_in_currency = usd_cents_to_currency(stripe_currency, owed_amount_cents_usd) return unless stripe_balance_amount > owed_amount_in_currency # Determine the stripe balance amount in usd. # Reduce that amount by 5%, as a buffer for possible currency conversion inaccuracies. # Then, avoid debiting the customer's bank account if they haven't accumulated enough balance in their Gumroad-controlled Stripe account. stripe_balance_amount_cents_usd = get_usd_cents("usd", stripe_balance_amount) stripe_balance_amount_cents_usd_reduced_by_five_percent = (stripe_balance_amount_cents_usd - (5.0 / 100) * stripe_balance_amount_cents_usd).round return unless stripe_balance_amount_cents_usd_reduced_by_five_percent > owed_amount_cents_usd # Each of the `transfers` values below will be an Array of two-element Arrays, like: [["tr_123", 100], ["tr_456", 200], ...] # These two-element Arrays represent the transfer ID, and the amount to reverse. data = { usd: { owed: owed_amount_cents_usd, transfers: [], sum_of_transfer_amounts: 0, }, stripe_currency.to_sym => { owed: owed_amount_in_currency, transfers: [], sum_of_transfer_amounts: 0, } } # First, look for internal transfers made from Gumroad's Stripe account # to the creator's Gumroad-controlled Stripe account. transfer_ids = credit.user.payments.completed .where(stripe_connect_account_id: stripe_account_id) .order(:created_at) .pluck(:stripe_internal_transfer_id) transfer_ids.compact_blank.each do |transfer_id| break if data.values.any? { |value| value[:sum_of_transfer_amounts] >= value[:owed] } transfer = Stripe::Transfer.retrieve(transfer_id) rescue nil calculate_transfer_reversal(transfer, data) end starting_after = nil until data.values.any? { |value| value[:sum_of_transfer_amounts] >= value[:owed] } # Next, look for transfers associated with an old purchase. # Look for transfers older than 120 days. # Disputes and refunds are not allowed after 120 days, so it's safe to reverse such transfers. transfers = Stripe::Transfer.list(destination: stripe_account_id, created: { 'lt': 120.days.ago.to_i }, limit: 100, starting_after:) break unless transfers.count > 0 transfers.each do |transfer| break if data.values.any? { |value| value[:sum_of_transfer_amounts] >= value[:owed] } starting_after = transfer.id calculate_transfer_reversal(transfer, data) end end reversal_currency, reversal_data = data.find { |_, value| value[:sum_of_transfer_amounts] >= value[:owed] } # Only perform transfers if we can transfer the total amount owed, in full. # Avoid making a batch of transfers that would only cover the partial amount owed. return unless reversal_currency.present? && reversal_data.present? reversal_currency = reversal_currency.to_s reversal_data[:transfers].each do |transfer_id, amount_to_reverse| transfer_reversal = Stripe::Transfer.create_reversal(transfer_id, { amount: amount_to_reverse }) BacktaxCollection.create!( user: credit.user, backtax_agreement:, amount_cents: amount_to_reverse, amount_cents_usd: get_usd_cents(reversal_currency, amount_to_reverse), currency: reversal_currency, stripe_transfer_id: transfer_reversal.id ) end backtax_agreement.update!(collected: true) end end def fight_chargeback(stripe_charge_id, dispute_evidence, merchant_account: nil) return if merchant_migrated? merchant_account with_stripe_error_handler do charge = Stripe::Charge.retrieve(stripe_charge_id) Stripe::Dispute.update( charge.dispute, evidence: { billing_address: dispute_evidence.billing_address, customer_email_address: dispute_evidence.customer_email, customer_name: dispute_evidence.customer_name, customer_purchase_ip: dispute_evidence.customer_purchase_ip, product_description: dispute_evidence.product_description, receipt: create_dispute_evidence_stripe_file(dispute_evidence.receipt_image), service_date: dispute_evidence.purchased_at.to_fs(:formatted_date_full_month), shipping_address: dispute_evidence.shipping_address, shipping_carrier: dispute_evidence.shipping_carrier, shipping_date: dispute_evidence.shipped_at&.to_fs(:formatted_date_full_month), shipping_tracking_number: dispute_evidence.shipping_tracking_number, uncategorized_text: [ "The merchant should win the dispute because:\n#{dispute_evidence.reason_for_winning}", dispute_evidence.uncategorized_text ].compact.join("\n\n"), access_activity_log: dispute_evidence.access_activity_log, cancellation_policy: create_dispute_evidence_stripe_file(dispute_evidence.cancellation_policy_image), cancellation_policy_disclosure: dispute_evidence.cancellation_policy_disclosure,
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/stripe/stripe_chargeable_token.rb
app/business/payments/charging/implementations/stripe/stripe_chargeable_token.rb
# frozen_string_literal: true # Public: Chargeable representing pre-tokenized data using Stripe. class StripeChargeableToken include StripeErrorHandler attr_reader :payment_method_id def initialize(token, zip_code, product_permalink:) @token_s = token @zip_code = zip_code @merchant_account = get_merchant_account(product_permalink) end def charge_processor_id StripeChargeProcessor.charge_processor_id end def prepare! with_stripe_error_handler do @token = Stripe::Token.retrieve(@token_s) if card.nil? end true end def funding_type return card[:funding] if card.present? && card[:funding].present? nil end def fingerprint return card[:fingerprint] if card.present? && card[:fingerprint].present? nil end def last4 return card[:last4] if card.present? && card[:last4].present? nil end def number_length return ChargeableVisual.get_card_length_from_card_type(card_type) if card_type nil end def visual return ChargeableVisual.build_visual(last4, number_length) if last4.present? && number_length.present? nil end def expiry_month return card[:exp_month] if card.present? && card[:exp_month].present? nil end def expiry_year return card[:exp_year] if card.present? && card[:exp_year].present? nil end def zip_code return card[:address_zip] if card.present? && card[:address_zip].present? @zip_code end def card_type return StripeCardType.to_card_type(card[:brand]) if card.present? && card[:brand].present? nil end def country return card[:country] if card.present? && card[:country].present? nil end def card return @customer.sources.first if @customer return @token.card if @token.present? nil end def reusable_token!(user) if @customer.nil? with_stripe_error_handler do creation_params = { description: user&.id.to_s, email: user&.email, card: @token_s, expand: %w[sources] } @customer = if @merchant_account&.is_a_stripe_connect_account? Stripe::Customer.create(creation_params, stripe_account: @merchant_account.charge_processor_merchant_id) else Stripe::Customer.create(creation_params) end end end @customer[:id] end def stripe_charge_params Rails.logger.error "StripeChargeableToken#stripe_charge_params called" reusable_token!(nil) return { customer: @customer[:id], payment_method: nil } if @customer { card: @token_s } end def requires_mandate? country == "IN" end private def get_merchant_account(permalink) return unless permalink link = Link.find_by unique_permalink: permalink link&.user && link.user.merchant_account(StripeChargeProcessor.charge_processor_id) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/stripe/stripe_card_type.rb
app/business/payments/charging/implementations/stripe/stripe_card_type.rb
# frozen_string_literal: true class StripeCardType CARD_TYPES = { "Visa" => CardType::VISA, "American Express" => CardType::AMERICAN_EXPRESS, "MasterCard" => CardType::MASTERCARD, "Discover" => CardType::DISCOVER, "JCB" => CardType::JCB, "Diners Club" => CardType::DINERS_CLUB, "UnionPay" => CardType::UNION_PAY }.freeze NEW_CARD_TYPES = { "visa" => CardType::VISA, "amex" => CardType::AMERICAN_EXPRESS, "mastercard" => CardType::MASTERCARD, "discover" => CardType::DISCOVER, "jcb" => CardType::JCB, "diners" => CardType::DINERS_CLUB, "unionpay" => CardType::UNION_PAY }.freeze def self.to_card_type(stripe_card_type) type = CARD_TYPES[stripe_card_type] type = CardType::UNKNOWN if type.nil? type end def self.to_new_card_type(stripe_card_type) type = NEW_CARD_TYPES[stripe_card_type] type = CardType::UNKNOWN if type.nil? type end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/stripe/stripe_charge_refund.rb
app/business/payments/charging/implementations/stripe/stripe_charge_refund.rb
# frozen_string_literal: true class StripeChargeRefund < ChargeRefund # Public: Create a ChargeRefund from a Stripe::Refund # # Inherits attr_accessor :charge_processor_id, :id, :charge_id, :flow_of_funds, :refund from ChargeRefund attr_reader :charge, :destination_payment_refund, :refund_balance_transaction, :application_fee_refund_balance_transaction, :destination_payment_refund_balance_transaction, :destination_payment_application_fee_refund def initialize(charge, refund, destination_payment_refund, refund_balance_transaction, application_fee_refund_balance_transaction, destination_payment_refund_balance_transaction, destination_payment_application_fee_refund) @charge = charge @refund = refund @destination_payment_refund = destination_payment_refund @refund_balance_transaction = refund_balance_transaction @application_fee_refund_balance_transaction = application_fee_refund_balance_transaction @destination_payment_refund_balance_transaction = destination_payment_refund_balance_transaction @destination_payment_application_fee_refund = destination_payment_application_fee_refund self.charge_processor_id = StripeChargeProcessor.charge_processor_id self.id = refund[:id] self.charge_id = refund[:charge] self.flow_of_funds = build_flow_of_funds end private def build_flow_of_funds gumroad_amount = nil merchant_account_gross_amount = nil merchant_account_net_amount = nil # Even if the charge involved a destination, the refund may not involve a destination. Refunds only involve the destination if # the transfer to the destination is also reversed/refunded. if fof_has_destination? && should_refund_application_fees? check_merchant_currency_mismatch gumroad_amount = calculate_application_fees_refund merchant_account_gross_amount = calculate_merchant_gross_amount merchant_account_net_amount = calculate_merchant_net_amount elsif fof_has_destination? gumroad_amount = calculate_gumroad_amount unless charge.on_behalf_of.present? merchant_account_gross_amount = calculate_merchant_gross_amount merchant_account_net_amount = calculate_merchant_net_amount elsif charge.application_fee&.account.present? gumroad_amount = FlowOfFunds::Amount.new( currency: refund.currency, cents: -1 * refund.amount ) else gumroad_amount = calculate_settled_amount end FlowOfFunds.new( issued_amount: calculate_issued_amount, settled_amount: calculate_settled_amount, gumroad_amount:, merchant_account_gross_amount:, merchant_account_net_amount: ) end private def calculate_settled_amount FlowOfFunds::Amount.new( currency: refund_balance_transaction[:currency], cents: refund_balance_transaction[:amount] ) end def calculate_issued_amount FlowOfFunds::Amount.new( currency: refund[:currency], cents: -1 * refund[:amount] ) end def calculate_application_fees_refund FlowOfFunds::Amount.new( currency: application_fee_refund_balance_transaction[:currency], cents: application_fee_refund_balance_transaction[:amount] ) end def calculate_gumroad_amount FlowOfFunds::Amount.new( currency: refund[:currency], cents: refund[:amount] - destination_payment_refund[:amount] ) end def calculate_merchant_gross_amount FlowOfFunds::Amount.new( currency: destination_payment_refund_balance_transaction[:currency], cents: destination_payment_refund_balance_transaction[:amount] ) end def calculate_merchant_net_amount cents = destination_payment_refund_balance_transaction[:amount] cents += destination_payment_application_fee_refund[:amount] if should_refund_application_fees? FlowOfFunds::Amount.new( currency: destination_payment_refund_balance_transaction[:currency], cents: ) end def fof_has_destination? charge[:destination] && destination_payment_refund_balance_transaction end def check_merchant_currency_mismatch return unless destination_payment_refund_balance_transaction.currency != destination_payment_application_fee_refund.currency raise "Destination Payment Application Fee Refund #{destination_payment_application_fee_refund[:id]} should be in the same currency "\ "as the Destination Payment Refund's Balance Transaction #{destination_payment_refund_balance_transaction[:id]}" end def should_refund_application_fees? application_fee_refund_balance_transaction && destination_payment_application_fee_refund end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/stripe/stripe_chargeable_credit_card.rb
app/business/payments/charging/implementations/stripe/stripe_chargeable_credit_card.rb
# frozen_string_literal: true # Public: Chargeable representing a card stored at Stripe. class StripeChargeableCreditCard include StripeErrorHandler attr_reader :fingerprint, :payment_method_id, :last4, :visual, :number_length, :expiry_month, :expiry_year, :zip_code, :card_type, :country, :stripe_setup_intent_id, :stripe_payment_intent_id def initialize(merchant_account, reusable_token, payment_method_id, fingerprint, stripe_setup_intent_id, stripe_payment_intent_id, last4, number_length, visual, expiry_month, expiry_year, card_type, country, zip_code = nil) @merchant_account = merchant_account @customer_id = reusable_token @payment_method_id = payment_method_id @fingerprint = fingerprint @stripe_setup_intent_id = stripe_setup_intent_id @stripe_payment_intent_id = stripe_payment_intent_id @last4 = last4 @number_length = number_length @visual = visual @expiry_month = expiry_month @expiry_year = expiry_year @card_type = card_type @country = country @zip_code = zip_code end def funding_type nil end def charge_processor_id StripeChargeProcessor.charge_processor_id end def prepare! @payment_method_id ||= Stripe::Customer.retrieve(@customer_id).default_source || Stripe::PaymentMethod.list({ customer: @customer_id, type: "card" }).data[0].id if @merchant_account&.is_a_stripe_connect_account? prepare_for_direct_charge update_card_details end true end def reusable_token!(_user) @customer_id end def stripe_charge_params if @merchant_account&.is_a_stripe_connect_account? { payment_method: @payment_method_id_on_connect_account } else { customer: @customer_id, payment_method: @payment_method_id } end end def requires_mandate? country == "IN" end # We always save the payment methods linked to our platform account. They must be # first cloned to the connected account before attempting a direct charge. # https://stripe.com/docs/payments/payment-methods/connect#cloning-payment-methods def prepare_for_direct_charge return unless @merchant_account&.is_a_stripe_connect_account? with_stripe_error_handler do # Old credit card records do not have a payment method ID on record, only the customer ID. # In such cases, we fetch the payment method associated with the customer first and then clone it. @payment_method_id = Stripe::PaymentMethod.list({ customer: @customer_id, type: "card" }).data[0].id if @payment_method_id.blank? @payment_method_on_connect_account = Stripe::PaymentMethod.create({ customer: @customer_id, payment_method: @payment_method_id }, { stripe_account: @merchant_account.charge_processor_merchant_id }) @payment_method_id_on_connect_account = @payment_method_on_connect_account.id end end def update_card_details card = @payment_method_on_connect_account&.card return unless card.present? @fingerprint = card[:fingerprint].presence @last4 = card[:last4].presence @card_type = StripeCardType.to_new_card_type(card[:brand]) if card[:brand].present? @number_length = ChargeableVisual.get_card_length_from_card_type(card_type) @visual = ChargeableVisual.build_visual(last4, number_length) if last4.present? && number_length.present? @expiry_month = card[:exp_month].presence @expiry_year = card[:exp_year].presence @country = card[:country].presence @zip_code = @payment_method_on_connect_account.billing_details[:address][:postal_code].presence || zip_code end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/stripe/stripe_charge_radar_processor.rb
app/business/payments/charging/implementations/stripe/stripe_charge_radar_processor.rb
# frozen_string_literal: true # Sample Stripe event: # { # "id": "evt_0O8n7L9e1RjUNIyY90W7gkV3", # "object": "event", # "api_version": "2020-08-27", # "created": 1699116878, # "data": { # "object": { # "id": "issfr_0O8n7K9e1RjUNIyYmTbvMMLa", # "object": "radar.early_fraud_warning", # "actionable": true, # "charge": "ch_2O8n7J9e1RjUNIyY1rs9MIRL", # "created": 1699116878, # "fraud_type": "made_with_stolen_card", # "livemode": false, # "payment_intent": "pi_2O8n7J9e1RjUNIyY1X7FyY6q" # } # }, # "livemode": false, # "pending_webhooks": 8, # "request": { # "id": "req_2WfpkRMdlbjEkY", # "idempotency_key": "82f4bcef-7a1e-4a28-ac2d-2ae4ceb7fcbe" # }, # "type": "radar.early_fraud_warning.created" # } module StripeChargeRadarProcessor extend self SUPPORTED_STRIPE_EVENTS = %w[radar.early_fraud_warning.created radar.early_fraud_warning.updated] def handle_event(stripe_params) raise "Unsupported event type: #{stripe_params["type"]}" unless SUPPORTED_STRIPE_EVENTS.include?(stripe_params["type"]) stripe_event_object = Stripe::Util.convert_to_stripe_object(stripe_params) early_fraud_warning = find_or_initialize_early_fraud_warning!(stripe_event_object.data.object) early_fraud_warning.update_from_stripe! ProcessEarlyFraudWarningJob.perform_async(early_fraud_warning.id) rescue ActiveRecord::RecordNotFound => e # Ignore for non-production environments, as the purchase could have been done on one of the many # environments (one of engineer's local, staging, branch app, etc) return unless Rails.env.production? # An event that has the `account` attribute is associated with a Stripe Connect account # If the purchase cannot be found, it's most likely because it wasn't done on the platform return if stripe_event_object.try(:account).present? raise e end private def find_or_initialize_early_fraud_warning!(stripe_efw_object) chargeable = Charge::Chargeable.find_by_processor_transaction_id!(stripe_efw_object.charge) EarlyFraudWarning.find_or_initialize_by( purchase: (chargeable if chargeable.is_a?(Purchase)), charge: (chargeable if chargeable.is_a?(Charge)), processor_id: stripe_efw_object.id, ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/stripe/stripe_charge_intent.rb
app/business/payments/charging/implementations/stripe/stripe_charge_intent.rb
# frozen_string_literal: true # Creates a ChargeIntent from Stripe::PaymentIntent class StripeChargeIntent < ChargeIntent delegate :id, :client_secret, to: :payment_intent def initialize(payment_intent:, merchant_account: nil) self.payment_intent = payment_intent load_charge(payment_intent, merchant_account) if succeeded? validate_next_action end def succeeded? payment_intent.status == StripeIntentStatus::SUCCESS end def requires_action? payment_intent.status == StripeIntentStatus::REQUIRES_ACTION && payment_intent.next_action.type == StripeIntentStatus::ACTION_TYPE_USE_SDK end def canceled? payment_intent.status == StripeIntentStatus::CANCELED end def processing? payment_intent.status == StripeIntentStatus::PROCESSING end private def load_charge(payment_intent, merchant_account) # TODO:: Remove the `|| payment_intent.charges.first&.id` part below # once all webhooks and the default API version have been upgraded to 2023-10-16 on Stripe dashboard. # Need to keep it for the transition phase to support webhooks in the old API version along with new. # The `charges` property on PaymentIntent has been replaced with `latest_charge`, in API version 2022-11-15. # Ref: https://stripe.com/docs/upgrades#2022-11-15 charge_id = payment_intent.latest_charge || payment_intent.charges.first&.id # For PaymentIntents with capture_method = automatic we always expect a single charge raise "Expected a charge for payment intent #{payment_intent.id}, but got nil" unless charge_id.present? self.charge = StripeChargeProcessor.new.get_charge(charge_id, merchant_account:) end def validate_next_action if payment_intent.status == StripeIntentStatus::REQUIRES_ACTION && payment_intent.next_action.type != StripeIntentStatus::ACTION_TYPE_USE_SDK Bugsnag.notify "Stripe charge intent #{id} requires an unsupported action: #{payment_intent.next_action.type}" end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/stripe/stripe_setup_intent.rb
app/business/payments/charging/implementations/stripe/stripe_setup_intent.rb
# frozen_string_literal: true # Creates a SetupIntent from Stripe::SetupIntent class StripeSetupIntent < SetupIntent delegate :id, :client_secret, to: :setup_intent def initialize(setup_intent) self.setup_intent = setup_intent validate_next_action end def succeeded? setup_intent.status == StripeIntentStatus::SUCCESS end def requires_action? setup_intent.status == StripeIntentStatus::REQUIRES_ACTION && setup_intent.next_action.type == StripeIntentStatus::ACTION_TYPE_USE_SDK end def canceled? setup_intent.status == StripeIntentStatus::CANCELED end private def validate_next_action if setup_intent.status == StripeIntentStatus::REQUIRES_ACTION && setup_intent.next_action.type != StripeIntentStatus::ACTION_TYPE_USE_SDK Bugsnag.notify "Stripe setup intent #{id} requires an unsupported action: #{setup_intent.next_action.type}" end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/stripe/stripe_chargeable_payment_method.rb
app/business/payments/charging/implementations/stripe/stripe_chargeable_payment_method.rb
# frozen_string_literal: true class StripeChargeablePaymentMethod include StripeErrorHandler attr_reader :payment_method_id, :stripe_setup_intent_id, :stripe_payment_intent_id def initialize(payment_method_id, customer_id: nil, stripe_setup_intent_id: nil, stripe_payment_intent_id: nil, zip_code:, product_permalink:) @payment_method_id = payment_method_id @customer_id = customer_id @stripe_setup_intent_id = stripe_setup_intent_id @stripe_payment_intent_id = stripe_payment_intent_id @zip_code = zip_code @merchant_account = get_merchant_account(product_permalink) end def charge_processor_id StripeChargeProcessor.charge_processor_id end def prepare! if @payment_method.present? @customer_id ||= @payment_method.customer return true end with_stripe_error_handler do @payment_method = Stripe::PaymentMethod.retrieve(@payment_method_id) end @customer_id ||= @payment_method.customer prepare_for_direct_charge if @merchant_account&.is_a_stripe_connect_account? true end def funding_type card[:funding].presence if card.present? end def fingerprint card[:fingerprint].presence if card.present? end def last4 card[:last4].presence if card.present? end def number_length ChargeableVisual.get_card_length_from_card_type(card_type) if card_type end def visual ChargeableVisual.build_visual(last4, number_length) if last4.present? && number_length.present? end def expiry_month card[:exp_month].presence if card.present? end def expiry_year card[:exp_year].presence if card.present? end def zip_code return @payment_method.billing_details[:address][:postal_code].presence if @payment_method.present? @zip_code end def card_type StripeCardType.to_new_card_type(card[:brand]) if card.present? && card[:brand].present? end def country card[:country].presence if card.present? end def card @merchant_account&.is_a_stripe_connect_account? ? @payment_method_on_connect_account&.card : @payment_method&.card end def reusable_token!(user) if @customer_id.blank? with_stripe_error_handler do creation_params = { description: user&.id.to_s, email: user&.email, payment_method: @payment_method_id } customer = Stripe::Customer.create(creation_params) @customer_id = customer.id end end @customer_id end def stripe_charge_params if @merchant_account&.is_a_stripe_connect_account? { payment_method: @payment_method_id_on_connect_account } else { customer: @customer_id, payment_method: @payment_method_id } end end def requires_mandate? country == "IN" end private def get_merchant_account(permalink) return unless permalink link = Link.find_by unique_permalink: permalink link&.user && link.user.merchant_account(StripeChargeProcessor.charge_processor_id) end # On the front end we always create payment methods linked to our platform account. They must be # first cloned to the connected account before attempting a direct charge. # https://stripe.com/docs/payments/payment-methods/connect#cloning-payment-methods def prepare_for_direct_charge return unless @merchant_account&.is_a_stripe_connect_account? with_stripe_error_handler do @payment_method_on_connect_account = Stripe::PaymentMethod.create({ customer: reusable_token!(nil), payment_method: @payment_method_id }, { stripe_account: @merchant_account.charge_processor_merchant_id }) @payment_method_id_on_connect_account = @payment_method_on_connect_account.id end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/stripe/stripe_charge.rb
app/business/payments/charging/implementations/stripe/stripe_charge.rb
# frozen_string_literal: true class StripeCharge < BaseProcessorCharge # Public: Create a BaseProcessorCharge from a Stripe::Charge and a Stripe::BalanceTransaction def initialize(stripe_charge, stripe_charge_balance_transaction, stripe_application_fee_balance_transaction, stripe_destination_payment_balance_transaction, stripe_destination_transfer) self.charge_processor_id = StripeChargeProcessor.charge_processor_id return if stripe_charge.nil? self.id = stripe_charge[:id] self.status = stripe_charge[:status].to_s.downcase self.refunded = stripe_charge[:refunded] self.disputed = stripe_charge[:dispute].present? stripe_fee_detail = stripe_charge_balance_transaction[:fee_details].find { |fee_detail| fee_detail[:type] == "stripe_fee" } if stripe_fee_detail.present? self.fee_currency = stripe_fee_detail[:currency] self.fee = stripe_fee_detail[:amount] end self.flow_of_funds = build_flow_of_funds(stripe_charge, stripe_charge_balance_transaction, stripe_application_fee_balance_transaction, stripe_destination_payment_balance_transaction, stripe_destination_transfer) return if stripe_charge["payment_method_details"].nil? fetch_risk_level(stripe_charge) fetch_card_details_from(stripe_charge) end private def fetch_risk_level(stripe_charge) self.risk_level = stripe_charge[:outcome][:risk_level] end def fetch_card_details_from(stripe_charge) payment_method_details = stripe_charge[:payment_method_details] billing_details = stripe_charge[:billing_details] payment_card = payment_method_details[:card] self.card_fingerprint = payment_card[:fingerprint] self.card_instance_id = stripe_charge[:payment_method] self.card_last4 = payment_card[:last4] if payment_card[:brand].present? card_type = StripeCardType.to_new_card_type(payment_card[:brand]) self.card_type = card_type self.card_number_length = ChargeableVisual.get_card_length_from_card_type(card_type) end self.card_expiry_month = payment_card[:exp_month] self.card_expiry_year = payment_card[:exp_year] self.card_zip_code = billing_details[:address][:postal_code] self.card_country = payment_card[:country] self.zip_check_result = case payment_card[:checks][:address_postal_code_check] when "pass" true when "fail" false end end def build_flow_of_funds(stripe_charge, stripe_charge_balance_transaction, stripe_application_fee_balance_transaction, stripe_destination_payment_balance_transaction, stripe_destination_transfer) return if stripe_charge[:destination] && stripe_application_fee_balance_transaction.nil? && stripe_destination_transfer.nil? issued_amount = FlowOfFunds::Amount.new(currency: stripe_charge[:currency], cents: stripe_charge[:amount]) settled_amount = FlowOfFunds::Amount.new(currency: stripe_charge_balance_transaction[:currency], cents: stripe_charge_balance_transaction[:amount]) if stripe_charge[:destination] if stripe_application_fee_balance_transaction.present? # For old charges with `application_fee_amount` parameter, we get the gumroad amount from the # application_fee object attached to the charge. gumroad_amount_currency = stripe_application_fee_balance_transaction[:currency] gumroad_amount_cents = stripe_application_fee_balance_transaction[:amount] else # For new charges with `transfer_data[amount]` parameter instead of `application_fee_amoount`, there's # no application_fee object attached to the charge so we calculate the gumroad amount as difference between # the total charge amount and the amount transferred to the connect account. gumroad_amount_currency = stripe_charge[:currency] gumroad_amount_cents = stripe_charge[:amount] - stripe_destination_transfer[:amount] end gumroad_amount = FlowOfFunds::Amount.new(currency: gumroad_amount_currency, cents: gumroad_amount_cents) # Note: The settled and merchant account gross amount will always be the same with Stripe Connect. # The transaction settles in the merchant account currency and the gross amount is the full settled amount. merchant_account_gross_amount = FlowOfFunds::Amount.new(currency: stripe_destination_payment_balance_transaction[:currency], cents: stripe_destination_payment_balance_transaction[:amount]) merchant_account_net_amount = FlowOfFunds::Amount.new(currency: stripe_destination_payment_balance_transaction[:currency], cents: stripe_destination_payment_balance_transaction[:net]) elsif stripe_application_fee_balance_transaction.present? # For direct charges in case of Stripe Connect accounts, there will be no destination on the Stripe charge, # but there will be an associated application_fee. We get the gumroad amount from the # application_fee object attached to the charge in this case. gumroad_amount_currency = stripe_application_fee_balance_transaction[:currency] gumroad_amount_cents = stripe_application_fee_balance_transaction[:amount] gumroad_amount = FlowOfFunds::Amount.new(currency: gumroad_amount_currency, cents: gumroad_amount_cents) # Note: The settled and merchant account gross amount will always be the same with Stripe Connect. # The transaction settles in the merchant account currency and the gross amount is the full settled amount. merchant_account_gross_amount = FlowOfFunds::Amount.new(currency: stripe_charge_balance_transaction[:currency], cents: stripe_charge_balance_transaction[:amount]) merchant_account_net_amount = FlowOfFunds::Amount.new(currency: stripe_charge_balance_transaction[:currency], cents: stripe_charge_balance_transaction[:net]) else gumroad_amount = settled_amount merchant_account_gross_amount = nil merchant_account_net_amount = nil end FlowOfFunds.new( issued_amount:, settled_amount:, gumroad_amount:, merchant_account_gross_amount:, merchant_account_net_amount: ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/stripe/helpers/stripe_error_handler.rb
app/business/payments/charging/implementations/stripe/helpers/stripe_error_handler.rb
# frozen_string_literal: true module StripeErrorHandler private def with_stripe_error_handler yield rescue Stripe::InvalidRequestError => e raise ChargeProcessorInvalidRequestError.new(original_error: e) rescue Stripe::APIConnectionError, Stripe::APIError => e raise ChargeProcessorUnavailableError.new(original_error: e) rescue Stripe::CardError => e error_code, charge_id = get_card_error_details(e) raise ChargeProcessorCardError.new(error_code, e.message, original_error: e, charge_id:) rescue Stripe::RateLimitError => e raise ChargeProcessorErrorRateLimit.new(original_error: e) rescue Stripe::StripeError => e raise ChargeProcessorErrorGeneric.new(e.code, original_error: e) end def get_card_error_details(error) error_details = error.json_body[:error] error_code = error.code # If available, the reason for a card decline (found in Stripe's `decline_code` # attribute) will appended to the error code returned to us by Stripe. Examples: # | Stripe's error code | Stripe's decline code | Gumroad's error_code | # | :------------------ | :-------------------- | :----------------------- | # | card_declined | generic_decline | card_declined_generic_decline | # | card_declined | fraudulent | card_declined_fraudulent | # | incorrect_cvc | | incorrect_cvc | decline_code = error_details[:decline_code] error_code += "_#{decline_code}" if error_code == "card_declined" && decline_code.present? [error_code, error_details[:charge]] end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/stripe/helpers/stripe_intent_status.rb
app/business/payments/charging/implementations/stripe/helpers/stripe_intent_status.rb
# frozen_string_literal: true class StripeIntentStatus SUCCESS = "succeeded" REQUIRES_CONFIRMATION = "requires_confirmation" REQUIRES_ACTION = "requires_action" PROCESSING = "processing" CANCELED = "canceled" ACTION_TYPE_USE_SDK = "use_stripe_sdk" end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/paypal/paypal_approved_order_chargeable.rb
app/business/payments/charging/implementations/paypal/paypal_approved_order_chargeable.rb
# frozen_string_literal: true class PaypalApprovedOrderChargeable attr_reader :fingerprint, :last4, :number_length, :visual, :expiry_month, :expiry_year, :zip_code, :card_type, :country, :funding_type, :email def initialize(order_id, visual, country) @fingerprint = order_id @visual = visual @email = visual @card_type = CardType::PAYPAL @country = country end def charge_processor_id PaypalChargeProcessor.charge_processor_id end def prepare! true end def reusable_token!(_user_id) nil end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/paypal/paypal_charge.rb
app/business/payments/charging/implementations/paypal/paypal_charge.rb
# frozen_string_literal: true class PaypalCharge < BaseProcessorCharge include CurrencyHelper attr_accessor :paypal_payment_status, :card_visual def initialize(paypal_transaction_id:, order_api_used:, payment_details: {}) self.charge_processor_id = PaypalChargeProcessor.charge_processor_id self.id = paypal_transaction_id load_transaction_details(paypal_transaction_id, order_api_used, payment_details) end private def load_transaction_details(paypal_transaction_id, order_api_used, payment_details) if order_api_used load_transaction_details_for_paypal_order_api(paypal_transaction_id, payment_details) else load_transaction_details_for_express_checkout_api(payment_details) end end def load_transaction_details_for_express_checkout_api(payment_details) self.fee = fee_cents(payment_details[:paypal_payment_info].FeeAmount.value, payment_details[:paypal_payment_info].FeeAmount.currencyID) self.paypal_payment_status = self.status = payment_details[:paypal_payment_info].PaymentStatus self.refunded = status.downcase == PaypalApiPaymentStatus::REFUNDED.downcase self.flow_of_funds = nil return if payment_details[:paypal_payer_info].nil? self.card_fingerprint = PaypalCardFingerprint.build_paypal_fingerprint(payment_details[:paypal_payer_info].PayerID) self.card_country = payment_details[:paypal_payer_info].PayerCountry self.card_type = CardType::PAYPAL end def load_transaction_details_for_paypal_order_api(capture_id, order_details) return if capture_id.blank? capture_details = fetch_capture_details(capture_id, order_details) if capture_details.dig("seller_receivable_breakdown", "paypal_fee").present? self.fee_currency = capture_details["seller_receivable_breakdown"]["paypal_fee"]["currency_code"] self.fee = fee_cents(capture_details["seller_receivable_breakdown"]["paypal_fee"]["value"], fee_currency) end self.paypal_payment_status = capture_details["status"] self.status = capture_details["status"].to_s.downcase self.refunded = status == PaypalApiPaymentStatus::REFUNDED.downcase self.card_fingerprint = PaypalCardFingerprint.build_paypal_fingerprint(order_details["payer"]["email_address"]) self.card_visual = order_details["payer"]["email_address"] self.card_country = order_details["payer"]["address"]["country_code"] self.card_type = CardType::PAYPAL # Don't create flow of funds for paypal charge as we don't use anything from it except for gumroad amount's currency # for affiliate balance creation, but as now gumroad amount's currency can be non-usd, we can't use it as affiliate balance # needs to be in usd always, so we'll simply generate a simple flow of funds for purchases via paypal for that purpose. # Keeping the method body for now in case we need it later for some reason and for debugging. # self.flow_of_funds = build_flow_of_funds(capture_details) if capture_details.present? end def fee_cents(fee_amount, currency) fee_amount.to_f * unit_scaling_factor(currency) end def fetch_capture_details(capture_id, order_details) order_details["purchase_units"].detect do |purchase_unit| purchase_unit["payments"]["captures"][0]["id"] == capture_id end["payments"]["captures"][0] end def build_flow_of_funds(capture_details) merchant_account_gross_amount = settled_amount = issued_amount = FlowOfFunds::Amount.new( currency: capture_details["seller_receivable_breakdown"]["gross_amount"]["currency_code"].downcase, cents: capture_details["seller_receivable_breakdown"]["gross_amount"]["value"]) gumroad_amount = FlowOfFunds::Amount.new( currency: capture_details["seller_receivable_breakdown"]["platform_fees"][0]["amount"]["currency_code"].downcase, cents: capture_details["seller_receivable_breakdown"]["platform_fees"][0]["amount"]["value"]) merchant_account_net_amount = FlowOfFunds::Amount.new( currency: capture_details["seller_receivable_breakdown"]["net_amount"]["currency_code"].downcase, cents: capture_details["seller_receivable_breakdown"]["net_amount"]["value"]) # These amounts are not actually used right now as we don't need to create balance-transactions for seller # in case of paypal native txns. Only the currency from gumroad_amount (which is always USD) is used # to create affiliate balance-transactions. FlowOfFunds.new( issued_amount:, settled_amount:, gumroad_amount:, merchant_account_gross_amount:, merchant_account_net_amount: ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/paypal/paypal_charge_processor.rb
app/business/payments/charging/implementations/paypal/paypal_charge_processor.rb
# frozen_string_literal: true class PaypalChargeProcessor extend PaypalApiResponse extend CurrencyHelper DISPLAY_NAME = "PayPal" MAXIMUM_DESCRIPTOR_LENGTH = 22 MAXIMUM_ITEM_NAME_LENGTH = 127 PAYPAL_VALID_CHARACTERS_REGEX = /[^A-Z0-9. ]/i private_constant :PAYPAL_VALID_CHARACTERS_REGEX DISPUTE_OUTCOME_SELLER_FAVOUR = %w[RESOLVED_SELLER_FAVOUR CANCELED_BY_BUYER DENIED].freeze private_constant :DISPUTE_OUTCOME_SELLER_FAVOUR # https://developer.paypal.com/docs/api/orders/v1/ VALID_TRANSACTION_STATUSES = %w(created approved completed) def self.charge_processor_id "paypal" end def self.handle_paypal_event(paypal_event) raise "Event for transaction #{paypal_event.try(:[], 'txn_id')} does not have an invoice field" if paypal_event["invoice"].nil? event_type = determine_paypal_event_type(paypal_event) return if event_type.nil? parent_txn_id = paypal_event["parent_txn_id"] # Only process dispute won events if the original payment status tells us the payment is in the completed state. # Paypal tells us the original reversal (created at dispute creation) was cancelled just before telling us we lost the dispute, # so we check the payment status of the main transaction to know what the cancelled reversal message is really telling us. return if event_type == ChargeEvent::TYPE_DISPUTE_WON && PaypalChargeProcessor.new.get_charge(parent_txn_id).paypal_payment_status != PaypalApiPaymentStatus::COMPLETED currency = paypal_event["mc_currency"].downcase fee_cents = Money.new(paypal_event["mc_fee"].to_f * 100, currency).cents if paypal_event["mc_fee"] event = ChargeEvent.new event.type = event_type event.charge_event_id = paypal_event["txn_id"] event.charge_processor_id = BraintreeChargeProcessor.charge_processor_id event.charge_reference = if paypal_event["invoice"].to_s.starts_with?(Charge::COMBINED_CHARGE_PREFIX) charge = Charge.find_by_external_id!(paypal_event["invoice"].sub(Charge::COMBINED_CHARGE_PREFIX, "")) Charge::COMBINED_CHARGE_PREFIX + charge.id.to_s else paypal_event["invoice"] end event.comment = paypal_event["reason_code"] || paypal_event["payment_status"] event.created_at = DateTime.parse(paypal_event["payment_date"]) event.extras = { "fee_cents" => fee_cents } if fee_cents event.flow_of_funds = nil ChargeProcessor.handle_event(event) end # Events like PAYMENT.CAPTURE.REFUNDED, PAYMENT.CAPTURE.COMPLETED are just # acknowledgements from Paypal. We get all the information in events(handled # in the method below) hence, we don't do anything on these events. def self.handle_order_events(event_info) # Use the master DB to ensure we're looking at the latest version and have the latest state. ActiveRecord::Base.connection.stick_to_primary! case event_info["event_type"] when PaypalEventType::CUSTOMER_DISPUTE_CREATED handle_dispute_created_event(event_info) when PaypalEventType::CUSTOMER_DISPUTE_RESOLVED handle_dispute_resolved_event(event_info) when PaypalEventType::PAYMENT_CAPTURE_COMPLETED handle_payment_capture_completed_event(event_info) when PaypalEventType::PAYMENT_CAPTURE_DENIED handle_payment_capture_denied_event(event_info) when PaypalEventType::PAYMENT_CAPTURE_REVERSED, PaypalEventType::PAYMENT_CAPTURE_REFUNDED handle_payment_capture_refunded_event(event_info) end end def self.handle_dispute_created_event(event_info) handle_dispute_event(event_info, ChargeEvent::TYPE_DISPUTE_FORMALIZED) rescue StandardError => e raise ChargeProcessorError, build_error_message(e.message, event_info) end private_class_method :handle_dispute_created_event def self.handle_dispute_resolved_event(event_info) dispute_outcome = event_info["resource"]["dispute_outcome"]["outcome_code"] event_type = determine_resolved_dispute_event_type(dispute_outcome) handle_dispute_event(event_info, event_type) rescue StandardError => e raise ChargeProcessorError, build_error_message(e.message, event_info) end private_class_method :handle_dispute_resolved_event def self.handle_payment_capture_completed_event(event_info) paypal_fee = event_info.dig("resource", "seller_receivable_breakdown", "paypal_fee") return if paypal_fee.blank? purchase = Purchase.successful.find_by(stripe_transaction_id: event_info["resource"]["id"]) return unless purchase purchase.processor_fee_cents_currency = paypal_fee["currency_code"] purchase.processor_fee_cents = paypal_fee["value"].to_f * unit_scaling_factor(purchase.processor_fee_cents_currency) purchase.save! end private_class_method :handle_payment_capture_completed_event def self.handle_payment_capture_denied_event(event_info) refund_purchase(capture_id: event_info["resource"]["id"]) end private_class_method :handle_payment_capture_denied_event def self.handle_payment_capture_refunded_event(event_info) refund_id = event_info["resource"]["id"] return if Refund.where(processor_refund_id: refund_id).exists? capture_url = event_info["resource"]["links"].find { |link| link["href"].include?("/v2/payments/captures/") } capture_id = capture_url["href"].split("/").last refunded_amount = event_info["resource"]["seller_payable_breakdown"]["total_refunded_amount"]["value"] refund_currency = event_info["resource"]["seller_payable_breakdown"]["total_refunded_amount"]["currency_code"] usd_amount_cents = get_usd_cents(refund_currency.downcase, (refunded_amount.to_f * unit_scaling_factor(refund_currency)).to_i) refund_purchase(capture_id:, usd_amount_cents:, processor_refund: OpenStruct.new({ id: refund_id, status: event_info["resource"]["status"] })) end private_class_method :handle_payment_capture_refunded_event def self.refund_purchase(capture_id:, usd_amount_cents: nil, processor_refund: nil) raise ArgumentError, "No paypal transaction id found in refund webhook" if capture_id.blank? purchase = Purchase.find_by(stripe_transaction_id: capture_id) return unless purchase&.successful? usd_cents_to_refund = usd_amount_cents.present? ? [usd_amount_cents, purchase.gross_amount_refundable_cents].min : purchase.gross_amount_refundable_cents flow_of_funds = FlowOfFunds.build_simple_flow_of_funds(Currency::USD, usd_cents_to_refund) purchase.refund_purchase!(flow_of_funds, purchase.seller_id, processor_refund) end private_class_method :refund_purchase def self.handle_dispute_event(event_info, event_type) event = ChargeEvent.new event.type = event_type event.charge_event_id = event_info["resource"]["dispute_id"] event.charge_processor_id = PaypalChargeProcessor.charge_processor_id event.charge_id = event_info["resource"]["disputed_transactions"][0]["seller_transaction_id"] event.comment = event_info["resource"]["reason"] || event_info["resource"]["status"] event.created_at = DateTime.parse(event_info["resource"]["create_time"]) event.extras = { reason: event_info["resource"]["reason"] || event_info["resource"]["status"], charge_processor_dispute_id: event_info["resource"]["dispute_id"] } event.flow_of_funds = nil ChargeProcessor.handle_event(event) end # Dispute Outcome Types # RESOLVED_BUYER_FAVOUR - The dispute was resolved in the customer's favor. # RESOLVED_SELLER_FAVOUR - The dispute was resolved in the merchant's favor. # RESOLVED_WITH_PAYOUT - PayPal provided the merchant or customer with protection and the case is resolved. # CANCELED_BY_BUYER - The customer canceled the dispute. # ACCEPTED - The dispute was accepted. # DENIED - The dispute was denied. # Empty - The dispute was not resolved. def self.determine_resolved_dispute_event_type(dispute_outcome) if DISPUTE_OUTCOME_SELLER_FAVOUR.include? dispute_outcome.upcase ChargeEvent::TYPE_DISPUTE_WON else ChargeEvent::TYPE_DISPUTE_LOST end end def self.generate_billing_agreement_token(shipping: false) paypal_rest_api = PaypalRestApi.new api_response = paypal_rest_api.generate_billing_agreement_token(shipping:) log_paypal_api_response("Generate billing agreement token", nil, api_response) if paypal_rest_api.successful_response?(api_response) && api_response.result.token_id.present? api_response.result.token_id else raise ChargeProcessorError, build_error_message(api_response.code, api_response.response) end rescue => e raise ChargeProcessorError, build_error_message(e.message, e.backtrace) end def self.create_billing_agreement(billing_agreement_token_id:) paypal_rest_api = PaypalRestApi.new api_response = paypal_rest_api.create_billing_agreement(billing_agreement_token_id:) log_paypal_api_response("Create billing agreement", billing_agreement_token_id, api_response) if paypal_rest_api.successful_response?(api_response) && api_response.result.id.present? open_struct_to_hash(api_response.result).as_json else raise ChargeProcessorError, build_error_message(api_response.code, api_response.response) end rescue => e raise ChargeProcessorError, build_error_message(e.message, e.backtrace) end def self.fetch_order(order_id:) paypal_rest_api = PaypalRestApi.new api_response = paypal_rest_api.fetch_order(order_id:) log_paypal_api_response("Fetch Order", order_id, api_response) if paypal_rest_api.successful_response?(api_response) open_struct_to_hash(api_response.result).as_json else raise ChargeProcessorError, build_error_message(api_response.code, api_response.response) end end def self.paypal_order_info(purchase) merchant_account = purchase.merchant_account || purchase.seller.merchant_account(charge_processor_id) currency = merchant_account.currency item_name = sanitize_for_paypal(purchase.link.name, MAXIMUM_ITEM_NAME_LENGTH).presence || sanitize_for_paypal(purchase.link.general_permalink, MAXIMUM_ITEM_NAME_LENGTH) create_purchase_unit_info(permalink: purchase.link.unique_permalink, item_name:, currency:, merchant_id: merchant_account.charge_processor_merchant_id, descriptor: sanitize_for_paypal(purchase.statement_description, MAXIMUM_DESCRIPTOR_LENGTH), invoice_id: purchase.external_id, price_cents_usd: price_cents(purchase), shipping_cents_usd: purchase.shipping_cents, tax_cents_usd: tax_cents(purchase), fee_cents_usd: purchase.total_transaction_amount_for_gumroad_cents, total_cents_usd: purchase.total_transaction_cents, quantity: purchase.quantity) end def self.create_order_from_purchase(purchase) purchase_unit_info = paypal_order_info(purchase) create_order(purchase_unit_info) end def self.create_order_from_charge(charge) purchase_unit_info = paypal_order_info_from_charge(charge) create_order(purchase_unit_info) end def self.paypal_order_info_from_charge(charge) merchant_account = charge.merchant_account currency = merchant_account.currency items = [] price_cents_usd = shipping_cents_usd = tax_cents_usd = fee_cents_usd = 0 charge.purchases.each do |purchase| item_name = sanitize_for_paypal(purchase.link.name, MAXIMUM_ITEM_NAME_LENGTH).presence || sanitize_for_paypal(purchase.link.general_permalink, MAXIMUM_ITEM_NAME_LENGTH) items << { name: item_name, quantity: purchase.quantity, sku: purchase.link.unique_permalink, unit_amount: { currency_code: currency.upcase, value: format_money(price_cents(purchase) / purchase.quantity, currency) }, currency: } price_cents_usd += price_cents(purchase) shipping_cents_usd += purchase.shipping_cents tax_cents_usd += tax_cents(purchase) fee_cents_usd += purchase.total_transaction_amount_for_gumroad_cents end purchase_unit_info = {} purchase_unit_info[:invoice_id] = charge.reference_id_for_charge_processors purchase_unit_info[:currency] = currency purchase_unit_info[:merchant_id] = merchant_account.charge_processor_merchant_id purchase_unit_info[:descriptor] = sanitize_for_paypal(charge.statement_description, MAXIMUM_DESCRIPTOR_LENGTH) purchase_unit_info[:items] = items purchase_unit_info[:shipping] = format_money(shipping_cents_usd, currency) purchase_unit_info[:tax] = format_money(tax_cents_usd, currency) purchase_unit_info[:fee] = format_money(fee_cents_usd, currency) purchase_unit_info[:price] = items.sum { |item| item[:unit_amount][:value] * item[:quantity] } purchase_unit_info[:total] = purchase_unit_info[:price] + purchase_unit_info[:shipping] + purchase_unit_info[:tax] purchase_unit_info end def self.tax_cents(purchase) if purchase.gumroad_responsible_for_tax? purchase.gumroad_tax_cents elsif purchase.was_tax_excluded_from_price purchase.tax_cents else 0 # Taxes are included in price in this case. end end def self.price_cents(purchase) price_cents = purchase.price_cents - purchase.shipping_cents price_cents -= purchase.tax_cents if purchase.was_tax_excluded_from_price price_cents end def self.format_money(money, currency) return 0 if money.blank? formatted_amount_for_paypal(usd_cents_to_currency(currency, money), currency) end def self.formatted_amount_for_paypal(cents, currency) amount = Money.new(cents, currency).amount # PayPal does not accept decimals in TWD, HUF, and JPY currencies # Ref: https://developer.paypal.com/docs/api/reference/currency-codes/ amount = amount.round(0).to_i if %w(TWD HUF JPY).include?(currency.upcase) amount end def self.create_purchase_unit_info(permalink:, item_name:, currency:, merchant_id:, descriptor:, invoice_id: nil, price_cents_usd:, shipping_cents_usd:, fee_cents_usd:, tax_cents_usd:, total_cents_usd:, quantity:) purchase_unit_info = {} purchase_unit_info[:invoice_id] = invoice_id if invoice_id purchase_unit_info[:product_permalink] = permalink purchase_unit_info[:item_name] = item_name purchase_unit_info[:currency] = currency purchase_unit_info[:merchant_id] = merchant_id purchase_unit_info[:descriptor] = descriptor purchase_unit_info[:price] = format_money(price_cents_usd, currency) purchase_unit_info[:shipping] = format_money(shipping_cents_usd, currency) purchase_unit_info[:tax] = format_money(tax_cents_usd, currency) purchase_unit_info[:fee] = format_money(fee_cents_usd, currency) purchase_unit_info[:quantity] = quantity purchase_unit_info[:unit_price] = format_money(price_cents_usd / quantity, currency) # In case the product currency and merchant account currency are different, # there's a chance that after conversion `unit_price * quantity` does not equal to `price`. # So we adjust the `price` and `total` such that: # price = unit_price * quantity # total = price + shipping + tax purchase_unit_info[:price] = purchase_unit_info[:unit_price] * purchase_unit_info[:quantity] purchase_unit_info[:total] = purchase_unit_info[:price] + purchase_unit_info[:shipping] + purchase_unit_info[:tax] purchase_unit_info end def self.create_order_from_product_info(product_info) product = Link.find_by_external_id(product_info[:external_id]) merchant_account = product.user.merchant_account(charge_processor_id) currency = product_info[:currency_code] item_name = sanitize_for_paypal(product.name, MAXIMUM_ITEM_NAME_LENGTH).presence || sanitize_for_paypal(product.general_permalink, MAXIMUM_ITEM_NAME_LENGTH) purchase_unit_info = create_purchase_unit_info(permalink: product.unique_permalink, item_name:, currency: merchant_account.currency, merchant_id: merchant_account.charge_processor_merchant_id, descriptor: sanitize_for_paypal(product.statement_description, MAXIMUM_DESCRIPTOR_LENGTH), price_cents_usd: get_usd_cents(currency, product_info[:price_cents].to_i), shipping_cents_usd: get_usd_cents(currency, product_info[:shipping_cents].to_i), tax_cents_usd: get_usd_cents(currency, product_info[:vat_cents].to_i > 0 ? product_info[:exclusive_vat_cents].to_i : product_info[:exclusive_tax_cents].to_i), fee_cents_usd: product.gumroad_amount_for_paypal_order( amount_cents: get_usd_cents(currency, product_info[:price_cents].to_i), affiliate_id: product_info[:affiliate_id], vat_cents: get_usd_cents(currency, product_info[:vat_cents].to_i), was_recommended: !!product_info[:was_recommended]), total_cents_usd: get_usd_cents(currency, product_info[:total_cents].to_i), quantity: product_info[:quantity].to_i) create_order(purchase_unit_info) end def self.update_order_from_product_info(paypal_order_id, product_info) if paypal_order_id.blank? || product_info.blank? Bugsnag.notify("PayPal order ID or product info not present in update order request") raise ChargeProcessorError, "PayPal order ID or product info not present in update order request" end product = Link.find_by_external_id(product_info[:external_id]) merchant_account = product.user.merchant_account(charge_processor_id) currency = product_info[:currency_code] item_name = sanitize_for_paypal(product.name, MAXIMUM_ITEM_NAME_LENGTH).presence || sanitize_for_paypal(product.general_permalink, MAXIMUM_ITEM_NAME_LENGTH) purchase_unit_info = create_purchase_unit_info(permalink: product.unique_permalink, item_name:, currency: merchant_account.currency, merchant_id: merchant_account.charge_processor_merchant_id, descriptor: sanitize_for_paypal(product.statement_description, MAXIMUM_DESCRIPTOR_LENGTH), price_cents_usd: get_usd_cents(currency, product_info[:price_cents].to_i), shipping_cents_usd: get_usd_cents(currency, product_info[:shipping_cents].to_i), tax_cents_usd: get_usd_cents(currency, product_info[:vat_cents].to_i > 0 ? product_info[:exclusive_vat_cents].to_i : product_info[:exclusive_tax_cents].to_i), fee_cents_usd: product.gumroad_amount_for_paypal_order( amount_cents: get_usd_cents(currency, product_info[:price_cents].to_i), affiliate_id: product_info[:affiliate_id], vat_cents: get_usd_cents(currency, product_info[:vat_cents].to_i), was_recommended: !!product_info[:was_recommended]), total_cents_usd: get_usd_cents(currency, product_info[:total_cents].to_i), quantity: product_info[:quantity].to_i) update_order(paypal_order_id, purchase_unit_info) end def self.create_order(purchase_unit_info) if purchase_unit_info.blank? Bugsnag.notify("Products are not present in create order request") raise ChargeProcessorError, "Products are not present in create order request" end paypal_rest_api = PaypalRestApi.new api_response = paypal_rest_api.create_order(purchase_unit_info:) log_paypal_api_response("Create Order", nil, api_response) if paypal_rest_api.successful_response?(api_response) && api_response.result.id.present? api_response.result.id else error_message = PaypalChargeProcessor.build_error_message("Failed paypal create order: ", api_response.result.details&.first&.description) raise determine_create_order_error(api_response), error_message end end def self.update_order(paypal_order_id, purchase_unit_info) paypal_rest_api = PaypalRestApi.new api_response = paypal_rest_api.update_order(order_id: paypal_order_id, purchase_unit_info:) log_paypal_api_response("Update Order", nil, api_response) paypal_rest_api.successful_response?(api_response) end def self.capture(order_id:, billing_agreement_id: nil) paypal_rest_api = PaypalRestApi.new api_response = paypal_rest_api.capture(order_id:, billing_agreement_id:) log_paypal_api_response("Capture Order", order_id, api_response) if paypal_rest_api.successful_response?(api_response) && api_response.result.id.present? api_response.result else error_message = PaypalChargeProcessor.build_error_message("Failed paypal capture order: ", api_response.result.details[0].description) raise determine_capture_order_error(api_response), error_message end end def get_chargeable_for_params(params, _gumroad_guid) if params[:billing_agreement_id].present? PaypalChargeable.new(params[:billing_agreement_id], params[:visual], params[:card_country]) elsif params[:paypal_order_id].present? PaypalApprovedOrderChargeable.new(params[:paypal_order_id], params[:visual], params[:card_country]) end end def get_chargeable_for_data(reusable_token, _payment_method_id, _fingerprint, _stripe_setup_intent_id, _stripe_payment_intent_id, _last4, _number_length, visual, _expiry_month, _expiry_year, _card_type, country, _zip_code = nil, merchant_account: nil) PaypalChargeable.new(reusable_token, visual, country) end def search_charge(purchase:) if purchase.paypal_order_id.present? get_charge_for_order_api(nil, purchase.paypal_order_id) end end def get_charge(charge_id, **_args) charge = Charge.find_by(processor_transaction_id: charge_id) purchase = Purchase.paypal_orders.where(stripe_transaction_id: charge_id).first unless charge.present? if charge get_charge_for_order_api(charge_id, charge.paypal_order_id) elsif purchase get_charge_for_order_api(charge_id, purchase.paypal_order_id) else get_charge_for_express_checkout_api(charge_id) end end def create_payment_intent_or_charge!(_merchant_account, chargeable, _amount_cents, _amount_for_gumroad_cents, reference, _description, **_args) charge_or_purchase = reference.starts_with?(Charge::COMBINED_CHARGE_PREFIX) ? Charge.find_by_external_id(reference.sub(Charge::COMBINED_CHARGE_PREFIX, "")) : Purchase.find_by_external_id(reference) if chargeable.instance_of?(PaypalApprovedOrderChargeable) update_invoice_id(order_id: charge_or_purchase.paypal_order_id, invoice_id: reference) capture_order(order_id: charge_or_purchase.paypal_order_id) else paypal_order_id = charge_or_purchase.is_a?(Charge) ? self.class.create_order_from_charge(charge_or_purchase) : self.class.create_order_from_purchase(charge_or_purchase) charge_or_purchase.update!(paypal_order_id:) charge_or_purchase.purchases.each { |purchase| purchase.update!(paypal_order_id:) } if charge_or_purchase.is_a?(Charge) capture_order(order_id: paypal_order_id, billing_agreement_id: chargeable.fingerprint) end end def update_invoice_id(order_id:, invoice_id:) paypal_rest_api = PaypalRestApi.new api_response = paypal_rest_api.update_invoice_id(order_id:, invoice_id:) unless paypal_rest_api.successful_response?(api_response) error_message = PaypalChargeProcessor.build_error_message("Failed paypal update order: ", api_response.result.details&.first&.description) raise determine_update_order_error(api_response), error_message end end def capture_order(order_id:, billing_agreement_id: nil) paypal_transaction = self.class.capture(order_id:, billing_agreement_id:) capture = paypal_transaction.purchase_units[0].payments.captures[0] if capture.status.downcase == PaypalApiPaymentStatus::COMPLETED.downcase || (capture.status.downcase == PaypalApiPaymentStatus::PENDING.downcase && capture.status_details.reason.upcase == "PENDING_REVIEW") charge = PaypalCharge.new(paypal_transaction_id: capture.id, order_api_used: true, payment_details: paypal_transaction) PaypalChargeIntent.new(charge:) else if capture.status.downcase == PaypalApiPaymentStatus::PENDING.downcase && capture.status_details.reason.upcase == "ECHECK" merchant_id = paypal_transaction.purchase_units[0].payee.merchant_id refund!(capture.id, merchant_account: MerchantAccount.find_by(charge_processor_merchant_id: merchant_id), paypal_order_purchase_unit_refund: true) end raise ChargeProcessorCardError.new("paypal_capture_failure", "PayPal transaction failed with status #{capture.status}", charge_id: capture.id) end end def refund!(charge_id, amount_cents: nil, merchant_account: nil, paypal_order_purchase_unit_refund: nil, **_args) if paypal_order_purchase_unit_refund refund_response = refund_order_purchase_unit!(charge_id, merchant_account, amount_cents) PaypalOrderRefund.new(refund_response, charge_id) else if amount_cents.nil? refund_request = paypal_api.build_refund_transaction(TransactionID: charge_id, RefundType: PaypalApiRefundType::FULL) else amount = amount_cents / 100.0 refund_request = paypal_api.build_refund_transaction(TransactionID: charge_id, RefundType: PaypalApiRefundType::PARTIAL, Amount: amount) end refund_response = paypal_api.refund_transaction(refund_request) if refund_response.errors.present? error = refund_response.errors.first error_code = error.ErrorCode.to_i case error_code when PaypalApiErrorCodeRange::REFUND_VALIDATION raise ChargeProcessorAlreadyRefundedError, error.LongMessage if error.LongMessage[/been fully refunded/].present? raise ChargeProcessorInvalidRequestError, PaypalChargeProcessor.build_error_message(error_code, error.LongMessage) when PaypalApiErrorCodeRange::REFUND_FAILURE raise ChargeProcessorCardError.new(error_code, error.LongMessage, charge_id:) else raise ChargeProcessorInvalidRequestError, PaypalChargeProcessor.build_error_message(error_code, error.LongMessage) end end PaypalChargeRefund.new(refund_response, charge_id) end rescue *INTERNET_EXCEPTIONS => e raise ChargeProcessorUnavailableError, e end def holder_of_funds(_merchant_account) HolderOfFunds::GUMROAD end def transaction_url(charge_id) sub_domain = Rails.env.production? ? "history" : "sandbox" "https://#{sub_domain}.paypal.com/us/cgi-bin/webscr?cmd=_history-details-from-hub&id=#{charge_id}" end private_class_method def self.determine_paypal_event_type(paypal_event) case paypal_event["payment_status"] when "Reversed" ChargeEvent::TYPE_DISPUTE_FORMALIZED when "Canceled_Reversal" ChargeEvent::TYPE_DISPUTE_WON when "Completed" ChargeEvent::TYPE_INFORMATIONAL end end private_class_method def self.build_error_message(error_code, error_message) "#{error_code}|#{error_message}" end private_class_method def self.paypal_api PayPal::SDK::Merchant::API.new end def self.log_paypal_api_response(api_label, resource_id, api_response) Rails.logger.info("#{api_label} (#{resource_id}) headers => #{api_response.headers.inspect}") Rails.logger.info("#{api_label} (#{resource_id}) body => #{api_response.inspect}") end private def paypal_api PaypalChargeProcessor.paypal_api end def get_charge_for_express_checkout_api(charge_id) transaction_details = paypal_api.get_transaction_details(paypal_api.build_get_transaction_details(TransactionID: charge_id)) if transaction_details.errors.present? error = transaction_details.errors.first raise ChargeProcessorInvalidRequestError, PaypalChargeProcessor.build_error_message(error.error_code, error.LongMessage) end PaypalCharge.new(paypal_transaction_id: charge_id, order_api_used: false, payment_details: { paypal_payment_info: transaction_details.PaymentTransactionDetails.PaymentInfo, paypal_payer_info: transaction_details.PaymentTransactionDetails.PayerInfo }) rescue *INTERNET_EXCEPTIONS => e raise ChargeProcessorUnavailableError, e end def get_charge_for_order_api(capture_id, order_id) order_details = PaypalChargeProcessor.fetch_order(order_id:) capture_id ||= order_details["purchase_units"][0]["payments"]["captures"][0]["id"] PaypalCharge.new(paypal_transaction_id: capture_id, order_api_used: true, payment_details: order_details) end # Types of error which could be raised while refunding using the Orders API: # # INTERNAL_ERROR (An internal service error occurred) # # MISSING_ARGS (Missing Required Arguments) # # INVALID_RESOURCE_ID (Requested resource ID was not found) # # PERMISSION_DENIED (Permission denied) # # TRANSACTION_REFUSED (Request was refused) # # INVALID_PAYER_ID (Payer ID is invalid) # # INSTRUMENT_DECLINED (Processor or bank declined funding instrument or it cannot be used for this payment) # # RISK_CONTROL_MAX_AMOUNT (Request was refused) # # REFUND_ALREADY_INITIATED (Refund refused. Refund was already issued for transaction) # # REFUND_FAILED_INSUFFICIENT_FUNDS (Refund failed due to insufficient funds in your PayPal account) # # EXTDISPUTE_REFUND_FAILED_INSUFFICIENT_FUNDS (Refund failed due to insufficient funds in seller's PayPal account) def refund_order_purchase_unit!(capture_id, merchant_account, amount_cents) paypal_rest_api = PaypalRestApi.new api_response = paypal_rest_api.refund(capture_id:, merchant_account:, amount: self.class.format_money(amount_cents, merchant_account.currency)) self.class.log_paypal_api_response("Refund Order Purchase Unit", capture_id, api_response) if paypal_rest_api.successful_response?(api_response) api_response.result else error_message = PaypalChargeProcessor.build_error_message("Failed refund capture id - #{capture_id}", api_response.result.details[0].description) raise determine_refund_order_error(api_response), error_message end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
true
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/paypal/paypal_rest_api.rb
app/business/payments/charging/implementations/paypal/paypal_rest_api.rb
# frozen_string_literal: true class PaypalRestApi include CurrencyHelper PAYPAL_INTENT_CAPTURE = "CAPTURE" def initialize paypal_environment = Rails.env.production? ? PayPal::LiveEnvironment.new(PAYPAL_PARTNER_CLIENT_ID, PAYPAL_PARTNER_CLIENT_SECRET) : PayPal::SandboxEnvironment.new(PAYPAL_PARTNER_CLIENT_ID, PAYPAL_PARTNER_CLIENT_SECRET) @paypal_client = PayPal::PayPalHttpClient.new(paypal_environment) end def new_request(path:, verb:) OpenStruct.new({ path:, verb:, headers: rest_api_headers, body: {}, }) end def generate_billing_agreement_token(shipping: false) @request = new_request(path: "/v1/billing-agreements/agreement-tokens", verb: "POST") @request.body = { "payer": { "payment_method": "PAYPAL" }, "plan": { "type": "CHANNEL_INITIATED_BILLING", "merchant_preferences": { "return_url": "#{UrlService.domain_with_protocol}/paypal_ba_return", "cancel_url": "#{UrlService.domain_with_protocol}/paypal_ba_cancel", "accepted_pymt_type": "INSTANT", "skip_shipping_address": !shipping } } } execute_request end def create_billing_agreement(billing_agreement_token_id:) @request = new_request(path: "/v1/billing-agreements/agreements", verb: "POST") @request.headers["PayPal-Request-Id"] = "create-billing-agreement-#{billing_agreement_token_id}" @request.body = { "token_id": billing_agreement_token_id } execute_request end def create_order(purchase_unit_info:) @request = new_request(path: "/v2/checkout/orders", verb: "POST") if Rails.env.production? && purchase_unit_info[:invoice_id].present? @request.headers["PayPal-Request-Id"] = "create-order-#{purchase_unit_info[:invoice_id]}" end @request.headers["Prefer"] = "return=representation" order_params = { intent: PAYPAL_INTENT_CAPTURE, purchase_units: [purchase_unit(purchase_unit_info)], application_context: { brand_name: "Gumroad", shipping_preference: "NO_SHIPPING" } } @request.body = order_params execute_request end def update_invoice_id(order_id:, invoice_id:) @request = new_request(path: "/v2/checkout/orders/#{order_id}", verb: "PATCH") @request.headers["Prefer"] = "return=representation" @request.body = [{ op: "add", path: "/purchase_units/@reference_id=='default'/invoice_id", value: invoice_id }] execute_request end def update_order(order_id:, purchase_unit_info:) @request = new_request(path: "/v2/checkout/orders/#{order_id}", verb: "PATCH") @request.headers["Prefer"] = "return=representation" @request.body = [{ op: "replace", path: "/purchase_units/@reference_id=='default'", value: purchase_unit(purchase_unit_info) }] execute_request end def fetch_order(order_id:) @request = new_request(path: "/v2/checkout/orders/#{order_id}", verb: "GET") execute_request end def capture(order_id:, billing_agreement_id:) @request = new_request(path: "/v2/checkout/orders/#{order_id}/capture", verb: "POST") @request.headers["PayPal-Request-Id"] = "capture-#{order_id}" @request.headers["Prefer"] = "return=representation" if billing_agreement_id.present? @request.body = { "payment_source": { "token": { "id": billing_agreement_id, "type": "BILLING_AGREEMENT" } } } end execute_request end def refund(capture_id:, merchant_account: nil, amount: nil) paypal_account_id = merchant_account&.charge_processor_merchant_id currency = merchant_account&.currency # If for some reason we don't have the paypal account id or currency in our records, # fetch the original order and get those details from it if paypal_account_id.blank? || currency.blank? purchase = Purchase.where(stripe_transaction_id: capture_id).last raise ArgumentError, "No purchase found for paypal transaction id #{capture_id}" unless purchase.present? paypal_order = fetch_order(order_id: purchase.paypal_order_id).result if paypal_order.purchase_units.present? paypal_account_id ||= paypal_order.purchase_units[0].payee.merchant_id currency ||= paypal_order.purchase_units[0].amount.currency_code end end @request = new_request(path: "/v2/payments/captures/#{capture_id}/refund", verb: "POST") @request.headers["PayPal-Request-Id"] = "refund-#{capture_id}-#{amount}-#{timestamp}" @request.headers["Prefer"] = "return=representation" @request.headers["Paypal-Auth-Assertion"] = paypal_auth_assertion_header(paypal_account_id) @request.body = refund_body(amount, currency) execute_request end def successful_response?(api_response) (200...300).include?(api_response.status_code) end private def purchase_unit(purchase_unit_info) currency = purchase_unit_info[:currency] info = { amount: { currency_code: currency, value: purchase_unit_info[:total], breakdown: { shipping: money_object(currency:, value: purchase_unit_info[:shipping]), tax_total: money_object(currency:, value: purchase_unit_info[:tax]), item_total: money_object(currency:, value: purchase_unit_info[:price]) } }, payee: { merchant_id: purchase_unit_info[:merchant_id] }, items: purchase_unit_info[:items].presence || [ { name: purchase_unit_info[:item_name], unit_amount: money_object(currency: purchase_unit_info[:currency], value: purchase_unit_info[:unit_price]), quantity: purchase_unit_info[:quantity], sku: purchase_unit_info[:product_permalink] } ], soft_descriptor: purchase_unit_info[:descriptor], payment_instruction: { platform_fees: [ { amount: money_object(currency:, value: purchase_unit_info[:fee]), payee: { email_address: PAYPAL_PARTNER_EMAIL } }] } } info[:invoice_id] = purchase_unit_info[:invoice_id] if purchase_unit_info[:invoice_id] info end def refund_body(amount, currency) body = {} body[:amount] = money_object(currency:, value: amount) if amount.to_f > 0 body end def timestamp Time.current.to_f.to_s.delete(".") end def rest_api_headers { "Accept" => "application/json", "Accept-Language" => "en_US", "Authorization" => PaypalPartnerRestCredentials.new.auth_token, "Content-Type" => "application/json", "PayPal-Partner-Attribution-Id" => PAYPAL_BN_CODE, "PayPal-Request-Id" => timestamp } end def paypal_auth_assertion_header(seller_merchant_id) header_part_one = { alg: "none" }.to_json header_part_two = { payer_id: seller_merchant_id, iss: PAYPAL_PARTNER_CLIENT_ID }.to_json "#{Base64.strict_encode64(header_part_one)}.#{Base64.strict_encode64(header_part_two)}." end def money_object(currency:, value:) { currency_code: currency.upcase, value: } end def execute_request Rails.logger.info "Making Paypal request:: #{@request.inspect}" @paypal_client.execute(@request) rescue PayPalHttp::HttpError => e Rails.logger.error "Paypal request failed:: Status code: #{e.status_code}, Result: #{e.result.inspect}" OpenStruct.new(status_code: e.status_code, result: e.result) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/paypal/paypal_order_refund.rb
app/business/payments/charging/implementations/paypal/paypal_order_refund.rb
# frozen_string_literal: true class PaypalOrderRefund < ChargeRefund def initialize(response, capture_id) self.charge_processor_id = PaypalChargeProcessor.charge_processor_id self.charge_id = capture_id self.id = response.id @refund = response end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/paypal/paypal_card_fingerprint.rb
app/business/payments/charging/implementations/paypal/paypal_card_fingerprint.rb
# frozen_string_literal: true module PaypalCardFingerprint PAYPAL_FINGERPRINT_PREFIX = "paypal_" private_constant :PAYPAL_FINGERPRINT_PREFIX def self.build_paypal_fingerprint(email) return "#{PAYPAL_FINGERPRINT_PREFIX}#{email}" if email.present? nil end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/paypal/paypal_chargeable.rb
app/business/payments/charging/implementations/paypal/paypal_chargeable.rb
# frozen_string_literal: true class PaypalChargeable attr_reader :billing_agreement_id, :fingerprint, :last4, :number_length, :visual, :expiry_month, :expiry_year, :zip_code, :card_type, :country, :funding_type, :email, :payment_method_id def initialize(billing_agreement_id, visual, country) @billing_agreement_id = billing_agreement_id @fingerprint = billing_agreement_id @visual = visual @email = visual @card_type = CardType::PAYPAL @country = country end def charge_processor_id PaypalChargeProcessor.charge_processor_id end def prepare! billing_agreement_id.present? end def reusable_token!(_user) billing_agreement_id end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/paypal/paypal_charge_refund.rb
app/business/payments/charging/implementations/paypal/paypal_charge_refund.rb
# frozen_string_literal: true class PaypalChargeRefund < ChargeRefund include CurrencyHelper def initialize(paypal_refund_response, charge_id) self.charge_processor_id = PaypalChargeProcessor.charge_processor_id self.id = paypal_refund_response.RefundTransactionID self.charge_id = charge_id self.flow_of_funds = nil end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/paypal/paypal_charge_intent.rb
app/business/payments/charging/implementations/paypal/paypal_charge_intent.rb
# frozen_string_literal: true class PaypalChargeIntent < ChargeIntent def initialize(charge: nil) self.charge = charge end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/paypal/helpers/paypal_api_payment_status.rb
app/business/payments/charging/implementations/paypal/helpers/paypal_api_payment_status.rb
# frozen_string_literal: true module PaypalApiPaymentStatus REFUNDED = "Refunded" COMPLETED = "Completed" REVERSED = "Reversed" PENDING = "Pending" end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/paypal/helpers/paypal_api_error_code_range.rb
app/business/payments/charging/implementations/paypal/helpers/paypal_api_error_code_range.rb
# frozen_string_literal: true module PaypalApiErrorCodeRange GENERAL_VALIDATION = (81_000..99_998) UNAVAILABLE = (10_002..10_101) CAPTURE_INTERNAL = (10_001..10_482) PAYMENT_INSTRUMENT_FAILURE = (10_486..20_000) REFUND_VALIDATION = (10_001..10_406) REFUND_FAILURE = (10_414..13_751) end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/charging/implementations/paypal/helpers/paypal_api_refund_type.rb
app/business/payments/charging/implementations/paypal/helpers/paypal_api_refund_type.rb
# frozen_string_literal: true module PaypalApiRefundType FULL = "Full" PARTIAL = "Partial" end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/reports/deferred_refunds_reports.rb
app/business/payments/reports/deferred_refunds_reports.rb
# frozen_string_literal: true module DeferredRefundsReports def self.deferred_refunds_report(month, year) json = { "Purchases" => [] } range = DateTime.new(year, month)...DateTime.new(year, month).end_of_month refunded_purchase_ids = Refund.where(created_at: range).pluck(:purchase_id) deferred_refund_purchases = Purchase.successful.where(id: refunded_purchase_ids).where("succeeded_at < ?", range.first) disputed_purchase_ids = Dispute.where(created_at: range).where.not(state: "won").pluck(:purchase_id) deferred_disputes = Purchase.successful.where(id: disputed_purchase_ids).where("succeeded_at < ?", range.first) payment_methods = { "PayPal" => [deferred_refund_purchases.where(card_type: "paypal"), deferred_disputes.where(card_type: "paypal")], "Stripe" => [deferred_refund_purchases.where.not(card_type: "paypal").where(charge_processor_id: [nil, *ChargeProcessor.charge_processor_ids]), deferred_disputes.where.not(card_type: "paypal").where(charge_processor_id: [nil, *ChargeProcessor.charge_processor_ids])], } payment_methods.each do |name, charges| refunded_purchases = charges.first disputed_purchases = charges.second json["Purchases"] << { "Processor" => name, "Sales" => { total_transaction_count: refunded_purchases.count + disputed_purchases.count, total_transaction_cents: refunded_purchases.joins(:refunds).sum("refunds.total_transaction_cents") + disputed_purchases.sum(:total_transaction_cents), gumroad_tax_cents: refunded_purchases.joins(:refunds).sum("refunds.gumroad_tax_cents") + disputed_purchases.sum(:gumroad_tax_cents), affiliate_credit_cents: refunded_purchases.joins(:refunds).sum("TRUNCATE(purchases.affiliate_credit_cents * (refunds.amount_cents / purchases.price_cents), 0)") + disputed_purchases.sum(:affiliate_credit_cents), fee_cents: refunded_purchases.joins(:refunds).sum("refunds.fee_cents") + disputed_purchases.sum(:fee_cents) } } end json end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/reports/funds_received_reports.rb
app/business/payments/reports/funds_received_reports.rb
# frozen_string_literal: true module FundsReceivedReports def self.funds_received_report(month, year) json = {} range = DateTime.new(year, month)...DateTime.new(year, month).end_of_month successful_purchases = Purchase.successful.not_fully_refunded.not_chargedback_or_chargedback_reversed.where(created_at: range) refunded_purchase_ids = Refund.where(created_at: range).where(purchase_id: successful_purchases).pluck(:purchase_id) partially_refunded_purchases = successful_purchases.where(stripe_partially_refunded: true).where(id: refunded_purchase_ids) payment_methods = { "PayPal" => [successful_purchases.where(card_type: "paypal"), partially_refunded_purchases.where(card_type: "paypal")], "Stripe" => [successful_purchases.where.not(card_type: "paypal").where(charge_processor_id: [nil, *ChargeProcessor.charge_processor_ids]), partially_refunded_purchases.where.not(card_type: "paypal").where(charge_processor_id: [nil, *ChargeProcessor.charge_processor_ids])], } json["Purchases"] = payment_methods.map do |name, purchases| successful_or_partially_refunded_purchases = purchases.first partially_refunded_purchases = purchases.second { "Processor" => name, "Sales" => { total_transaction_count: successful_or_partially_refunded_purchases.count, total_transaction_cents: successful_or_partially_refunded_purchases.sum(:total_transaction_cents) - partially_refunded_purchases.joins(:refunds).sum("refunds.total_transaction_cents"), gumroad_tax_cents: successful_or_partially_refunded_purchases.sum(:gumroad_tax_cents) - partially_refunded_purchases.joins(:refunds).sum("refunds.gumroad_tax_cents"), affiliate_credit_cents: successful_or_partially_refunded_purchases.sum(:affiliate_credit_cents) - partially_refunded_purchases.joins(:refunds).sum("TRUNCATE(purchases.affiliate_credit_cents * (refunds.amount_cents / purchases.price_cents), 0)"), fee_cents: successful_or_partially_refunded_purchases.sum(:fee_cents) - partially_refunded_purchases.joins(:refunds).sum("refunds.fee_cents") } } end json end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/reports/stripe_currency_balances_report.rb
app/business/payments/reports/stripe_currency_balances_report.rb
# frozen_string_literal: true module StripeCurrencyBalancesReport extend CurrencyHelper def self.stripe_currency_balances_report currency_balances = {} stripe_balance = Stripe::Balance.retrieve stripe_balance.available.sort_by { _1["currency"] }.each do |balance| currency_balances[balance["currency"]] = balance["amount"] end stripe_balance.connect_reserved.sort_by { _1["currency"] }.each do |balance| currency_balances[balance["currency"]] += balance["amount"] if currency_balances[balance["currency"]].abs != balance["amount"].abs end CSV.generate do |csv| csv << %w(Currency Balance) currency_balances.each do |currency, balance| csv << [currency, is_currency_type_single_unit?(currency) ? balance : (balance / 100.0).round(2)] end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/events/stripe/stripe_event_handler.rb
app/business/payments/events/stripe/stripe_event_handler.rb
# frozen_string_literal: true class StripeEventHandler attr_accessor :params # See full list of events at https://stripe.com/docs/api/events/types ALL_HANDLED_EVENTS = %w{account.application.deauthorized account.updated capability.updated payout. charge. capital. radar. payment_intent.payment_failed}.freeze # Handle's a Stripe event. Calls out to the necessary modules # that handle different types of Stripe events. # # stripe_connect_account_id – the Stripe Account ID if the event is for # a connected Stripe Account, nil if the event # is for our Stripe Account def initialize(params) @params = params.to_hash.deep_symbolize_keys! end def handle_stripe_event unless ALL_HANDLED_EVENTS.any? { |evt| params[:type].to_s.starts_with?(evt) } Rails.logger.error("Unhandled event #{params[:type]}:: #{params}") return end stripe_connect_account_id = params[:user_id].present? ? params[:user_id] : params[:account] if stripe_connect_account_id.present? && stripe_connect_account_id != STRIPE_PLATFORM_ACCOUNT_ID if params && params[:type] == "account.application.deauthorized" handle_event_for_connected_account_deauthorized else with_stripe_error_handler do handle_event_for_connected_account(stripe_connect_account_id:) end end else handle_event_for_gumroad end rescue StandardError => e if Rails.env.staging? Rails.logger.error("Error while handling event with params #{params} :: #{e}") else raise e end end private def stripe_event @_stripe_event ||= Stripe::Util.convert_to_stripe_object(params, {}) end def handle_event_for_gumroad StripeChargeProcessor.handle_stripe_event(stripe_event) if stripe_event["type"].start_with?("charge.", "capital.", "radar.", "payment_intent.payment_failed") end def handle_event_for_connected_account(stripe_connect_account_id:) if stripe_event["type"].start_with?("charge.", "radar.", "payment_intent.payment_failed") StripeChargeProcessor.handle_stripe_event(stripe_event) elsif stripe_event["type"].start_with?("account.", "capability.") StripeMerchantAccountManager.handle_stripe_event(stripe_event) elsif stripe_event["type"].start_with?("payout.") StripePayoutProcessor.handle_stripe_event(stripe_event, stripe_connect_account_id:) end end def handle_event_for_connected_account_deauthorized params[:type] = "account.application.deauthorized" # Make sure type is always deauthorized deauthorized_stripe_event = Stripe::Util.convert_to_stripe_object(params, {}) StripeMerchantAccountManager.handle_stripe_event_account_deauthorized(deauthorized_stripe_event) end def with_stripe_error_handler yield rescue StandardError => exception if exception.message.include?("Application access may have been revoked.") handle_event_for_connected_account_deauthorized elsif exception.message.include?("a similar object exists in test mode, but a live mode key was used to make this request") # noop, we can safely ignore these else raise exception end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/events/paypal/paypal_event_handler.rb
app/business/payments/events/paypal/paypal_event_handler.rb
# frozen_string_literal: true class PaypalEventHandler attr_accessor :paypal_event IGNORED_TRANSACTION_TYPES = %w[express_checkout cart mp_signup mp_notification mp_cancel].freeze private_constant :IGNORED_TRANSACTION_TYPES def initialize(paypal_event) self.paypal_event = paypal_event end def schedule_paypal_event_processing Rails.logger.info("Paypal event: received IPN/Webhook #{paypal_event}") case paypal_event["event_type"] when *PaypalEventType::ORDER_API_EVENTS, *PaypalEventType::MERCHANT_ACCOUNT_EVENTS HandlePaypalEventWorker.perform_async(paypal_event) else HandlePaypalEventWorker.perform_in(10.minutes, paypal_event) end end def handle_paypal_event case paypal_event["event_type"] when *PaypalEventType::ORDER_API_EVENTS PaypalChargeProcessor.handle_order_events(paypal_event) when *PaypalEventType::MERCHANT_ACCOUNT_EVENTS PaypalMerchantAccountManager.new.handle_paypal_event(paypal_event) else handle_paypal_legacy_event end end private def handle_paypal_legacy_event if verified_ipn_payload? message_handler = determine_message_handler message_handler&.handle_paypal_event(paypal_event) else Rails.logger.info "Invalid IPN message for transaction #{paypal_event.try(:[], 'txn_id')}" end end # https://developer.paypal.com/docs/api-basics/notifications/ipn/IPNImplementation/#ipn-listener-request-response-flow def verified_ipn_payload? response = HTTParty.post(PAYPAL_IPN_VERIFICATION_URL, headers: { "User-Agent" => "Ruby-IPN-Verification-Script" }, body: ({ cmd: "_notify-validate" }.merge(paypal_event)).to_query, timeout: 60).parsed_response response == "VERIFIED" end # Private: Determine the handler for the PayPal event.The presence of an invoice field # in the event routes the message to the PaypalChargeProcessor. If not, it is routed # to the Payouts PayPal event handler # # paypal_event - The PayPal event that needs to be handled def determine_message_handler if paypal_event["invoice"] PaypalChargeProcessor elsif paypal_event["txn_type"] == "masspay" PaypalPayoutProcessor elsif paypal_event["txn_type"].in?(IGNORED_TRANSACTION_TYPES) nil else Bugsnag.notify("No message handler for PayPal message for transaction ID : #{paypal_event.try(:[], 'txn_id')}", paypal_event:) nil end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/events/paypal/paypal_event_type.rb
app/business/payments/events/paypal/paypal_event_type.rb
# frozen_string_literal: true class PaypalEventType CUSTOMER_DISPUTE_CREATED = "CUSTOMER.DISPUTE.CREATED" CUSTOMER_DISPUTE_RESOLVED = "CUSTOMER.DISPUTE.RESOLVED" PAYMENT_CAPTURE_COMPLETED = "PAYMENT.CAPTURE.COMPLETED" PAYMENT_CAPTURE_DENIED = "PAYMENT.CAPTURE.DENIED" PAYMENT_CAPTURE_REVERSED = "PAYMENT.CAPTURE.REVERSED" PAYMENT_CAPTURE_REFUNDED = "PAYMENT.CAPTURE.REFUNDED" MERCHANT_ONBOARDING_SELLER_GRANTED_CONSENT = "CUSTOMER.MERCHANT-INTEGRATION.SELLER-CONSENT-GRANTED" MERCHANT_ONBOARDING_COMPLETED = "MERCHANT.ONBOARDING.COMPLETED" MERCHANT_PARTNER_CONSENT_REVOKED = "MERCHANT.PARTNER-CONSENT.REVOKED" MERCHANT_IDENTITY_AUTH_CONSENT_REVOKED = "IDENTITY.AUTHORIZATION-CONSENT.REVOKED" MERCHANT_CAPABILITY_UPDATED = "CUSTOMER.MERCHANT-INTEGRATION.CAPABILITY-UPDATED" MERCHANT_SUBSCRIPTION_UPDATED = "CUSTOMER.MERCHANT-INTEGRATION.PRODUCT-SUBSCRIPTION-UPDATED" MERCHANT_EMAIL_CONFIRMED = "CUSTOMER.MERCHANT-INTEGRATION.SELLER-EMAIL-CONFIRMED" ORDER_API_EVENTS = [CUSTOMER_DISPUTE_CREATED, CUSTOMER_DISPUTE_RESOLVED, PAYMENT_CAPTURE_COMPLETED, PAYMENT_CAPTURE_DENIED, PAYMENT_CAPTURE_REVERSED, PAYMENT_CAPTURE_REFUNDED].freeze MERCHANT_ACCOUNT_EVENTS = [MERCHANT_ONBOARDING_COMPLETED, MERCHANT_PARTNER_CONSENT_REVOKED, MERCHANT_CAPABILITY_UPDATED, MERCHANT_SUBSCRIPTION_UPDATED, MERCHANT_EMAIL_CONFIRMED, MERCHANT_IDENTITY_AUTH_CONSENT_REVOKED, MERCHANT_ONBOARDING_SELLER_GRANTED_CONSENT].freeze end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/transfers/stripe/stripe_transfer_affiliate_credits.rb
app/business/payments/transfers/stripe/stripe_transfer_affiliate_credits.rb
# frozen_string_literal: false # Handles moving money around internally from Gumroad's Stripe # account, into Stripe managed accounts. Transfers should be performed # using the functions on this account rather than directly creating # Stripe::Transfer objects, since transfers created here are logged to # Slack rooms with the information needed to be able to track special # case transfers. module StripeTransferAffiliateCredits # Public: Creates a Stripe transfer that may or may not be attached to a charge. # Returns the Stripe::Transfer object that was created. def self.transfer_funds_to_account(description:, stripe_account_id:, amount_cents:, transfer_group:, related_charge_id: nil, metadata: nil) amount_cents_formatted = Money.new(amount_cents, "usd").format(no_cents_if_whole: false, symbol: true) message = <<-EOS Creating Affiliate transfer for #{description}. Related Charge ID: <#{StripeUrl.charge_url(related_charge_id)}|#{related_charge_id}> Amount: #{amount_cents_formatted} EOS message.strip! Rails.logger.info(message) transfer = Stripe::Transfer.create( destination: stripe_account_id, currency: "usd", amount: amount_cents, description:, metadata:, transfer_group:, expand: %w[balance_transaction application_fee.balance_transaction] ) transfer end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/transfers/stripe/stripe_transfer_internally_to_creator.rb
app/business/payments/transfers/stripe/stripe_transfer_internally_to_creator.rb
# frozen_string_literal: true # Handles moving money around internally from Gumroad's Stripe # account, into Stripe managed accounts. Transfers should be performed # using the functions on this account rather than directly creating # Stripe::Transfer objects, since transfers created here are logged to # Slack rooms with the information needed to be able to track special # case transfers. module StripeTransferInternallyToCreator # Public: Creates a Stripe transfer that may or may not be attached to a charge. # Logs the transfer to the #payments chat room. # Returns the Stripe::Transfer object that was created. def self.transfer_funds_to_account(message_why:, stripe_account_id:, currency:, amount_cents:, related_charge_id: nil, metadata: nil) description = message_why description += " Related Charge ID: #{related_charge_id}." if related_charge_id transfer = Stripe::Transfer.create( destination: stripe_account_id, currency:, description:, amount: amount_cents, metadata:, expand: %w[balance_transaction]) transfer end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/transfers/stripe/stripe_transfer_externally_to_gumroad.rb
app/business/payments/transfers/stripe/stripe_transfer_externally_to_gumroad.rb
# frozen_string_literal: true # Handles moving money for the Gumroad main Stripe account. # Provides information about how much money is in the Stripe # balance, and functionality to move money from the Stripe balance # to Gumroad's bank account. module StripeTransferExternallyToGumroad # Maximum amount Stripe is able to transfer in a single transfer. MAX_TRANSFER_AMOUNT = 99_999_999_99 private_constant :MAX_TRANSFER_AMOUNT # Public: Returns a hash of currencies to balance amounts in cents # of the balances available at Stripe on our master account. # The balances returned are only the balance available for transfer. def self.available_balances balance = Stripe::Balance.retrieve available_balances = {} balance.available.each do |balance_for_currency| currency = balance_for_currency["currency"] amount_cents = balance_for_currency["amount"] available_balances[currency] = amount_cents end available_balances end # Public: Transfers the amount from the Stripe master account to # the default bank account for the given currency. def self.transfer(currency, amount_cents) description = "#{currency.upcase} #{Time.current.strftime('%y%m%d %H%M')}" Stripe::Payout.create( amount: amount_cents, currency:, description:, statement_descriptor: description ) end # Public: Transfers the outstanding available balance in the Stripe # master account to the default bank account. # # buffer_cents – an amount that will be kept in the balance and will # not be transfered. def self.transfer_all_available_balances(buffer_cents: 0) available_balances.map do |currency, balance_cents| transfer_amount_cents = [balance_cents - buffer_cents, MAX_TRANSFER_AMOUNT].min next if transfer_amount_cents <= 0 transfer(currency, transfer_amount_cents) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/utilities/stripe_url.rb
app/business/payments/utilities/stripe_url.rb
# frozen_string_literal: true module StripeUrl def self.dashboard_url(account_id: nil) [base_url(account_id:), "dashboard"].join("/") end def self.event_url(event_id, account_id: nil) [base_url(account_id:), "events", event_id].join("/") end def self.transfer_url(transfer_id, account_id: nil) [base_url(account_id:), "transfers", transfer_id].join("/") end def self.charge_url(charge_id) [base_url, "payments", charge_id].join("/") end def self.connected_account_url(account_id) [base_url, "applications", "users", account_id].join("/") end private_class_method def self.base_url(account_id: nil) [ "https://dashboard.stripe.com", account_id, ("test" unless Rails.env.production?) ].compact.join("/") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/utilities/stripe_metadata.rb
app/business/payments/utilities/stripe_metadata.rb
# frozen_string_literal: false module StripeMetadata STRIPE_METADATA_VALUE_MAX_LENGTH = 500 STRIPE_METADATA_MAX_KEYS_LENGTH = 50 private_constant :STRIPE_METADATA_VALUE_MAX_LENGTH # Public: Builds a hash to be included in Stripe metadata that lists the items passed in, separated by the # separator and split over multiple hash keys in the format of key[0], key[1], etc. def self.build_metadata_large_list(items, key:, separator: ",", max_value_length: STRIPE_METADATA_VALUE_MAX_LENGTH, max_key_length: STRIPE_METADATA_MAX_KEYS_LENGTH) # Stripe metadata has a maximum length of 500 characters per key, so we need to breakup the items across multiple keys. items_in_slices = items.each_with_object([]) do |item, slices| slice = slices.last slice = (slices << "").last if slice.nil? || (slice.length + separator.length + item.length) > max_value_length slice << separator if slice.present? slice << item end items_in_slices.each_with_index.map { |slice, index| ["#{key}{#{index}}", slice] }[0..max_key_length].to_h end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/payments/utilities/braintree_exceptions.rb
app/business/payments/utilities/braintree_exceptions.rb
# frozen_string_literal: true module BraintreeExceptions UNAVAILABLE = [Braintree::ServiceUnavailableError, Braintree::SSLCertificateError, Braintree::ServerError, Braintree::UnexpectedError, *INTERNET_EXCEPTIONS].freeze end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/sales_tax/sales_tax_calculation.rb
app/business/sales_tax/sales_tax_calculation.rb
# frozen_string_literal: true class SalesTaxCalculation attr_reader :price_cents, :tax_cents, :zip_tax_rate, :business_vat_status, :used_taxjar, :gumroad_is_mpf, :taxjar_info, :is_quebec def initialize(price_cents:, tax_cents:, zip_tax_rate:, business_vat_status: nil, used_taxjar: false, gumroad_is_mpf: false, taxjar_info: nil, is_quebec: false) @price_cents = price_cents @tax_cents = tax_cents @zip_tax_rate = zip_tax_rate @business_vat_status = business_vat_status @used_taxjar = used_taxjar @gumroad_is_mpf = gumroad_is_mpf @taxjar_info = taxjar_info @is_quebec = is_quebec end def self.zero_tax(price_cents) SalesTaxCalculation.new(price_cents:, tax_cents: BigDecimal(0), zip_tax_rate: nil) end def self.zero_business_vat(price_cents) SalesTaxCalculation.new(price_cents:, tax_cents: BigDecimal(0), zip_tax_rate: nil, business_vat_status: :valid) end def to_hash { price_cents:, tax_cents:, business_vat_status:, has_vat_id_input: has_vat_id_input? } end private def has_vat_id_input? is_quebec || zip_tax_rate.present? && ( Compliance::Countries::EU_VAT_APPLICABLE_COUNTRY_CODES.include?(zip_tax_rate.country) || Compliance::Countries::GST_APPLICABLE_COUNTRY_CODES.include?(zip_tax_rate.country) || Compliance::Countries::NORWAY_VAT_APPLICABLE_COUNTRY_CODES.include?(zip_tax_rate.country) || Compliance::Countries::COUNTRIES_THAT_COLLECT_TAX_ON_ALL_PRODUCTS.include?(zip_tax_rate.country) || Compliance::Countries::COUNTRIES_THAT_COLLECT_TAX_ON_DIGITAL_PRODUCTS.include?(zip_tax_rate.country) ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/sales_tax/sales_tax_calculator.rb
app/business/sales_tax/sales_tax_calculator.rb
# frozen_string_literal: true require_relative "../../../lib/utilities/geo_ip" class SalesTaxCalculator attr_accessor :tax_rate, :product, :price_cents, :shipping_cents, :quantity, :buyer_location, :buyer_vat_id, :state, :is_us_taxable_state, :is_ca_taxable, :is_quebec def initialize(product:, price_cents:, shipping_cents: 0, quantity: 1, buyer_location:, buyer_vat_id: nil, from_discover: false) @tax_rate = nil @product = product @price_cents = price_cents @shipping_cents = shipping_cents @quantity = quantity @buyer_location = buyer_location @buyer_vat_id = buyer_vat_id validate @state = if buyer_location[:country] == Compliance::Countries::USA.alpha2 UsZipCodes.identify_state_code(buyer_location[:postal_code]) elsif buyer_location[:country] == Compliance::Countries::CAN.alpha2 buyer_location[:state] end @is_us_taxable_state = buyer_location[:country] == Compliance::Countries::USA.alpha2 && @state.present? && Compliance::Countries.taxable_state?(@state) @is_ca_taxable = buyer_location[:country] == Compliance::Countries::CAN.alpha2 && @state.present? @is_quebec = is_ca_taxable && @state == QUEBEC end def calculate return SalesTaxCalculation.zero_tax(price_cents) if price_cents == 0 return SalesTaxCalculation.zero_tax(price_cents) if product.user.has_brazilian_stripe_connect_account? return SalesTaxCalculation.zero_business_vat(price_cents) if is_vat_id_valid? sales_tax_calculation = calculate_with_taxjar return sales_tax_calculation if sales_tax_calculation calculate_with_lookup_table return SalesTaxCalculation.zero_tax(price_cents) if tax_rate.nil? return SalesTaxCalculation.zero_tax(price_cents) unless tax_eligible? tax_amount_cents = price_cents * tax_rate.combined_rate SalesTaxCalculation.new(price_cents:, tax_cents: tax_amount_cents, zip_tax_rate: tax_rate, business_vat_status: @buyer_vat_id.present? ? :invalid : nil, is_quebec:) end private def calculate_with_taxjar return unless is_us_taxable_state || is_ca_taxable origin = { country: GumroadAddress::COUNTRY.alpha2, state: GumroadAddress::STATE, zip: GumroadAddress::ZIP } destination = { country: buyer_location[:country], state: } destination[:zip] = buyer_location[:postal_code] if buyer_location[:country] == Compliance::Countries::USA.alpha2 nexus_address = { country: buyer_location[:country], state: } product_tax_code = Link::NATIVE_TYPES_TO_TAX_CODE[product.native_type] unit_price_dollars = price_cents / 100.0 / quantity shipping_dollars = shipping_cents / 100.0 begin taxjar_response_json = TaxjarApi.new.calculate_tax_for_order(origin:, destination:, nexus_address:, quantity:, product_tax_code:, unit_price_dollars:, shipping_dollars:) rescue *TaxjarErrors::CLIENT, *TaxjarErrors::SERVER return end taxjar_info = { combined_tax_rate: taxjar_response_json["rate"], state_tax_rate: taxjar_response_json["breakdown"]["state_tax_rate"], county_tax_rate: taxjar_response_json["breakdown"]["county_tax_rate"], city_tax_rate: taxjar_response_json["breakdown"]["city_tax_rate"], gst_tax_rate: taxjar_response_json["breakdown"]["gst_tax_rate"], pst_tax_rate: taxjar_response_json["breakdown"]["pst_tax_rate"], qst_tax_rate: taxjar_response_json["breakdown"]["qst_tax_rate"], jurisdiction_state: taxjar_response_json["jurisdictions"]["state"], jurisdiction_county: taxjar_response_json["jurisdictions"]["county"], jurisdiction_city: taxjar_response_json["jurisdictions"]["city"] } tax_amount_cents = (taxjar_response_json["amount_to_collect"] * 100.0).round.to_d SalesTaxCalculation.new(price_cents:, tax_cents: tax_amount_cents, zip_tax_rate: nil, business_vat_status: buyer_vat_id.present? ? :invalid : nil, used_taxjar: true, taxjar_info:, gumroad_is_mpf: is_us_taxable_state || is_ca_taxable, is_quebec:) end def validate raise SalesTaxCalculatorValidationError, "Price (cents) should be an Integer" unless @price_cents.is_a? Integer raise SalesTaxCalculatorValidationError, "Buyer Location should be a Hash" unless @buyer_location.is_a? Hash raise SalesTaxCalculatorValidationError, "Product should be a Link instance" unless @product.is_a? Link end def is_vat_id_valid? if buyer_location && Compliance::Countries::AUS.alpha2 == buyer_location[:country] AbnValidationService.new(@buyer_vat_id).process elsif buyer_location && Compliance::Countries::SGP.alpha2 == buyer_location[:country] GstValidationService.new(@buyer_vat_id).process elsif buyer_location && Compliance::Countries::CAN.alpha2 == buyer_location[:country] && state == QUEBEC QstValidationService.new(@buyer_vat_id).process elsif buyer_location && Compliance::Countries::NOR.alpha2 == buyer_location[:country] MvaValidationService.new(@buyer_vat_id).process elsif buyer_location && Compliance::Countries::KEN.alpha2 == buyer_location[:country] KraPinValidationService.new(@buyer_vat_id).process elsif buyer_location && Compliance::Countries::BHR.alpha2 == buyer_location[:country] TrnValidationService.new(@buyer_vat_id).process elsif buyer_location && Compliance::Countries::OMN.alpha2 == buyer_location[:country] OmanVatNumberValidationService.new(@buyer_vat_id).process elsif buyer_location && Compliance::Countries::NGA.alpha2 == buyer_location[:country] FirsTinValidationService.new(@buyer_vat_id).process elsif buyer_location && Compliance::Countries::TZA.alpha2 == buyer_location[:country] TraTinValidationService.new(@buyer_vat_id).process elsif buyer_location && (Compliance::Countries::COUNTRIES_THAT_COLLECT_TAX_ON_ALL_PRODUCTS.include?(buyer_location[:country]) || Compliance::Countries::COUNTRIES_THAT_COLLECT_TAX_ON_DIGITAL_PRODUCTS_WITH_TAX_ID_PRO_VALIDATION.include?(buyer_location[:country])) TaxIdValidationService.new(@buyer_vat_id, buyer_location[:country]).process else VatValidationService.new(@buyer_vat_id).process end end # Internal: Determine the sales tax to be levied if applicable. # # product_external_id - Product's external ID , used to retrieve metadata from cache. # buyer_location - Buyer location information to determine tax rate. def calculate_with_lookup_table return if tax_rate.present? return if product.nil? country_code = buyer_location[:country] return if country_code.blank? tax_rate = if is_us_taxable_state ZipTaxRate.alive .where(country: Compliance::Countries::USA.alpha2, state:) .not_is_seller_responsible .not_is_epublication_rate .first elsif Compliance::Countries::EU_VAT_APPLICABLE_COUNTRY_CODES.include?(buyer_location[:country]) zip_tax_rates = ZipTaxRate.alive .where(country: country_code) .not_is_seller_responsible zip_tax_rates = product.is_epublication? ? zip_tax_rates.is_epublication_rate : zip_tax_rates.not_is_epublication_rate zip_tax_rates.first elsif Compliance::Countries::AUS.alpha2 == buyer_location[:country] ZipTaxRate.alive .where(country: Compliance::Countries::AUS.alpha2) .not_is_seller_responsible .not_is_epublication_rate .first elsif Compliance::Countries::SGP.alpha2 == country_code rates = ZipTaxRate.alive .where(country: Compliance::Countries::SGP.alpha2) .not_is_seller_responsible .not_is_epublication_rate .order(created_at: :asc) .to_a rates.find { |rate| rate.applicable_years.include?(Time.current.year) } || rates.sort_by { |rate| rate.applicable_years.max }.last elsif Compliance::Countries::NOR.alpha2 == country_code zip_tax_rates = ZipTaxRate.alive .where(country: Compliance::Countries::NOR.alpha2) .not_is_seller_responsible zip_tax_rates = product.is_epublication? ? zip_tax_rates.is_epublication_rate : zip_tax_rates.not_is_epublication_rate zip_tax_rates.first elsif Compliance::Countries::CAN.alpha2 == country_code ZipTaxRate.alive .where(country: Compliance::Countries::CAN.alpha2, state:) .not_is_seller_responsible .not_is_epublication_rate .first else feature_flag = "collect_tax_#{country_code.downcase}" if Feature.active?(feature_flag) && (Compliance::Countries::COUNTRIES_THAT_COLLECT_TAX_ON_ALL_PRODUCTS + Compliance::Countries::COUNTRIES_THAT_COLLECT_TAX_ON_DIGITAL_PRODUCTS).include?(country_code) # Countries that have special e-publication rates special_epublication_countries = [ Compliance::Countries::ISL.alpha2, Compliance::Countries::CHE.alpha2, Compliance::Countries::MEX.alpha2 ] zip_tax_rates = ZipTaxRate.alive .where(country: country_code) .not_is_seller_responsible if special_epublication_countries.include?(country_code) zip_tax_rates = product.is_epublication? ? zip_tax_rates.is_epublication_rate : zip_tax_rates.not_is_epublication_rate end zip_tax_rates.first end end return unless tax_rate return if is_vat_exempt?(tax_rate) @tax_rate = tax_rate end # Certain territories of EU countries are exempt from VAT # https://docs.recurly.com/docs/eu-vat-2015#section-eu-territories-that-don-t-require-vat # This only supports Canary Islands for now, but should be expanded in the future. def is_vat_exempt?(tax_rate) return unless tax_rate if Compliance::Countries::EU_VAT_APPLICABLE_COUNTRY_CODES.include?(tax_rate.country) if tax_rate.country == "ES" if buyer_location[:ip_address] && (geocode = GEOIP.city(buyer_location[:ip_address]) rescue nil) geocode.country.iso_code == "ES" && geocode.subdivisions.collect(&:name).any? { |division_name| Compliance::VAT_EXEMPT_REGIONS.include?(division_name) } end end end end def tax_eligible? product_tax_eligible = product.is_physical && tax_rate.country == Compliance::Countries::USA.alpha2 product_tax_eligible ||= Compliance::Countries::EU_VAT_APPLICABLE_COUNTRY_CODES.include?(tax_rate.country) product_tax_eligible ||= tax_rate.country == Compliance::Countries::AUS.alpha2 product_tax_eligible ||= tax_rate.country == Compliance::Countries::SGP.alpha2 product_tax_eligible ||= tax_rate.country == Compliance::Countries::NOR.alpha2 Compliance::Countries::COUNTRIES_THAT_COLLECT_TAX_ON_ALL_PRODUCTS.each do |country_code| product_tax_eligible ||= tax_rate.country == country_code && Feature.active?("collect_tax_#{country_code.downcase}") end Compliance::Countries::COUNTRIES_THAT_COLLECT_TAX_ON_DIGITAL_PRODUCTS.each do |country_code| product_tax_eligible ||= tax_rate.country == country_code && !product.is_physical && Feature.active?("collect_tax_#{country_code.downcase}") end product_tax_eligible ||= is_us_taxable_state product_tax_eligible ||= is_ca_taxable product_tax_eligible || tax_rate.user_id.present? end def seller @_seller ||= product&.user end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/sales_tax/errors/sales_tax_calculator_validation_error.rb
app/business/sales_tax/errors/sales_tax_calculator_validation_error.rb
# frozen_string_literal: true class SalesTaxCalculatorValidationError < GumroadRuntimeError end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/sales_tax/taxjar/taxjar_errors.rb
app/business/sales_tax/taxjar/taxjar_errors.rb
# frozen_string_literal: true module TaxjarErrors CLIENT = [Taxjar::Error::BadRequest, Taxjar::Error::Unauthorized, Taxjar::Error::Forbidden, Taxjar::Error::NotFound, Taxjar::Error::MethodNotAllowed, Taxjar::Error::NotAcceptable, Taxjar::Error::Gone, Taxjar::Error::UnprocessableEntity, Taxjar::Error::TooManyRequests].freeze SERVER = [Taxjar::Error::InternalServerError, Taxjar::Error::ServiceUnavailable, *INTERNET_EXCEPTIONS].freeze end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/sales_tax/taxjar/taxjar_api.rb
app/business/sales_tax/taxjar/taxjar_api.rb
# frozen_string_literal: true class TaxjarApi def initialize @client = Taxjar::Client.new(api_key: TAXJAR_API_KEY, headers: { "x-api-version" => "2022-01-24" }, api_url: TAXJAR_ENDPOINT) @cache = Redis::Namespace.new(:taxjar_calculations, redis: $redis) end # Returns nil if there's an error calling TaxJar. def calculate_tax_for_order(origin:, destination:, nexus_address:, quantity:, product_tax_code:, unit_price_dollars:, shipping_dollars:) taxjar_params = { from_country: origin[:country], from_state: origin[:state], from_zip: origin[:zip], to_country: destination[:country], to_state: destination[:state], to_zip: destination[:zip], shipping: shipping_dollars, line_items: [ { quantity:, unit_price: unit_price_dollars, discount: 0, product_tax_code: } ], nexus_addresses: [nexus_address] } with_caching(taxjar_params) do @client.tax_for_order(taxjar_params).to_json end end def create_order_transaction(transaction_id:, transaction_date:, destination:, quantity:, product_tax_code:, amount_dollars:, shipping_dollars:, sales_tax_dollars:, unit_price_dollars:) taxjar_params = { transaction_id: transaction_id, transaction_date: transaction_date, provider: "api", from_country: GumroadAddress::COUNTRY.alpha2, from_state: GumroadAddress::STATE, from_zip: GumroadAddress::ZIP, to_country: destination[:country], to_state: destination[:state], to_zip: destination[:zip], amount: amount_dollars, shipping: shipping_dollars, sales_tax: sales_tax_dollars, line_items: [ { quantity:, unit_price: unit_price_dollars, sales_tax: sales_tax_dollars, product_tax_code:, } ] } with_caching(taxjar_params) do @client.create_order(taxjar_params).to_json end end private def with_caching(taxjar_params) cache_key = taxjar_params.to_s cached_json = @cache.get(cache_key) if cached_json JSON.parse(cached_json) else Rails.logger.info "Making TaxJar Request:: #{taxjar_params.inspect}" response_json = yield Rails.logger.info "TaxJar Response JSON:: #{response_json}" @cache.set(cache_key, response_json, ex: 10.minutes.to_i) JSON.parse(response_json) end rescue *TaxjarErrors::CLIENT => e Rails.logger.error "TaxJar Client Error: #{e.inspect}" Bugsnag.notify(e) raise e rescue *TaxjarErrors::SERVER => e Rails.logger.error "TaxJar Server Error: #{e.inspect}" raise e end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/card_data_handling/card_data_handling_error.rb
app/business/card_data_handling/card_data_handling_error.rb
# frozen_string_literal: true # CardDataHandlingError is an error from the front-end when the card data was being handled and failed for some reason. class CardDataHandlingError attr_reader :card_error_code, :error_message # Public: Initialize the error with an error message and card error code. If the card error code is nil the error # is assumed to not be a card error. # # error_message - The error message to log/persist for this error # card_error_code - def initialize(error_message, card_error_code = nil) @error_message = error_message @card_error_code = card_error_code end # Public: Indicates if the error this object represents is an card error or some other error. Card errors are errors # specifically relating to the card that's been presented, where-as other errors may have to do with connectivity # with the payment processor, or any other non-card issue. # # Returns: true if the error is a card error, false if not def is_card_error? !card_error_code.nil? end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/business/card_data_handling/card_data_handling_mode.rb
app/business/card_data_handling/card_data_handling_mode.rb
# frozen_string_literal: true module CardDataHandlingMode TOKENIZE_VIA_STRIPEJS = "stripejs.0" VALID_MODES = { TOKENIZE_VIA_STRIPEJS => StripeChargeProcessor.charge_processor_id }.freeze module_function def is_valid(card_data_handling_mode) return false if card_data_handling_mode.nil? card_data_handling_modes = card_data_handling_mode.split(",") (card_data_handling_modes - VALID_MODES.keys).empty? end def get_card_data_handling_mode(_seller) [ TOKENIZE_VIA_STRIPEJS ].join(",") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/activate_integrations_worker.rb
app/sidekiq/activate_integrations_worker.rb
# frozen_string_literal: true class ActivateIntegrationsWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(purchase_id) purchase = Purchase.find(purchase_id) Integrations::CircleIntegrationService.new.activate(purchase) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/subtitle_file_size_worker.rb
app/sidekiq/subtitle_file_size_worker.rb
# frozen_string_literal: true class SubtitleFileSizeWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(subtitle_file_id) file = SubtitleFile.find_by(id: subtitle_file_id) return if file.nil? file.calculate_size end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/handle_helper_event_worker.rb
app/sidekiq/handle_helper_event_worker.rb
# frozen_string_literal: true class HandleHelperEventWorker include Sidekiq::Job sidekiq_options retry: 3, queue: :default RECENT_PURCHASE_PERIOD = 1.year HELPER_EVENTS = %w[conversation.created] def perform(event, payload) return unless event.in?(HELPER_EVENTS) conversation_id = payload["conversation_id"] email_id = payload["email_id"] email = payload["email_from"] Rails.logger.info("Received Helper event '#{event}' for conversation #{conversation_id}") if email.blank? Rails.logger.warn("Empty email in conversation #{conversation_id}") return end if email == BlockStripeSuspectedFraudulentPaymentsWorker::STRIPE_EMAIL_SENDER && BlockStripeSuspectedFraudulentPaymentsWorker::POSSIBLE_CONVERSATION_SUBJECTS.include?(payload["subject"]) BlockStripeSuspectedFraudulentPaymentsWorker.new.perform(conversation_id, email, payload["body"]) return end user_info = HelperUserInfoService.new(email:, recent_purchase_period: RECENT_PURCHASE_PERIOD).user_info purchase = user_info[:recent_purchase] unblock_email_service = Helper::UnblockEmailService.new(conversation_id:, email_id:, email:) unblock_email_service.recent_blocked_purchase = purchase if purchase.try(:buyer_blocked?) && (purchase.stripe_error_code || purchase.error_code).in?(PurchaseErrorCode::UNBLOCK_BUYER_ERROR_CODES) unblock_email_service.process if unblock_email_service.replied? Rails.logger.info("Replied to Helper conversation #{conversation_id} from UnblockEmailService") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/charge_preorder_worker.rb
app/sidekiq/charge_preorder_worker.rb
# frozen_string_literal: true class ChargePreorderWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default MAX_ATTEMPTS = 4 TIME_BETWEEN_RETRIES = 6.hours PREORDER_AUTO_CANCEL_WAIT_TIME = 2.weeks def perform(preorder_id, attempts = 1) Rails.logger.info "ChargePreorder: attempting to charge #{preorder_id}." preorder = Preorder.find_by(id: preorder_id) purchase = preorder.charge!(purchase_params: { is_automatic_charge: true }) raise "Unable to charge preorder #{preorder_id}: not in chargeable state" if purchase.nil? unless purchase.persisted? Rails.logger.info "ChargePreorder: could not persist purchase for #{preorder_id}, errors: #{purchase.errors.full_messages.join(", ")}." end if purchase.successful? preorder.mark_charge_successful! else if PurchaseErrorCode.is_temporary_network_error?(purchase.error_code) || PurchaseErrorCode.is_temporary_network_error?(purchase.stripe_error_code) # special retry for connection-related issues and stripe 500ing if attempts >= MAX_ATTEMPTS Rails.logger.info "ChargePreorder: Gave up charging Preorder #{preorder_id} after #{MAX_ATTEMPTS} attempts." else ChargePreorderWorker.perform_in(TIME_BETWEEN_RETRIES, preorder.id, attempts.next) end else CustomerLowPriorityMailer.preorder_card_declined(preorder.id).deliver_later(queue: "low") CancelPreorderWorker.perform_in(PREORDER_AUTO_CANCEL_WAIT_TIME, preorder.id) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/rename_product_file_worker.rb
app/sidekiq/rename_product_file_worker.rb
# frozen_string_literal: true class RenameProductFileWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(product_file_id) file = ProductFile.find_by(id: product_file_id) return if file.nil? || file.deleted_from_cdn? file.rename_in_storage end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/fight_disputes_job.rb
app/sidekiq/fight_disputes_job.rb
# frozen_string_literal: true class FightDisputesJob include Sidekiq::Job sidekiq_options retry: 3, queue: :default, lock: :until_executed def perform DisputeEvidence.not_resolved.find_each do |dispute_evidence| next if dispute_evidence.hours_left_to_submit_evidence.positive? FightDisputeJob.perform_async(dispute_evidence.dispute.id) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/schedule_workflow_emails_worker.rb
app/sidekiq/schedule_workflow_emails_worker.rb
# frozen_string_literal: true class ScheduleWorkflowEmailsWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(purchase_id) purchase = Purchase.find(purchase_id) purchase.schedule_all_workflows end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/remove_deleted_files_from_s3_job.rb
app/sidekiq/remove_deleted_files_from_s3_job.rb
# frozen_string_literal: true class RemoveDeletedFilesFromS3Job include Sidekiq::Job sidekiq_options retry: 1, queue: :low # There is no need to try to remove S3 objects from records that were marked as deleted years ago, and whose removal failed: # those will need to be dealt with manually. # Because this job is called every day, it ensures we'll try to remove objects at least once, but not much more than that. MAX_DELETION_AGE_IN_DAYS = 3 # If there's a need to run this job over a larger period of time than just the last 3 days of deleted files, # you can enqueue it like this: # RemoveDeletedFilesFromS3Job.perform_async(60) # => all records marked as deleted up to 60 days ago will be considered def perform(max_deletion_age_in_days = MAX_DELETION_AGE_IN_DAYS) [ ProductFile, ProductFilesArchive, SubtitleFile, StampedPdf, TranscodedVideo, ].each do |model| remove_records_files(model.where(deleted_at: max_deletion_age_in_days.days.ago .. 24.hours.ago)) end end private def remove_records_files(scoped_model) scoped_model.cdn_deletable.find_each do |file| next if file.has_alive_duplicate_files? remove_record_files(file) rescue => e Bugsnag.notify(e) { _1.add_tab(:file, model: file.class.name, id: file.id, url: file.try(:url)) } end end def remove_record_files(file) s3_keys = if file.is_a?(TranscodedVideo) gather_transcoded_video_keys(file) else [file.s3_key] end.compact_blank delete_s3_objects!(s3_keys) unless s3_keys.empty? file.mark_deleted_from_cdn end def s3 @_s3 ||= begin credentials = Aws::Credentials.new(GlobalConfig.get("S3_DELETER_ACCESS_KEY_ID"), GlobalConfig.get("S3_DELETER_SECRET_ACCESS_KEY")) Aws::S3::Resource.new(region: AWS_DEFAULT_REGION, credentials:) end end def bucket @_bucket ||= s3.bucket(S3_BUCKET) end def delete_s3_objects!(s3_keys) s3_keys.each_slice(1_000) do |keys_slice| s3_objects = keys_slice.map { { key: _1 } } s3.client.delete_objects(bucket: S3_BUCKET, delete: { objects: s3_objects, quiet: true }) end end def gather_transcoded_video_keys(file) key = file.transcoded_video_key return [] unless /\/hls\/(index\.m3u8)?$/.match?(key) # sanity check: only deal with keys ending with /hls/ or /hls/index.m3u8 hls_dir = key.delete_suffix("index.m3u8") keys = bucket.objects(prefix: hls_dir).map(&:key) keys.delete_if { _1.delete_prefix(hls_dir).include?("/") } # sanity check: ignore any sub-directories in /hls/ end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/low_balance_fraud_check_worker.rb
app/sidekiq/low_balance_fraud_check_worker.rb
# frozen_string_literal: true class LowBalanceFraudCheckWorker include Sidekiq::Job sidekiq_options retry: 2, queue: :default def perform(purchase_id) creator = Purchase.find(purchase_id).seller creator.check_for_low_balance_and_probate(purchase_id) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/free_trial_expiring_reminder_worker.rb
app/sidekiq/free_trial_expiring_reminder_worker.rb
# frozen_string_literal: true class FreeTrialExpiringReminderWorker include Sidekiq::Job sidekiq_options retry: 3, queue: :default def perform(subscription_id) subscription = Subscription.find(subscription_id) return unless subscription.alive?(include_pending_cancellation: false) && subscription.in_free_trial? && !subscription.is_test_subscription? SentEmailInfo.ensure_mailer_uniqueness("CustomerLowPriorityMailer", "free_trial_expiring_soon", subscription_id) do CustomerLowPriorityMailer.free_trial_expiring_soon(subscription_id).deliver_later(queue: "low") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/save_to_mongo_worker.rb
app/sidekiq/save_to_mongo_worker.rb
# frozen_string_literal: true class SaveToMongoWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :mongo def perform(collection, doc) Mongoer.safe_write(collection, doc) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/delete_product_files_worker.rb
app/sidekiq/delete_product_files_worker.rb
# frozen_string_literal: true class DeleteProductFilesWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(product_id) product = Link.find(product_id) return unless product.deleted? # user undid product deletion return if product.has_successful_sales? product.product_files.each(&:delete!) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/generate_canada_sales_report_job.rb
app/sidekiq/generate_canada_sales_report_job.rb
# frozen_string_literal: true class GenerateCanadaSalesReportJob include Sidekiq::Job def perform(month, year) raise ArgumentError, "Invalid month" unless month.in?(1..12) raise ArgumentError, "Invalid year" unless year.in?(2014..3200) begin temp_file = Tempfile.new temp_file.write(row_headers.to_csv) timeout_seconds = ($redis.get(RedisKey.generate_canada_sales_report_job_max_execution_time_seconds) || 1.hour).to_i WithMaxExecutionTime.timeout_queries(seconds: timeout_seconds) do Purchase.successful .not_fully_refunded .not_chargedback_or_chargedback_reversed .where.not(stripe_transaction_id: nil) .where("purchases.created_at BETWEEN ? AND ?", Date.new(year, month).beginning_of_month.beginning_of_day, Date.new(year, month).end_of_month.end_of_day) .find_each do |purchase| next if purchase.chargedback_not_reversed_or_refunded? country_name, province_name = determine_country_name_and_province_name(purchase) next unless country_name == Compliance::Countries::CAN.common_name provinces = Compliance::Countries::CAN.subdivisions.values.map(&:code) province = if provinces.include?(purchase.state) purchase.state else provinces.include?(purchase.ip_state) ? purchase.ip_state : "Uncategorized" end row = [ purchase.created_at, purchase.external_id, purchase.seller.external_id, purchase.seller.name_or_username, purchase.seller.form_email&.gsub(/.{0,4}@/, '####@'), country_name, province_name, purchase.link.external_id, purchase.link.name, purchase.link.is_recurring_billing? ? "Subscription" : "Product", purchase.link.native_type, purchase.link.is_physical? ? "Physical" : "Digital", purchase.link.is_physical? ? "DTC" : "BS", purchase.purchaser&.external_id, purchase.purchaser&.name_or_username, purchase.email&.gsub(/.{0,4}@/, '####@'), purchase.card_visual&.gsub(/.{0,4}@/, '####@'), purchase.country.presence || purchase.ip_country, province, purchase.price_cents_net_of_refunds, purchase.fee_cents_net_of_refunds, purchase.was_product_recommended? ? (purchase.price_cents_net_of_refunds / 10.0).round : 0, purchase.tax_cents_net_of_refunds, purchase.gumroad_tax_cents_net_of_refunds, purchase.shipping_cents, purchase.total_cents_net_of_refunds ] temp_file.write(row.to_csv) temp_file.flush end end temp_file.rewind s3_filename = "canada-sales-fees-report-#{year}-#{month}-#{SecureRandom.hex(4)}.csv" s3_report_key = "sales-tax/ca-sales-fees-monthly/#{s3_filename}" s3_object = Aws::S3::Resource.new.bucket(REPORTING_S3_BUCKET).object(s3_report_key) s3_object.upload_file(temp_file) s3_signed_url = s3_object.presigned_url(:get, expires_in: 1.week.to_i).to_s SlackMessageWorker.perform_async("payments", "Canada Sales Fees Reporting", "Canada #{year}-#{month} sales fees report is ready - #{s3_signed_url}", "green") ensure temp_file.close end end private def row_headers [ "Sale time", "Sale ID", "Seller ID", "Seller Name", "Seller Email", "Seller Country", "Seller Province", "Product ID", "Product Name", "Product / Subscription", "Product Type", "Physical/Digital Product", "Direct-To-Customer/Buy-Sell Product", "Buyer ID", "Buyer Name", "Buyer Email", "Buyer Card", "Buyer Country", "Buyer State", "Price", "Total Gumroad Fee", "Gumroad Discover Fee", "Creator Sales Tax", "Gumroad Sales Tax", "Shipping", "Total" ] end def determine_country_name_and_province_name(purchase) user_compliance_info = purchase.seller.user_compliance_infos.where("created_at < ?", purchase.created_at).where.not("country IS NULL AND business_country IS NULL").last rescue nil country_name = user_compliance_info&.legal_entity_country.presence province_code = user_compliance_info&.legal_entity_state.presence unless country_name.present? country_name = purchase.seller&.country province_code = purchase.seller&.state end unless country_name.present? country_name = GeoIp.lookup(purchase.seller&.account_created_ip)&.country_name province_code = GeoIp.lookup(purchase.seller&.account_created_ip)&.region_name end country_name = Compliance::Countries.find_by_name(country_name)&.common_name || "Uncategorized" province_name = Compliance::Countries::CAN.subdivisions.values.find { |subdivision| subdivision.code == province_code }&.name || "Uncategorized" [country_name, province_name] end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/recurring_charge_worker.rb
app/sidekiq/recurring_charge_worker.rb
# frozen_string_literal: true class RecurringChargeWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default, lock: :until_executed def perform(subscription_id, ignore_consecutive_failures = false, _deprecated = nil) ActiveRecord::Base.connection.stick_to_primary! SuoSemaphore.recurring_charge(subscription_id).lock do Rails.logger.info("Processing RecurringChargeWorker#perform(#{subscription_id})") subscription = Subscription.find(subscription_id) return if subscription.link.user.suspended? return unless subscription.alive?(include_pending_cancellation: false) return if subscription.is_test_subscription || subscription.current_subscription_price_cents == 0 return if subscription.charges_completed? return if subscription.in_free_trial? last_successful_purchase = subscription.purchases.successful.last return if last_successful_purchase && (last_successful_purchase.created_at + subscription.period) > Time.current last_purchase = subscription.purchases.last return if last_purchase.in_progress? && last_purchase.sync_status_with_charge_processor return if subscription.has_a_charge_in_progress? if ignore_consecutive_failures && last_purchase.failed? if subscription.seconds_overdue_for_charge > Subscription::ALLOWED_TIME_BEFORE_FAIL_AND_UNSUBSCRIBE Rails.logger.info("RecurringChargeWorker#perform(#{subscription_id}): marking subscription failed") subscription.unsubscribe_and_fail! end return end # Check if the user has initiated any plan changes that must be applied at # the end of the current billing period. If so, apply the most recent change # before charging. plan_changes = subscription.subscription_plan_changes.alive latest_applicable_plan_change = subscription.latest_applicable_plan_change override_params = {} if latest_applicable_plan_change.present? same_tier = latest_applicable_plan_change.tier == subscription.tier new_price = subscription.link.prices.is_buy.alive.find_by(recurrence: latest_applicable_plan_change.recurrence) || subscription.link.prices.is_buy.find_by(recurrence: latest_applicable_plan_change.recurrence) # use live price if exists, else deleted price begin subscription.update_current_plan!( new_variants: [latest_applicable_plan_change.tier], new_price:, new_quantity: latest_applicable_plan_change.quantity, perceived_price_cents: latest_applicable_plan_change.perceived_price_cents, is_applying_plan_change: true, ) latest_applicable_plan_change.update!(applied: true) subscription.update!(flat_fee_applicable: true) unless subscription.flat_fee_applicable? rescue Subscription::UpdateFailed => e Rails.logger.info("RecurringChargeWorker#perform(#{subscription_id}) failed: #{e.class} (#{e.message})") return end subscription.reload.original_purchase.schedule_workflows_for_variants unless same_tier plan_changes.map(&:mark_deleted!) override_params[:is_upgrade_purchase] = true # avoid double charged error subscription.reload UpdateIntegrationsOnTierChangeWorker.perform_async(subscription.id) unless same_tier end subscription.charge!(override_params:) Rails.logger.info("Completed processing RecurringChargeWorker#perform(#{subscription_id})") end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/find_expired_subscriptions_to_set_as_deactivated_worker.rb
app/sidekiq/find_expired_subscriptions_to_set_as_deactivated_worker.rb
# frozen_string_literal: true class FindExpiredSubscriptionsToSetAsDeactivatedWorker include Sidekiq::Job sidekiq_options retry: 0, queue: :default def perform now = Time.current relations = [ Subscription.where("cancelled_at < ? and deactivated_at is null", now).not_is_test_subscription.select(:id), Subscription.where("failed_at < ? and deactivated_at is null", now).not_is_test_subscription.select(:id), Subscription.where("ended_at < ? and deactivated_at is null", now).not_is_test_subscription.select(:id), ] relations.each do |relation| relation.find_each do |subscription| SetSubscriptionAsDeactivatedWorker.perform_async(subscription.id) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/send_payment_reminder_worker.rb
app/sidekiq/send_payment_reminder_worker.rb
# frozen_string_literal: true class SendPaymentReminderWorker include Sidekiq::Job sidekiq_options retry: 1, queue: :default def perform User.payment_reminder_risk_state.announcement_notification_enabled .where(payment_address: nil).holding_balance_more_than(1000) .find_each do |user| ContactingCreatorMailer.remind(user.id).deliver_later(queue: "low") if user.active_bank_account.nil? && user.stripe_connect_account.blank? && !user.has_paypal_account_connected? && user.form_email.present? end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/delete_old_unused_events_worker.rb
app/sidekiq/delete_old_unused_events_worker.rb
# frozen_string_literal: true class DeleteOldUnusedEventsWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :low DELETION_BATCH_SIZE = 100 # Deletes non-permitted events within the default time window of: # (2 months and 2 days ago) .. (2 months ago) # # Params: # - `to` allows us to keep the most recent events, as they are used by the admin "Show GUIDs" feature. # - `from` allows this job to only review recent events. # Without it, we would have to scan the same events every day all the way up to `to`. # Because this job runs every day, we can only review 2 days worth of events and know we reviewed all the ones we should. def perform(to: 2.months.ago, from: to - 2.days) start_id = Event.where("created_at >= ?", from).order(:created_at).first&.id finish_id = Event.where("created_at <= ?", to).order(created_at: :desc).first&.id return if start_id.nil? || finish_id.nil? Event.select(:id, :event_name).find_in_batches(start: start_id, finish: finish_id, batch_size: DELETION_BATCH_SIZE) do |events| ReplicaLagWatcher.watch data = events.to_h { |event| [event.id, event.event_name] } ids_to_delete = data.filter { |_, name| Event::PERMITTED_NAMES.exclude?(name) }.keys Event.where(id: ids_to_delete).delete_all unless ids_to_delete.empty? end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/log_resend_event_job.rb
app/sidekiq/log_resend_event_job.rb
# frozen_string_literal: true class LogResendEventJob include Sidekiq::Job sidekiq_options retry: 5, queue: :mongo def perform(event_json) resend_event_info = ResendEventInfo.new(event_json) return if resend_event_info.invalid? return unless resend_event_info.type.in?([ResendEventInfo::EVENT_OPENED, ResendEventInfo::EVENT_CLICKED]) case resend_event_info.type when ResendEventInfo::EVENT_OPENED EmailEvent.log_open_event(resend_event_info.email, resend_event_info.created_at) when ResendEventInfo::EVENT_CLICKED EmailEvent.log_click_event(resend_event_info.email, resend_event_info.created_at) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/recalculate_recent_wishlist_follower_count_job.rb
app/sidekiq/recalculate_recent_wishlist_follower_count_job.rb
# frozen_string_literal: true class RecalculateRecentWishlistFollowerCountJob include Sidekiq::Job def perform Wishlist.find_in_batches do |batch| follower_counts = WishlistFollower.alive .where(wishlist_id: batch.map(&:id)) .where("created_at > ?", 30.days.ago) .group(:wishlist_id) .count batch.each do |wishlist| wishlist.update!(recent_follower_count: follower_counts[wishlist.id] || 0) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/generate_financial_reports_for_previous_quarter_job.rb
app/sidekiq/generate_financial_reports_for_previous_quarter_job.rb
# frozen_string_literal: true class GenerateFinancialReportsForPreviousQuarterJob include Sidekiq::Job sidekiq_options retry: 1, queue: :default, lock: :until_executed, on_conflict: :replace def perform return unless Rails.env.production? quarter_start_date = Date.current.prev_quarter.beginning_of_quarter quarter_end_date = Date.current.prev_quarter.end_of_quarter quarter = ((quarter_start_date.month - 1) / 3) + 1 CreateVatReportJob.perform_async(quarter, quarter_start_date.year) [Compliance::Countries::GBR, Compliance::Countries::AUS, Compliance::Countries::SGP, Compliance::Countries::NOR].each do |country| GenerateSalesReportJob.perform_async(country.alpha2, quarter_start_date.to_s, quarter_end_date.to_s, GenerateSalesReportJob::ALL_SALES) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/generate_username_job.rb
app/sidekiq/generate_username_job.rb
# frozen_string_literal: true class GenerateUsernameJob include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(user_id) user = User.find(user_id) return if user.read_attribute(:username).present? username = UsernameGeneratorService.new(user).username return if username.nil? user.with_lock do break if user.read_attribute(:username).present? user.update!(username:) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/transfer_dropbox_file_to_s3_worker.rb
app/sidekiq/transfer_dropbox_file_to_s3_worker.rb
# frozen_string_literal: true class TransferDropboxFileToS3Worker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(dropbox_file_id) dropbox_file = DropboxFile.find(dropbox_file_id) dropbox_file.transfer_to_s3 end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/handle_grmc_callback_job.rb
app/sidekiq/handle_grmc_callback_job.rb
# frozen_string_literal: true class HandleGrmcCallbackJob include Sidekiq::Job sidekiq_options retry: 2, queue: :default def perform(notification) ActiveRecord::Base.connection.stick_to_primary! transcoded_video_from_job = TranscodedVideo.processing.find_by(job_id: notification["job_id"]) return if transcoded_video_from_job.nil? TranscodedVideo.processing.where(original_video_key: transcoded_video_from_job.original_video_key).find_each do |transcoded_video| if notification["status"] == "success" transcoded_video.streamable.update!(is_transcoded_for_hls: true) transcoded_video.update!(transcoded_video_key: transcoded_video.transcoded_video_key + "index.m3u8") transcoded_video.mark_completed else transcoded_video.mark_error next if transcoded_video.deleted? TranscodeVideoForStreamingWorker.perform_async( transcoded_video.streamable_id, transcoded_video.streamable_type, TranscodeVideoForStreamingWorker::MEDIACONVERT, true ) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/publish_scheduled_post_job.rb
app/sidekiq/publish_scheduled_post_job.rb
# frozen_string_literal: true class PublishScheduledPostJob include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(post_id, version) post = Installment.find(post_id) post.with_lock do return unless post.alive? # post may have been deleted return if post.published? # no need to try to publish it again or send emails rule = post.installment_rule return unless version == rule.version # the version may have changed (e.g. the post was rescheduled) return unless rule.alive? # the rule may have been deleted (happens when the post is published) post.publish! if post.can_be_blasted? blast = PostEmailBlast.create!(post:, requested_at: rule.to_be_published_at) SendPostBlastEmailsJob.perform_async(blast.id) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/delete_product_files_archives_worker.rb
app/sidekiq/delete_product_files_archives_worker.rb
# frozen_string_literal: true class DeleteProductFilesArchivesWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(product_id = nil, variant_id = nil) return if product_id.nil? && variant_id.nil? variant = BaseVariant.find(variant_id) if variant_id.present? product = product_id.present? ? Link.find(product_id) : Link.find(variant.variant_category.link_id) if variant_id.present? return unless variant.deleted? variant.product_files_archives.alive.each(&:mark_deleted!) else return unless product.deleted? product.product_files_archives.alive.each(&:mark_deleted!) product.alive_variants.each { _1.product_files_archives.alive.each(&:mark_deleted!) } end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/score_product_worker.rb
app/sidekiq/score_product_worker.rb
# frozen_string_literal: true class ScoreProductWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :low def perform(product_id) return unless Rails.env.production? sqs = Aws::SQS::Client.new queue_url = sqs.get_queue_url(queue_name: "risk_queue").queue_url sqs.send_message(queue_url:, message_body: { "type" => "product", "id" => product_id }.to_s) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/expiring_credit_card_message_worker.rb
app/sidekiq/expiring_credit_card_message_worker.rb
# frozen_string_literal: true class ExpiringCreditCardMessageWorker include Sidekiq::Job sidekiq_options retry: 1, queue: :default # Selects all the credit cards that expire next month and notifies the customers to update them. # There are 2 types of emails that we send to users: # - emails that specify the membership assigned # - a general email that mentions the last purchase def perform cutoff_date = Date.today.at_beginning_of_month.next_month CreditCard.includes(:users).where(expiry_month: cutoff_date.month, expiry_year: cutoff_date.year).find_each do |credit_card| credit_card.users.each do |user| next unless user.form_email.present? user.subscriptions.active_without_pending_cancel.where(credit_card_id: credit_card.id).each do |subscription| CustomerLowPriorityMailer.credit_card_expiring_membership(subscription.id).deliver_later(queue: "low") end end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/send_purchase_receipt_job.rb
app/sidekiq/send_purchase_receipt_job.rb
# frozen_string_literal: true # Generates custom PDFs and sends a receipt # We want to make sure the receipt is sent after all the PDFs have been stamped # Exception: a receipt is not sent for bundle product pruchases, as they are dummy purchases # If there are PDFs that need to be stamped, the caller must enqueue this job using the "default" queue # class SendPurchaseReceiptJob include Sidekiq::Job sidekiq_options queue: :default, retry: 5, lock: :until_executed def perform(purchase_id) purchase = Purchase.find(purchase_id) PdfStampingService.stamp_for_purchase!(purchase) if purchase.link.has_stampable_pdfs? return if purchase.is_bundle_product_purchase? CustomerMailer.receipt(purchase_id).deliver_now end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/renew_custom_domain_ssl_certificates.rb
app/sidekiq/renew_custom_domain_ssl_certificates.rb
# frozen_string_literal: true class RenewCustomDomainSslCertificates include Sidekiq::Job sidekiq_options retry: 0, queue: :low def perform if SslCertificates::Renew.supported_environment? SslCertificates::Renew.new.process end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/update_sales_related_products_infos_job.rb
app/sidekiq/update_sales_related_products_infos_job.rb
# frozen_string_literal: true class UpdateSalesRelatedProductsInfosJob include Sidekiq::Job sidekiq_options retry: 3, queue: :low def perform(purchase_id, increment = true) return if Feature.inactive?(:update_sales_related_products_infos) purchase = Purchase.find(purchase_id) product_id = purchase.link_id related_product_ids = Purchase .successful_or_preorder_authorization_successful_and_not_refunded_or_chargedback .where(email: purchase.email) .where.not(link_id: product_id) .distinct .pluck(:link_id) return if related_product_ids.empty? SalesRelatedProductsInfo.update_sales_counts(product_id:, related_product_ids:, increment:) base_delay = $redis.get(RedisKey.update_cached_srpis_job_delay_hours)&.to_i || 72 args = [product_id, *related_product_ids].map { [_1] } ats = args.map { base_delay.hours.from_now.to_i + rand(24.hours.to_i) } Sidekiq::Client.push_bulk( "class" => UpdateCachedSalesRelatedProductsInfosJob, "args" => args, "queue" => "low", "at" => ats, ) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/update_taxonomy_stats_job.rb
app/sidekiq/update_taxonomy_stats_job.rb
# frozen_string_literal: true class UpdateTaxonomyStatsJob include Sidekiq::Job sidekiq_options retry: 3, queue: :low def perform taxonomies = Taxonomy.roots taxonomies.each do |taxonomy| descendant_ids = taxonomy.descendant_ids stat = TaxonomyStat.find_or_create_by!(taxonomy:) shared_params = { taxonomy: [taxonomy.id] + descendant_ids, state: "successful", size: 0, exclude_unreversed_chargedback: true, exclude_refunded: true, exclude_bundle_product_purchases: true, track_total_hits: true, } search_result = PurchaseSearchService.search( **shared_params, aggs: { creators_count: { cardinality: { field: "seller_id" } }, products_count: { cardinality: { field: "product_id" } }, } ).response stat.sales_count = search_result["hits"]["total"]["value"] stat.creators_count = search_result.aggregations.creators_count.value stat.products_count = search_result.aggregations.products_count.value search_result = PurchaseSearchService.search( **shared_params, created_on_or_after: 30.days.ago, ).response stat.recent_sales_count = search_result["hits"]["total"]["value"] stat.save! end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/delete_product_rich_content_worker.rb
app/sidekiq/delete_product_rich_content_worker.rb
# frozen_string_literal: true class DeleteProductRichContentWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(product_id, variant_id = nil) product = Link.find(product_id) if variant_id.present? variant = BaseVariant.find(variant_id) delete_rich_content(product, variant:) else delete_rich_content(product) product.variants.find_each do |product_variant| delete_rich_content(product, variant: product_variant) end end end private def delete_rich_content(product, variant: nil) product_or_variant = variant.presence || product return unless product_or_variant.alive_rich_contents.exists? && product_or_variant.deleted? product_or_variant.alive_rich_contents.find_each(&:mark_deleted!) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/find_subscriptions_with_missing_charge_worker.rb
app/sidekiq/find_subscriptions_with_missing_charge_worker.rb
# frozen_string_literal: true class FindSubscriptionsWithMissingChargeWorker include Sidekiq::Job sidekiq_options retry: 0, queue: :low BATCHES_SCHEDULE_MARGIN_IN_MINUTES = 20 def perform(batch_number = nil) if batch_number.nil? 10.times { |i| self.class.perform_in(i * BATCHES_SCHEDULE_MARGIN_IN_MINUTES * 60, i) } return end susbcriptions = Subscription .not_is_test_subscription .where(deactivated_at: nil) .where("subscriptions.id % 10 = ?", batch_number) .includes(link: :user) susbcriptions.find_in_batches do |subscriptions| subscriptions.reject! { |subscription| subscription.link.user.suspended? || subscription.has_a_charge_in_progress? } next if subscriptions.empty? subscriptions = Subscription.where(id: subscriptions.map(&:id)).includes(:original_purchase).to_a subscriptions.reject! { |subscription| subscription.current_subscription_price_cents == 0 } next if subscriptions.empty? subscriptions = Subscription.includes(:last_successful_purchase, last_payment_option: :price).where(id: subscriptions.map(&:id)).to_a subscriptions.reject! do |subscription| subscription.last_successful_purchase.blank? || subscription.seconds_overdue_for_charge < 75.minutes end subscriptions.each do |subscription| Rails.logger.info("Found potentially missing charge for subscription #{subscription.id}") RecurringChargeWorker.perform_async(subscription.id, true) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/send_last_post_job.rb
app/sidekiq/send_last_post_job.rb
# frozen_string_literal: true class SendLastPostJob include Sidekiq::Job sidekiq_options retry: 5, queue: :low def perform(purchase_id) purchase = Purchase.find(purchase_id) subscription = purchase.subscription posts = Installment.emailable_posts_for_purchase(purchase:).order(published_at: :desc) post = posts.find { _1.purchase_passes_filters(purchase) } return if post.nil? SentPostEmail.ensure_uniqueness(post:, email: purchase.email) do recipient = { email: purchase.email, purchase:, subscription: } recipient[:url_redirect] = post.generate_url_redirect_for_subscription(subscription) if post.has_files? PostEmailApi.process(post:, recipients: [recipient]) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/deactivate_integrations_worker.rb
app/sidekiq/deactivate_integrations_worker.rb
# frozen_string_literal: true class DeactivateIntegrationsWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(purchase_id) purchase = Purchase.find(purchase_id) purchases_to_process(purchase).each { deactivate_integrations(_1) } end private def purchases_to_process(purchase) purchases = [purchase] if purchase.subscription.present? subscription_purchases = purchase.subscription.purchases .joins(:live_purchase_integrations) .distinct purchases.concat(subscription_purchases) end purchases.uniq(&:id) end def deactivate_integrations(purchase) [Integrations::CircleIntegrationService, Integrations::DiscordIntegrationService].each do |integration_service| integration_service.new.deactivate(purchase) rescue Discordrb::Errors::NoPermission => e Rails.logger.warn("DeactivateIntegrationsWorker: Permissions error for #{purchase.id} - #{e.class} => #{e.message}") next end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/annual_tax_summary_export_worker.rb
app/sidekiq/annual_tax_summary_export_worker.rb
# frozen_string_literal: true class AnnualTaxSummaryExportWorker include Sidekiq::Job sidekiq_options queue: :low def perform(year, start = nil, finish = nil) csv_url = nil WithMaxExecutionTime.timeout_queries(seconds: 4.hour) do csv_url = Exports::TaxSummary::Annual.new(year:, start:, finish:).perform end return unless csv_url AccountingMailer.payable_report(csv_url, year).deliver_now end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/seller_update_worker.rb
app/sidekiq/seller_update_worker.rb
# frozen_string_literal: true class SellerUpdateWorker include Sidekiq::Job sidekiq_options retry: 0, queue: :default def perform(user_id) user = User.find(user_id) ContactingCreatorMailer.seller_update(user.id).deliver_later(queue: "critical") if user.form_email && user.announcement_notification_enabled && (user.last_weeks_sales > 0 || user.last_weeks_followers > 0) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/update_seller_refund_eligibility_job.rb
app/sidekiq/update_seller_refund_eligibility_job.rb
# frozen_string_literal: true class UpdateSellerRefundEligibilityJob include Sidekiq::Job sidekiq_options retry: 2, queue: :default def perform(user_id) user = User.find(user_id) unpaid_balance_cents = user.unpaid_balance_cents if unpaid_balance_cents > 0 && user.refunds_disabled? user.enable_refunds! elsif unpaid_balance_cents < -10000 && !user.refunds_disabled? user.disable_refunds! end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/update_purchase_email_to_match_account_worker.rb
app/sidekiq/update_purchase_email_to_match_account_worker.rb
# frozen_string_literal: true class UpdatePurchaseEmailToMatchAccountWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(user_id) user = User.find(user_id) user.purchases.find_each do |purchase| purchase.update!(email: user.email) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/utm_link_sale_attribution_job.rb
app/sidekiq/utm_link_sale_attribution_job.rb
# frozen_string_literal: true class UtmLinkSaleAttributionJob include Sidekiq::Job ATTRIBUTION_WINDOW = 7.days sidekiq_options queue: :low, lock: :until_executed, retry: 3 def perform(order_id, browser_guid) purchases_by_seller = Order.find(order_id).purchases.successful.group_by(&:seller_id) # Fetch only the latest visit per UtmLink latest_visits_query = <<~SQL.squish SELECT utm_link_id, MAX(created_at) AS latest_visit_at FROM utm_link_visits WHERE browser_guid = '#{ActiveRecord::Base.connection.quote_string(browser_guid)}' AND created_at >= '#{ATTRIBUTION_WINDOW.ago.beginning_of_day.strftime("%Y-%m-%d %H:%M:%S")}' GROUP BY utm_link_id SQL visits = UtmLinkVisit .includes(:utm_link) .joins(<<~SQL.squish) INNER JOIN (#{latest_visits_query}) AS latest_visits ON utm_link_visits.utm_link_id = latest_visits.utm_link_id AND utm_link_visits.created_at = latest_visits.latest_visit_at SQL .where(browser_guid:) .where("utm_link_visits.created_at >= ?", ATTRIBUTION_WINDOW.ago.beginning_of_day) .order(created_at: :desc) purchase_attribution_map = {} visits.find_each do |visit| utm_link = visit.utm_link next unless Feature.active?(:utm_links, utm_link.seller) qualified_purchases = purchases_by_seller[utm_link.seller_id] next if qualified_purchases.blank? if utm_link.target_product_page? qualified_purchases.select! { _1.link_id == utm_link.target_resource_id } end # Attribute only one visit (the most recent among all applicable links) per purchase qualified_purchases.each { purchase_attribution_map[_1.id] ||= { visit:, purchase: _1 } } end purchase_attribution_map.each do |purchase_id, info| purchase = info.fetch(:purchase) visit = info.fetch(:visit) utm_link = visit.utm_link visit.update!(country_code: Compliance::Countries.find_by_name(purchase.country)&.alpha2) if visit.country_code.blank? && purchase.country.present? utm_link.utm_link_driven_sales.create!(utm_link_visit: visit, purchase:) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/update_large_sellers_sales_count_job.rb
app/sidekiq/update_large_sellers_sales_count_job.rb
# frozen_string_literal: true class UpdateLargeSellersSalesCountJob include Sidekiq::Job sidekiq_options retry: 1, queue: :low def perform LargeSeller.find_each(batch_size: 100) do |large_seller| next unless large_seller.user current_sales_count = large_seller.user.sales.count if current_sales_count != large_seller.sales_count large_seller.update!(sales_count: current_sales_count) end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/generate_fees_by_creator_location_report_job.rb
app/sidekiq/generate_fees_by_creator_location_report_job.rb
# frozen_string_literal: true class GenerateFeesByCreatorLocationReportJob include Sidekiq::Job sidekiq_options retry: 1, queue: :default, lock: :until_executed def perform(month, year) raise ArgumentError, "Invalid month" unless month.in?(1..12) raise ArgumentError, "Invalid year" unless year.in?(2014..3200) state_data = {} country_data = {} timeout_seconds = ($redis.get(RedisKey.generate_fees_by_creator_location_job_max_execution_time_seconds) || 1.hour).to_i WithMaxExecutionTime.timeout_queries(seconds: timeout_seconds) do Purchase.successful .not_fully_refunded .not_chargedback_or_chargedback_reversed .where.not(stripe_transaction_id: nil) .where("purchases.created_at BETWEEN ? AND ?", Date.new(year, month).beginning_of_month.beginning_of_day, Date.new(year, month).end_of_month.end_of_day).find_each do |purchase| GC.start if purchase.id % 10000 == 0 next if purchase.chargedback_not_reversed_or_refunded? fee_cents = purchase.fee_cents_net_of_refunds country_name, state_name = determine_country_name_and_state_name(purchase) country_data[country_name] ||= 0 country_data[country_name] += fee_cents if country_name == "United States" state_data[state_name] ||= 0 state_data[state_name] += fee_cents end end end row_headers = ["Month", "Creator Country", "Creator State", "Gumroad Fees"] begin temp_file = Tempfile.new temp_file.write(row_headers.to_csv) state_data.each do |state_name, state_fee_cents_total| temp_file.write([Date.new(year, month).strftime("%B %Y"), "United States", state_name, state_fee_cents_total].to_csv) end country_data.each do |country_name, country_fee_cents_total| temp_file.write([Date.new(year, month).strftime("%B %Y"), country_name, "", country_fee_cents_total].to_csv) end temp_file.flush temp_file.rewind s3_filename = "fees-by-creator-location-report-#{year}-#{month}-#{SecureRandom.hex(4)}.csv" s3_report_key = "sales-tax/fees-by-creator-location-monthly/#{s3_filename}" s3_object = Aws::S3::Resource.new.bucket(REPORTING_S3_BUCKET).object(s3_report_key) s3_object.upload_file(temp_file) s3_signed_url = s3_object.presigned_url(:get, expires_in: 1.week.to_i).to_s SlackMessageWorker.perform_async("payments", "Fee Reporting", "#{year}-#{month} fee by creator location report is ready - #{s3_signed_url}", "green") ensure temp_file.close end end def determine_country_name_and_state_name(purchase) user_compliance_info = purchase.seller.user_compliance_infos.where("created_at < ?", purchase.created_at).where.not("country IS NULL AND business_country IS NULL").last rescue nil country_name = user_compliance_info&.legal_entity_country.presence state_code = user_compliance_info&.legal_entity_state.presence unless country_name.present? country_name = purchase.seller&.country state_code = purchase.seller&.state end unless country_name.present? country_name = GeoIp.lookup(purchase.seller&.account_created_ip)&.country_name state_code = GeoIp.lookup(purchase.seller&.account_created_ip)&.region_name end country_name = Compliance::Countries.find_by_name(country_name)&.common_name || "Uncategorized" state_name = Compliance::Countries::USA.subdivisions[state_code]&.name || "Uncategorized" [country_name, state_name] end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/send_rental_expires_soon_email_worker.rb
app/sidekiq/send_rental_expires_soon_email_worker.rb
# frozen_string_literal: true class SendRentalExpiresSoonEmailWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(purchase_id, time_till_rental_expiration_in_seconds) purchase = Purchase.find(purchase_id) url_redirect = purchase.url_redirect return if !url_redirect.is_rental || url_redirect.rental_first_viewed_at.present? || purchase.chargedback_not_reversed_or_refunded? CustomerLowPriorityMailer.rental_expiring_soon(purchase.id, time_till_rental_expiration_in_seconds).deliver_later(queue: "low") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/charge_declined_reminder_worker.rb
app/sidekiq/charge_declined_reminder_worker.rb
# frozen_string_literal: true class ChargeDeclinedReminderWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(subscription_id) subscription = Subscription.find(subscription_id) return if !subscription.alive?(include_pending_cancellation: false) || subscription.is_test_subscription || !subscription.overdue_for_charge? CustomerLowPriorityMailer.subscription_card_declined_warning(subscription_id).deliver_later(queue: "low") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/recover_aus_backtaxes_from_stripe_accounts_job.rb
app/sidekiq/recover_aus_backtaxes_from_stripe_accounts_job.rb
# frozen_string_literal: true class RecoverAusBacktaxesFromStripeAccountsJob include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform BacktaxAgreement .not_collected .where(jurisdiction: BacktaxAgreement::Jurisdictions::AUSTRALIA) .pluck(:user_id) .uniq .each { |creator_id| RecoverAusBacktaxFromStripeAccountJob.perform_async(creator_id) } end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/delete_wishlist_products_job.rb
app/sidekiq/delete_wishlist_products_job.rb
# frozen_string_literal: true class DeleteWishlistProductsJob include Sidekiq::Job sidekiq_options queue: :low def perform(product_id) product = Link.find(product_id) return unless product.deleted? # user undid product deletion product.wishlist_products.alive.find_each(&:mark_deleted!) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/custom_domains_verification_worker.rb
app/sidekiq/custom_domains_verification_worker.rb
# frozen_string_literal: true class CustomDomainsVerificationWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :low MAX_DURATION_TO_VERIFY_ALL_DOMAINS = 1.hour def perform CustomDomain.alive.find_each.with_index do |custom_domain, index| next if custom_domain.exceeding_max_failed_verification_attempts? CustomDomainVerificationWorker.perform_in((index % MAX_DURATION_TO_VERIFY_ALL_DOMAINS).seconds, custom_domain.id) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/process_purchase_early_fraud_warning_job.rb
app/sidekiq/process_purchase_early_fraud_warning_job.rb
# frozen_string_literal: true # Before removing this file, make sure there are no more enqueued jobs in production using the class name ProcessPurchaseEarlyFraudWarningJob = ProcessEarlyFraudWarningJob
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/stripe_transfer_gumroads_available_balances_to_gumroads_bank_account_worker.rb
app/sidekiq/stripe_transfer_gumroads_available_balances_to_gumroads_bank_account_worker.rb
# frozen_string_literal: true class StripeTransferGumroadsAvailableBalancesToGumroadsBankAccountWorker include Sidekiq::Job sidekiq_options retry: 0, queue: :default BALANCE_BUFFER_CENTS = 1_000_000_00 private_constant :BALANCE_BUFFER_CENTS def perform return unless Rails.env.production? || Rails.env.staging? return if Feature.active?(:skip_transfer_from_stripe_to_bank) next_payout_end_date = User::PayoutSchedule.next_scheduled_payout_end_date held_amount_cents = PayoutEstimates.estimate_held_amount_cents(next_payout_end_date, PayoutProcessorType::STRIPE) buffer_cents = BALANCE_BUFFER_CENTS + held_amount_cents[HolderOfFunds::GUMROAD] StripeTransferExternallyToGumroad.transfer_all_available_balances(buffer_cents:) end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/send_reminders_for_outstanding_user_compliance_info_requests_worker.rb
app/sidekiq/send_reminders_for_outstanding_user_compliance_info_requests_worker.rb
# frozen_string_literal: true class SendRemindersForOutstandingUserComplianceInfoRequestsWorker include Sidekiq::Job sidekiq_options retry: 0, queue: :default TIME_UNTIL_REQUEST_NEEDS_REMINDER = 2.days MAX_NUMBER_OF_REMINDERS = 2 private_constant :MAX_NUMBER_OF_REMINDERS, :TIME_UNTIL_REQUEST_NEEDS_REMINDER def perform user_ids = UserComplianceInfoRequest.requested.distinct.pluck(:user_id) user_ids.each do |user_id| user = User.find(user_id) return unless user.account_active? requests = user.user_compliance_info_requests if user.stripe_account&.country == Compliance::Countries::SGP.alpha2 sg_verification_request = requests.requested.where(field_needed: UserComplianceInfoFields::Individual::STRIPE_ENHANCED_IDENTITY_VERIFICATION).last # Stripe account is permanently closed if not updated in 120 days, so do not send reminders after that. # Ref: https://stripe.com/en-in/guides/sg-payment-services-act-2019#account-closure sg_verification_deadline = user.stripe_account.created_at + 120.days if sg_verification_request.present? && Time.current < sg_verification_deadline && (sg_verification_request.sg_verification_reminder_sent_at.nil? || sg_verification_request.sg_verification_reminder_sent_at < 7.days.ago) ContactingCreatorMailer.singapore_identity_verification_reminder(user_id, sg_verification_deadline).deliver_later(queue: "default") sg_verification_request.sg_verification_reminder_sent_at = Time.current sg_verification_request.save! end end oldest_request = requests.first should_remind = (oldest_request.last_email_sent_at.nil? || oldest_request.last_email_sent_at < TIME_UNTIL_REQUEST_NEEDS_REMINDER.ago) && oldest_request.emails_sent_at.count < MAX_NUMBER_OF_REMINDERS next unless should_remind ContactingCreatorMailer.payouts_may_be_blocked(user_id).deliver_later(queue: "critical") email_sent_at = Time.current requests.each { |request| request.record_email_sent!(email_sent_at) } end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/delete_stripe_apple_pay_domain_worker.rb
app/sidekiq/delete_stripe_apple_pay_domain_worker.rb
# frozen_string_literal: true class DeleteStripeApplePayDomainWorker include Sidekiq::Job sidekiq_options retry: 3, queue: :low def perform(user_id, domain) record = StripeApplePayDomain.find_by(user_id:, domain:) return unless record response = Stripe::ApplePayDomain.delete(record.stripe_id) record.destroy if response.deleted rescue Stripe::InvalidRequestError record.destroy end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/refund_purchase_worker.rb
app/sidekiq/refund_purchase_worker.rb
# frozen_string_literal: true class RefundPurchaseWorker include Sidekiq::Job sidekiq_options retry: 5, queue: :default def perform(purchase_id, admin_user_id, reason = nil) purchase = Purchase.find(purchase_id) if reason == Refund::FRAUD purchase.refund_for_fraud_and_block_buyer!(admin_user_id) else purchase.refund_and_save!(admin_user_id) end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/sidekiq/update_user_balance_stats_cache_worker.rb
app/sidekiq/update_user_balance_stats_cache_worker.rb
# frozen_string_literal: true class UpdateUserBalanceStatsCacheWorker include Sidekiq::Job sidekiq_options retry: 1, queue: :low, lock: :until_executed def perform(user_id) user = User.find(user_id) WithMaxExecutionTime.timeout_queries(seconds: 1.hour) do UserBalanceStatsService.new(user:).write_cache end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false