Context:
I am using Stripe checkout to accept one-time payment in rails.
I have a charges controller as shown below.
I was initially using stripe webhook to listen to charge.succeeded, but running into some issues due to the async nature of webhooks.
My I have moved the business logic to the controller.
If the customer charge is a success, then I save the customer and some other details to the db.
My question:
Is this check enough to ensure that a charge is successful ?
if charge["paid"] == true
The Stripe documentation for Stripe::Charge.create states, "
Returns a charge object if the charge succeeded. Raises an error if something goes wrong. A common source of error is an invalid or expired card, or a valid card with insufficient available balance."
My ChargesController:
class ChargesController < ApplicationController
def new
end
def create
# Amount in cents
#amount = 100
temp_job_id = cookies[:temp_job_id]
customer_email = TempJobPost.find_by(id: temp_job_id).company[:email]
customer = Stripe::Customer.create(
:email => customer_email,
:card => params[:stripeToken]
)
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => #amount,
:description => 'Rails Stripe customer',
:currency => 'usd',
:metadata => {"job_id"=> temp_job_id}
)
# TODO: charge.paid or charge["paid"]
if charge["paid"] == true
#Save customer to the db
end
# need to test this and refactor this using begin-->rescue--->end
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to charges_path
end
end
Yes, that's all you need to do. If the charge succeeded, Stripe will return a Charge object, and you can check its paid parameter. If the charge failed, we'd throw an exception.
Cheers,
Larry
PS I work on Support at Stripe.
Related
def create_charge
#amount = 500
customer = Stripe::Customer.create(email: params[:email])
pay = Stripe::Charge.create(
:amount => params[:amount],
:currency =>params[:currency],
# :source=>params[:token],
:customer=>customer.id, # obtained with Stripe.js
:description => "Charge for ")
send_json_response("Payment","success",{:pay=>pay})
end
Am trying to create a customer and charge that customer using Rails and Stripe. The customer is getting created in Stripe, but I keep getting the error Cannot charge a customer that has no active card when trying to do the charge
if you are taking info of card on this time ... first check card is valid or not
begin
#token = Stripe::Token.create(
:card => {
:number => params[:card][:card_number],
:exp_month => params[:card][:exp_month],
:exp_year => params[:card][:exp_year],
:cvc => params[:card][:ccv]
},
)
rescue Stripe::CardError, Stripe::InvalidRequestError => e
flash[:error] = e.message and return
rescue
flash[:notice] = 'Something went wrong! Try Again' and return
end
if customer is connected to your website
run webhooks of stripe to check if customer has valid card if not then take that customer to update card page ... to update its card before any purchase
check event type where ( "type": "customer.source.updated")
https://stripe.com/docs/api#event_types
on update card try to check again card is valid or not
Building an application in rails that uses stripe for its payment/checkout system. I have the charges controller, new.html.erb and all the necessary gems in place but for some reason whenever I use my credit card to test stripe with a real payment (the charge is only $2 so it doesn't hurt to test) it appears in my logs as a v1/token rather than a v1/charge and does not appear in the payments section. I have researched extensively the conversion from token to charge and have found multiple answers pointing to the same solution (creating a begin method that turns tokens into charges which I have) but when implementing it doesn't work for me. this is my current charges controller:
require "stripe"
class ChargesController < ApplicationController
def new
# this will remain empty unless you need to set some instance variables to pass on
end
def create
# Amount in cents
#amount = 200
# Set your secret key: remember to change this to your live secret key in production
# See your keys here https://dashboard.stripe.com/account/apikeys
Stripe.api_key = "pk_live_z....." //taken out for security reasons
# Get the credit card details submitted by the form
token = params[:stripeToken]
# Create the charge on Stripe's servers - this will charge the user's card
begin
charge = Stripe::Charge.create(
:amount => #amount, # amount in cents, again
:currency => "usd",
:source => token,
:description => "Example charge"
)
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to new_charge_path
end
end
end
your create method is not being called which executes the logic of payment.
I am integrating Stripe with Devise. I want to sign a user up with stripe and store that Stripe ID before the user is saved. The method is completing before the API call return the Customer hash. How can I fix this?
class User < ActiveRecord::Base
validates_presence_of :stripe_id
before_validation :create_stripe_customer
def create_stripe_customer
customer = Stripe::Customer.create(
:email => email,
:card => stripe_card_token
)
self.stripe_id = customer.id
end
end
When I inspect the User, stripe_id is nil, and validation fails.
The best way to achieve this is to wrap it with a protective block using Active Record Transaction.
Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action.
begin
#user = User.new(strong_params)
User.transaction do
#user.save!
customer = Stripe::Customer.create(
:email => email,
:card => stripe_card_token
)
#user.update_attributes!(stripe_id: customer.id)
end
rescue Exception => ex
flash[:danger] = "#{ex}"
render 'new'
end
This will enforce that the statement will be executed together or not at all.
so I just noticed I had a small problem. I'm using Stripe as my payment processor, and what happened was quite simple. I had a bug in my code which didn't allow me to save the customer_id_token and change a boolean called subscription active.
However the payment still went through (confirmed in stripe logs). Thus it's obvious I don't have proper validations in place as this should never happen. Here's what my code looks like now:
def create
customer = Stripe::Customer.create(
:email => current_user.email,
:plan => params[:plan_id],
:card => params[:stripeToken]
)
current_user.update_attributes!(
:stripe_customer_token => customer.id,
:subscription_active => true,
:plan_id => params[:plan_id]
)
redirect_to root_url, notice: 'Successfully subscribed'
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to charges_path
end
I can see that they are obviously not really connected with one another, and my question is how can I turn this into something that if the customer_token is not saved it won't go through with the payment either?
Okay,
I'm going to take a shot at this, problem is I do not know how Stripe works, so I cannot guarantee this to work.
I just want to demonstrate the usage of transactions:
def create
ActiveRecord::Base.transaction do
customer = Stripe::Customer.create(
email: current_user.email,
plan: params[:plan_id],
card: params[:stripeToken]
)
current_user.update_attributes!(
stripe_customer_token: customer.id,
subscription_active: true,
plan_id: params[:plan_id]
)
end
redirect_to root_url, notice: 'Successfully subscribed'
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to charges_path
end
What I would definitely add to your current_user model, is a validation to check that the token cannot be null:
class User < ActiveRecord::Base
validates :stripe_customer_token, presence: true
end
That way the update fails when the token is not provided, rolling back the transaction. Although with this it should also work if the first call fails.
However this will only work if this Stripe::Customer supports transactions. I do not know or gurantee this to be the solution.
If the Customer call still goes through and does not validate whether the payment is valid, then there's not much you can do.
I have a requirement where i have list of products and each product belongs to various seller and now the user can sign in to the application and buy the product and amount will be transferred to the corresponding seller stripe account. I am struggling with how to proceed with this.
I so far have allowed the seller to signup and connect his stripe account if he has already one or signup and get the code back to the app but i also wanted to know how to get the access token by posting the code that is received in rails and i wanted to know how the user can send the money through card to the corresponding seller.
Please help me
This is speculative (I don't know if you can do this with the current Stripe API):
Can't you assign the seller's stripe access tokens to the Stripe instance?
It seems the Stripe credentials are set in an initializer, which generally means they can't be changed; although I'd hazard a guess you can do by either calling a new instance of the Stripe object, or dynamically setting the seller details:
def create
# Amount in cents
#amount = 500
seller = User.find_by id: params[:product_id]
Stripe.api_key = seller.stripe_api
customer = Stripe::Customer.create(
:email => 'example#stripe.com',
:card => params[:stripeToken]
)
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => #amount,
:description => 'Rails Stripe customer',
:currency => 'usd'
)
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to charges_path
end