Skip to content

Instantly share code, notes, and snippets.

@braidn
Created March 8, 2014 18:23
Show Gist options
  • Save braidn/9436441 to your computer and use it in GitHub Desktop.
Save braidn/9436441 to your computer and use it in GitHub Desktop.
require 'stripe'
namespace :quarterly do
desc 'associate json file with existing users'
task json_to_stripe: :environment do
File.open("tmp/q_import.json", "r") do |file|
parsed_data = JSON.parse file.read
parsed_data['ids'].each do |id|
next if good_customer(stripe_account(id.last))
associate_with_stripe(stripe_account(id.last), spree_user_by_profile(id.first))
end
end
end
desc 'associate through all recurly customers'
task associate_with_stripe: :environment do
iteration, stop = 1, 0
@stripers = stripe_customers
while stop <= @stripers.count
@stripers.each do |cust|
unless good_customer(cust)
associate_with_stripe(cust, spree_user(cust))
if @stripers.data.last.id == cust.id
binding.pry
@stripers = stripe_customers(iteration * 100)
iteration +=1; stop +=@stripers.data.count
end
end
end
end
end
desc 'delayed_job_check'
task :dj_stripe_check, [:issue_id] => :environment do |t, args|
Spree::User.find(delayed_job_users_ids(args)).each do |user|
if gateway_id(user)
if compare_default_card(user)
puts '--yep'
else
puts "--nope #{user.id} #{user.email}"
end
else
puts "#{user.id} not a valid Stripe Customer"
end
end
end
def good_customer(cust)
(spree_user(cust) && gateway_id(spree_user(cust)) == cust.id) &&
gateway_payment(spree_user(cust)) == cust.default_card
end
def spree_user(cust)
Spree::User.find_by_email(cust.email)
end
def stripe_customers(offset = 0)
Stripe::Customer.all(count: 2, offset: offset)
end
def compare_default_card(user)
Stripe::Customer.retrieve(gateway_id(user)).default_card ==
user.payment_source_on_file.gateway_payment_profile_id
end
def gateway_payment(user)
user.payment_source_on_file.gateway_payment_profile_id
end
def gateway_id(user)
return false if user.payment_source_on_file.nil?
user.payment_source_on_file.gateway_customer_profile_id
end
def delayed_job_users_ids(args)
Delayed::Job.where('queue like ?', "retry_issue_#{args[:issue_id]}%" ).
map{ |j| j.queue.split("_")[4] }.uniq
end
def stripe_account(account_id)
Stripe::Customer.retrieve(account_id)
end
def spree_user_by_profile(profile)
return nil if Spree::CreditCard.find_by_gateway_customer_profile_id(profile).nil?
Spree::CreditCard.find_by_gateway_customer_profile_id(profile).user
end
def associate_with_stripe(striper, spree_user)
return if spree_user.nil? || spree_user.payment_source_on_file_id.nil?
new_cc = spree_user.payment_source_on_file.dup
new_cc.assign_attributes({ gateway_customer_profile_id: striper.id,
gateway_payment_profile_id: striper.default_card },
without_protection: true)
new_cc.save
spree_user.update_attribute(:payment_source_on_file_id, new_cc.id)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment