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
Related
I have a store where you can buy digital products via download. Every product purchased (I've tested multiple products) displays the same product's information (title, art_link, and download_url) on the thank you page right after purchase.
What Am I doing wrong here that is preventing it from loading the correct data from the pack just purchased?
I'm using Stripe for payments. Everything else works perfectly, the money goes through, the email is sent and links to the receipt, the UUID works, etc.
UPDATE: I've checked my DB and Everything is saving correctly. The only problem is with the purchases/show view not rendering properly.
purchases/show:
<p><b><%= #pack.title %></b></p>
<%= image_tag("#{#pack.art_link}", :alt => "#{#pack.title} sound library.", :width => 330, :height => 330, class: "img-center img-responsive shade") %>
<p><a class="btn btn-success top-drop" href="<%= #pack.download_url %>" target="_blank">Download Files</a></p>
purchases_controller:
def show
#purchase = Purchase.find_by_uuid(params[:id])
#pack = Pack.find(#purchase.product_id)
set_meta_tags noindex: true
end
Purchase model:
attr_accessor :download_token
after_create :email_purchaser
def to_param
uuid
end
def email_purchaser
PurchaseMailer.purchase_receipt(self).deliver
end
def Purchase.new_token
SecureRandom.urlsafe_base64
end
def create_download
self.download_token = Purchase.email.new_token
update_attribute(:download, Purchase.email(download_token))
update_attribute(:download_sent_at, Time.zone.now)
end
charges_controller:
def create
pack = Pack.find(params[:product_id])
customer = Stripe::Customer.create(
:email => params[:stripeEmail],
:source => params[:stripeToken],
)
# Amount in cents
charge = Stripe::Charge.create(
:customer => customer.id,
:amount => pack.price_in_cents,
:description => 'Rails Stripe customer',
:currency => 'usd',
)
purchase = Purchase.create(
email: params[:stripeEmail],
card: params[:stripeToken],
amount: pack.price_in_cents,
description: charge.description,
currency: charge.currency,
customer_id: customer.id,
product_id: pack.id,
uuid: SecureRandom.uuid,
)
redirect_to purchase
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to new_charge_path
end
Thank you very much, this really has me stuck.
Routes.rb:
resources :packs, :path => 'products'
resources :charges
resources :purchases, only: [:show]
The problem was solved on a chat.
In routes.rb, there were following lines:
get 'purchase' => 'purchases#show', as: 'purchase'
...
resources :purchases, only: [:show]
So when OP called: redirect_to purchase the URL was:
http://localhost:3000/purchase.4c77a556-299e-4611-b683-3ff6eb672738
From that, the params[:id] was nil. In DB, there were 4 purchases with UUID equal nil, and the first one was always returned (because find_by returns the first matched record).
So my Plan says Stripe::InvalidRequestError at /orders/26/payments
No such plan: The title of my plan.
This code should check if the the plan already exists and if not create it and subscribe the user to it. I thought this worked because it was working for the case where I already had a plan with the same ID and it said "Plan already exists". How can I prevent this Error from happening?
This is my code:
class PaymentsController < ApplicationController
before_action :set_order
def new
end
def create
#user = current_user
customer = Stripe::Customer.create(
source: params[:stripeToken],
email: params[:stripeEmail],
)
# Storing the customer.id in the customer_id field of user
#user.customer_id = customer.id
#plan = Stripe::Plan.retrieve(#order.service.title)
unless #plan
plan = Stripe::Plan.create(
:name => #order.service.title,
:id => #order.service.title,
:interval => "month",
:currency => #order.amount.currency,
:amount => #order.amount_pennies,
)
else
subscription = Stripe::Subscription.create(
:customer => #user.customer_id,
:plan => #order.service.title
)
end
#order.update(payment: plan.to_json, state: 'paid')
redirect_to order_path(#order)
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to new_order_payment_path(#order)
end
private
def set_order
#order = Order.where(state: 'pending').find(params[:order_id])
end
end
The documentation says that if you try to retrieve a plan that does not exist, it will raise an error. So you just need to catch the error:
begin
#plan = Stripe::Plan.retrieve(#order.service.title)
rescue
#plan = Stripe::Plan.create(...)
end
Little bit improved version. It's sad that there is no way to check if plan exists and you have to rely on exception swallowing it. Here is my version, it tries to retrieve the plan, if error is 404, it creates the plan. Otherwise, lets exception to pop up. So it won't swallow all of the exceptions, which is important IMO when you work with finance API.
def retrieve_or_create_plan(id)
begin
Stripe::Plan.retrieve(id)
rescue Stripe::InvalidRequestError => e
if e.response.http_status == 404
Stripe::Plan.create(
name: 'Your plan name',
id: id,
interval: :month,
currency: :usd,
amount: 100
)
else
raise e
end
end
end
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.
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.
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