Given the following method
def change_plan_to(plan_id)
new_plan = Plan.find plan_id
stripe_customer = Stripe::Customer.retrieve(stripe_customer_token)
stripe_customer.update_subscription(plan: new_plan.slug)
self.plan = new_plan
self.active = true
save
rescue Stripe::InvalidRequestError => e
logger.error "[STRIPE] #{ e }"
errors.add :base, "Unable to change your plan!"
false
end
Specifically line #4-6. I want 4 and 5 to happen only if 4 is successful but Stripe doesn't return the ability to wrap that in a if. If it errors it just throws Stripe::InvalidRequestError.
What's the best way to handle this? Fire & forget and allow Stripe webhook callbacks to manage expiring active state as needed?
The other scenario is that all the code will halt after line 4 if it doesn't pass. Is this how rescue works?
Yes thats the way rescue work,
So better you execute these statements which is dependent on line 4 in webhook callbacks that stripe sends to you. Because that ensures subscription change.
Related
I have a custom validator that checks if the user has entered the correct SMS code. When the user enters the wrong code I need to log the failed attempt and limit their retries to 3 per code.
I have created the following validator that works however the field is not being incremented.
def token_match
if token != User.find(user_id).verification_token
User.find(user_id).increment!(:verification_fails)
errors.add(:sms_code, "does not match")
end
end
The problem is as soon as I add the error the previous statement is rolled back. If I comment out the errors.add line then the increment works however there is no higher level validation performed.
Change your custom validator to be:
def token_match
if token != User.find(user_id).verification_token
errors.add(:sms_code, "does not match")
end
end
and add in your model after_validation callback to be like this:
after_validation: increase_fails_count
def increase_fails_count
unless self.errors[:sms_code].empty?
user = User.find_by(:id => user_id)
user.increment!(:verification_fails)
user.save
end
end
You can use #update_columns in your validator. It writes directly to db.
u = User.find(user_id)
u.update_columns(verification_fails: u.verification_fails + 1)
This worked for me. But if for some reason it doesn't work for you, maybe you can try running it in a new thread,which creates a new db connection:
Thread.new do
num = User.find(user_id).verification_fails
ActiveRecord::Base.connection_pool.with_connection { |con| con.exec_query("UPDATE users SET verification_fails = #{num} WHERE id = #{user_id}") }
end.join
I've been developing Stripe Webhook handler to create/update records depending the values.
It's not really hard, if it's a simple like this below;
StripeEvent.configure do |events|
events.subscribe 'charge.succeeded' do |event|
charge = event.data.object
StripeMailer.receipt(charge).deliver
StripeMailer.admin_charge_succeeded(charge).deliver
end
end
However If I need to store the data conditionally, it could be little messier.
In here I extracted the each Webhook handler and defined something like stripe_handlers/blahblah_handler.rb.
class InvoicePaymentFailed
def call(event)
invoice_obj = event.data.object
charge_obj = retrieve_charge_obj_of(invoice_obj)
invoice = Invoice.find_by(stripe_invoice_id: charge_obj[:invoice])
# common execution for subscription
invoice.account.subscription.renew_billing_period(start_at: invoice_obj[:period_start], end_at: invoice_obj[:period_end])
case invoice.state
when 'pending'
invoice.fail!(:processing,
amount_due: invoice[:amount_due],
error: {
code: charge_obj[:failure_code],
message: charge_obj[:failure_message]
})
when 'past_due'
invoice.failed_final_attempt!
end
invoice.next_attempt_at = Utils.unix_time_to_utc(invoice_obj[:next_payment_attempt].to_i)
invoice.attempt_count = invoice_obj[:attempt_count].to_i
invoice.save
end
private
def retrieve_charge_obj_of(invoice)
charge_obj = Stripe::Charge.retrieve(id: invoice.charge)
return charge_obj
rescue Stripe::InvalidRequestError, Stripe::AuthenticationError, Stripe::APIConnectionError, Stripe::StripeError => e
logger.error e
logger.error e.backtrace.join("\n")
end
end
end
I just wonder how I can DRY up this Webhook handler.
Is there some best practice to approach this or any ideas?
I suggest re-raising the exception in retrieve_charge_obj_of, since you'll just get a nil reference exception later on, which is misleading. (As is, you might as well let the exception bubble up, and let a dedicated error handling system rescue, log, and return a meaningful 500 error.)
a. If you don't want to return a 500, then you have a bug b/c retrieve_charge_obj_of will return nil after the exception is rescued. And if charge_obj is nil, then this service will raise a NPE, resulting in a 500.
if invoice_obj[:next_payment_attempt] can be !present? (blank?), then what is Utils.unix_time_to_utc(invoice_obj[:next_payment_attempt].to_i) supposed to mean?
a. If it was nil, false, or '', #to_i returns 0 -- is that intended? ([]/{} is also blank? but would raise)
Conceptually, this handler needs to issue a state transition on an Invoice, so a chunk of this logic can go in the model instead:
class Invoice < ApplicationRecord
# this method is "internal" to your application, so incoming params should be already "clean"
def mark_payment_failed!(err_code, err_msg, attempt_count, next_payment_at)
transaction do # payment processing usually needs to be transactional
case self.state
when 'pending'
err = { code: err_code, message: err_msg }
self.fail!(:processing, amount_due: self.amount_due, error: err)
when 'past_due'
self.failed_final_attempt!
else
ex_msg = "some useful data #{state} #{err_code}"
raise InvalidStateTransition, ex_msg
end
self.next_attempt_at = next_payment_at
self.attempt_count = attempt_count
self.save
end
end
class InvalidStateTransition < StandardError; end
end
Note: I recommend a formal state machine implementation (e.g. state_machine) before states & transitions get out of hand.
Data extraction, validation, and conversion should happen in the handler (that's what "handlers" are for), and they should happen before flowing deeper in your application. Errors are best caught early and execution stopped early, before any action has been taken.
There are still some other edge cases that I see that aren't really handled.
Consider a simple method -
def my_method(users)
eligible_users = []
users.each do |u|
# Go to the next user unless they are eligible
next unless is_eligible?(u)
begin
update_user(u)
eligible_users << u
rescue
puts "Error occured"
# Prints some other stuff about error
next
end
end
end
A key feature of this method is that it loops through users but continues to the next user even if a given user throws an error.
If I were writing spec tests for this, I'd love to pass an array of 3 users and purposely have it error out on the first user. I can then check that the 2nd and 3rd were still correctly processed.
How would I go about raising an error on purpose for only one of the result sets?
I was thinking I could stub is_eligible? and return an error for one of the result and true for the remainder -
allow_any_instance_of(MyClass).to receive(:is_eligible?).and_return(
raise StandardError.new,
true,
true
)
As expected, that doesn't work. Any other approaches?
Thanks!
I can't exactly answer the question, but rather than doing a begin resuce thing,you can follow this approach,
Make the update_user return true or false.
Keep an array of users that falied to update.
return an object like
response: { status: "failure", message: "falied to update #{pluralize(failed_users_array.count, 'user')}", failures: failed_users_array.join(", ") } for failures and
response: { status: "success", message: "#{pluralize(users.count, 'user')} updated successfully" } for all success.
now you can easily test,
have two cases, one where you can test failures and when you can test all success.
Just stub the response object.
For raising errors, you have to do .and_raise("some tezt or StandardError.new") , thats in the docs.
I created a batch email system for my website. The problem I have, which is terrible, is it continuously sends out emails. It seems the job is stuck in an infinite loop. Please advise. It is crazy because on my development server only one email is sent per account, but on my production server I received 5 emails. Thus, meaning all users of my site received multiple emails.
Controller:
class BatchEmailsController < ApplicationController
before_filter :authenticate_admin_user!
def deliver
flash[:notice] = "Email Being Delivered"
Delayed::Job.enqueue(BatchEmailJob.new(params[:batch_email_id]), 3, 10.seconds.from_now, :queue => 'batch-email', :attempts => 0)
redirect_to admin_batch_emails_path
end
end
Job in the lib folder:
class BatchEmailJob < Struct.new(:batch_email_id)
def perform
be = BatchEmail.find(batch_email_id)
if be.to.eql?("Contractors")
cs = Contractor.all
cs.each do|c|
begin
BatchEmailMailer.batch_email(be.subject, be.message, be.link_name, be.link_path, be.to, c.id).deliver
rescue Exception => e
Rails.logger.warn "Batch Email Error: #{e.message}"
end
else
ps = Painter.all
ps.each do |p|
begin
BatchEmailMailer.batch_email(be.subject, be.message, be.link_name, be.link_path, be.to, p.id).deliver
rescue Exception => e
Rails.logger.warn "Batch Email Error: #{e.message}"
end
end
end
end
end
Delayed Job Initializer:
Delayed::Worker.max_attempts = 0
Please provide feedback on this approach. I want to send out the batch email to all users, but avoid retrying multiple times if something goes wrong. I added rescue block to catch email exceptions in hope that the batch will skip errors and continue processing. As a last resort do not run again if something else goes wrong.
What one of my apps does which seems to work flawlessly after millions of emails:
1) in an initializer, do NOT let DelayedJob re-attempt a failed job AND ALSO not let DJ delete failed jobs:
Delayed::Worker.destroy_failed_jobs = false
Delayed::Worker.max_attempts = 1
2) Scheduling a mass email is 1 job, aka the "master job"
3) When THAT jobs runs, it spawns N jobs where N is the number of emails being sent. So each email gets its own job. (Note: if you use a production email service with 'batch' capability, one "email" might actually be a batch of 100 or 1000 emails.)
4) We have an admin panel that shows us if we have any failed jobs, and if they are, because we don't delete them, we can inspect the failed job and see what happened (malformed email address etc)
If one email fails, the others are un-affected. And no email can ever be sent twice.
I am new to rails and new to active merchant, just want to know if the following code is good enough for payment processing using active merchant.
As you can see, I am using authorize and capture instead of the purchase method. My main concern is the "brought_quantity" subtraction in the code (and it's counter part, when the payment processing fails), I am not quite sure how to deal with it in case of race condition or error from the payment gateway.
Please note that the variable transactions is a instance variable for a model/table where I store the information of the payment gateways responses.
def purchase(item)
price = price_in_cents(item.value)
if !item.can_purchase
errors[:base] << "We are sorry, all items are sold out at the moment."
return false
else
response = GATEWAY.authorize(price, credit_card, purchase_options)
transactions.create!(:action => "authorize", :value => price, :params => response)
#p response
if response.success?
item.brought_quantity = item.brought_quantity + 1
if item.save!
response = GATEWAY.capture(price, response.authorization)
transactions.create!(:action => "capture", :value => price, :params => response)
if !response.success?
errors[:base] << "There were some problem processing your payment, please either try again or contact us at support#foo.com with this error id: 111"
#rd = RunningDeal.find_by_id(#item.id)
#rd.brought_quantity = #rd.brought_quantity - 1
#rd.save!
return false
end
else
errors[:base] << "We are sorry, all items are sold out at the moment."
return false
end
else
# problem process their payment, put out error
errors[:base] << "There were some problem processing your payment, please either try again or contact us at support#foo.com with this error id: 111"
return false
end
end
return true
end
Edit
Ok, did some refactoring and here is the updated code, any comments and suggestions are welcome. I removed the ! on transaction.create since that not a important enough operation to raise an exception.
Here is the updated code based on the feedback.
#from running_deal.rb
def decrement_deal_quantity
self.brought_quantity = self.brought_quantity + 1
return self.save!
end
def purchase(running_deal)
price = price_in_cents(running_deal.value)
if !running_deal.can_purchase
errors[:base] << "We are sorry, all items are sold out at the moment."
return false
else
auth_resp = GATEWAY.authorize(price, credit_card, purchase_options)
transactions.create(:action => "authorize", :value => price, :success => auth_resp.success?, :message => auth_resp.message, :authorization => auth_resp.authorization, :params => auth_resp)
if auth_resp.success?
begin
running_deal.decrement_deal_quantity
cap_resp = GATEWAY.capture(price, auth_resp.authorization)
transactions.create(:action => "capture", :value => price, :success => cap_resp.success?, :message => cap_resp.message, :authorization => cap_resp.authorization, :params => cap_resp)
rescue
GATEWAY.void(auth_resp.authorization, purchase_options) if auth_resp.success?
errors[:base] << "There were some problem processing your payment, please either try again or contact us at support#foo.com"
return false
end
else
# problem process their payment, put out error
errors[:base] << "There were some problem processing your payment, please either try again or contact us at support#foo.com"
return false
end
end
return true
end
processing transactions is tricky.
Couple of thoughts:
if authorize succeeds, capture will succeed in 99.9% of cases. You don't really need to worry about this case that much.
if something fails in your code after authorize() was successful (like an exception writing to the database) you want to call void() to the gateway, to remove the authorization. Otherwise funds are frozen for 7 days.
this code needs to be moved into a model method:
#rd = RunningDeal.find_by_id(#item.id)
#rd.brought_quantity = #rd.brought_quantity - 1
#rd.save!
you need to add clause to the bottom of your method to catch exceptions, since you are calling create!() not create() (which return true if it saves)
rescue Exception => e
# error handing
end
it is unclear why if item.save! fails your error message indicates that the item is sold out? That is totally obscure.
Overall, you want to do someting like this:
check if there is enough inventory
perform AUTH
start db transaction
save/update all db objects
commit transaction
perform CAPTURE
catch exception, and if AUTH was successful - perform VOID
Hope this helps.