Rails : Controller/Create - How to write an if create success - ruby-on-rails

I am currently building an app that uses stripe, when a payment is successful the user follows redirect_to session.delete(:return_to). How do I control where the user goes when the payment is declined or there is an error?
Perhaps I need an if statement? If success?
def create
#account = User.find_by_id(params[:account_id])
key = #account.access_code
Stripe.api_key = key
account_suid = #account.uid
#order = Order.find(params[:order])
charge = #order.amount * 100
fee = #order.amount * 1
token = params[:stripeToken]
customer = Stripe::Customer.create(email: #order.email, source: token)
Stripe::PaymentIntent.create({
customer: customer,
amount: (charge).to_i,
confirm: true,
currency: 'gbp',
payment_method_types: ['card'],
application_fee_amount: (fee).to_i,
}, {
stripe_account: account_suid
})
options = {
stripe_id: customer.id
}
options.merge!(
card_last4: params[:user][:card_last4],
card_exp_month: params[:user][:card_exp_month],
card_exp_year: params[:user][:card_exp_year],
card_type: params[:user][:card_brand]
)
OrderFiniJob.perform_now(#order)
redirect_to session.delete(:return_to), notice: "Your order has been successful 👌🏼"
end

When an error occurs or the payment is declined, stripe raises an exception (some stripe erros).
So, you could rescue the error and respond what you want, for example 400
def create
...
redirect_to ...
rescue Stripe::StripeError
render status: :bad_request
end

Related

Is it possible to apply billings to paypal using the sdk gem?

I am applying paypal payments to my website developed in rails 5, I am using the gem 'paypal-sdk-rest', it works quite well for unit payments but i need to implement memberships with monthly and annual fee automatically. is it possible to create memberships with the gem'paypal-sdk-rest'? What would be the necessary parameters to send to the paypal api? this is what I have so far:
class Paypal::CheckoutsController < ApplicationController
include PayPal::SDK::REST
def create
payment = Payment.new({
intent: 'sale',
payer: {
payment_method: 'paypal'
},
redirect_urls: {
return_url: complete_paypal_checkouts_url,
cancel_url: line_items_url
},
transactions: [
{
amount: {
total: current_cart.total,
currency: 'USD',
},
description: 'Pago de productos',
item_list: {
items: current_cart.line_items.map(&:to_paypal)
}
},
]
})
if payment.create
redirect_url = payment.links.find{|v| v.rel == "approval_url" }.href
redirect_to redirect_url
else
redirect_to line_items_path, alert: 'Something went wrong, please try later'
end
end
def complete
payment = Payment.find(params[:paymentId])
if payment.execute(payer_id: params[:PayerID]) #return true or false
session[:cart_id] = nil
redirect_to root_path, notice: 'Thanks for purchasing!'
else
redirect_to line_items_path, alert: 'There was a problem processing your payment'
end
end
end

Active Merchant paypal recurring payments

I am using Active Merchant gem to handle payments through the site. But now i want to make these payments recurring, on a monthly basis. Is there a way using active merchant or?
subscription_controller.rb
class SubscriptionsController < ApplicationController
def new
#home_page = true
#white = true
#subscription = Subscription.new(token: params[:token])
if !logged_in?
redirect_to signup_url
end
end
def create
#subscription = Subscription.new(subscription_params)
#subscription.remote_ip = request.remote_ip
#subscription.user_id = current_user.id
if #subscription.save
if #subscription.purchase
#subscription.send_thank_you_email
redirect_to thankyou_path
else
raise ActiveRecord::Rollback
flash[:notice] = "It seems something went wrong with the paypal transaction. Please check that your credit card is valid and has credit in it and try again."
redirect_to :back
end
else
flash[:notice] = "Something went wrong with marking your purchase as complete. Please contact support to check it out."
redirect_to :back
end
end
def purchase
response = GATEWAY.setup_purchase(999,
ip: request.remote_ip,
return_url: new_subscription_url,
cancel_return_url: root_url,
currency: "USD",
items: [{name: "Order", description: "Recurring payment for ******", quantity: "1", amount: 999}]
)
redirect_to GATEWAY.redirect_url_for(response.token)
end
def thank_you
#home_page = true
#white = true
end
private
def subscription_params
params.require(:subscription).permit(:token)
end
end
subscription.rb model
def purchase
response = GATEWAY.purchase(999, express_purchase_options)
response.success?
end
def token=(token)
self[:token] = token
if new_record? && !token.blank?
# you can dump details var if you need more info from buyer
details = GATEWAY.details_for(token)
puts details.params["PayerInfo"]["PayerName"].inspect
self.payer_id = details.payer_id
self.first_name = details.params["PayerInfo"]["PayerName"]["FirstName"]
self.last_name = details.params["PayerInfo"]["PayerName"]["LastName"]
end
end
# send thank you email
def send_thank_you_email
UserMailer.thank_you(self).deliver_now
end
private
def express_purchase_options
{
:ip => remote_ip,
:token => token,
:payer_id => payer_id
}
end
production.rb environment
config.after_initialize do
ActiveMerchant::Billing::Base.mode = :production
::GATEWAY = ActiveMerchant::Billing::PaypalExpressGateway.new(
:login => ENV['PAYPAL_LOGIN'],
:password => ENV['PAYPAL_PASSWORD'],
:signature => ENV['PAYPAL_SIGNATURE']
)
end
I think ActiveMerchant used to have something like this:
subscription = PAYPAL_EXPRESS_GATEWAY.recurring(#subscription.price_in_cents, nil,
:description => 'blah',
:start_date => Date.tomorrow,
:period => 'Year',
:frequency => 1,
:amount => price,
:currency => 'USD'
)
See this answer Does ActiveMerchant support Subscription Based transaction
Also see this: https://github.com/activemerchant/active_merchant/blob/master/lib/active_merchant/billing/gateways/paypal_express.rb
https://github.com/activemerchant/active_merchant/blob/master/lib/active_merchant/billing/gateways/paypal/paypal_recurring_api.rb

Item description not shown in Paypal Transaction details

Hi I'm Integrating Paypal express checkout using Activemerchant.
I'm able to make successful transaction but I'm not seeing My Item's description in transaction details page.It display all the other option correctly but the Options column is empty.
However I'm seeing Items details in the checkout page.
Here is my code.I probably doing something wrong.
def express_checkout
listing = Listing.find(session[:listing_id].to_f)
response = EXPRESS_GATEWAY.setup_purchase(session[:amount].to_f,
ip: request.remote_ip,
return_url: "http://esignature.lvh.me:3000/en/transactions/status",
cancel_return_url: "http://esignature.lvh.me:3000/",
currency: "USD",
allow_guest_checkout: true,
items: [{name: listing.title, description: listing.description, quantity: session[:number_of_days], amount: listing.price_cents},
{name: "Service Charge" ,description: "Service Charge", amount: session[:service_charge]}
]
)
redirect_to EXPRESS_GATEWAY.redirect_url_for(response.token)
end
def status
if (params[:token].present? && params[:PayerID].present?)
token = params[:token]
#response = EXPRESS_GATEWAY.details_for(token).params
listing = Listing.find(session[:listing_id].to_f)
express_purchase_options = {
:ip => request.remote_ip,
:token => params[:token],
:payer_id => params[:PayerID],
items: [{ name: listing.title, description: listing.description, quantity: session[:number_of_days], amount: listing.price_cents},
{ name: "Service Charge", description: "Service Charge", amount: session[:service_charge ]}
]
}
response = EXPRESS_GATEWAY.purchase(session[:amount].to_f, express_purchase_options)
if response.message == "Success"
listing = Listing.find(session[:listing_id].to_f)
BookingInfo.create!(listing_id: listing.id, start_on: session[:start_date].to_date, end_on: session[:end_date].to_date)
render 'status'
else
render 'status_error'
end
reset_session_params
else
reset_session_params
redirect_to homepage_without_locale_path
end
end
here I'm setting Item details in both setup_purchase as well as in purchase.Any suggestion will be appreciated.Thank you

Shopping Cart Contents missing Transaction details not shown on Paypal Express Checkout

I'm using ActiveMerchantI'm trying to Integrate PayPal using express checkout and Adaptive Payment. In the Adaptive Payment I was able to view Shopping Cart Contents as below . My code was like this which works as expected.
def adaptive_checkout
listing = Listing.find(session[:listing_id].to_f)
total_amount_in_cents = listing.price_cents
service_charge_rate = 5 #in percentage 5%
service_charge_in_cents = total_amount_in_cents * service_charge_rate / 100
service_charge_in_dollor = service_charge_in_cents / 100.00 # this will be for secondary user (Admin of the system)
total_amount_in_dollar = total_amount_in_cents / 100.00 # this will be for primary receiver
seller_email = PaypalAccount.where(person_id: listing.author_id).last.email # This is the Primary receiver
system_admin_email = PaypalAccount.where(active: true)
.where("paypal_accounts.community_id IS NOT NULL && paypal_accounts.person_id IS NULL")
.first.email # This is the Secondary receiver
recipients = [
{
email: seller_email,
amount: total_amount_in_dollar ,
primary: true
},
{
email: system_admin_email,
amount: service_charge_in_dollor,
primary: false
}
]
response = ADAPTIVE_GATEWAY.setup_purchase(
action_type: "CREATE",
return_url: "http://esignature.lvh.me:3000/en/transactions/status",
cancel_url: "http://esignature.lvh.me:3000/",
ipn_notification_url: "http://0dbf7871.ngrok.io/en/transactions/notification",
receiver_list: recipients
)
ADAPTIVE_GATEWAY.set_payment_options(
pay_key: response["payKey"],
receiver_options: [
{
description: "Your purchase of #{listing.title}",
invoice_data: {
item: [
{
name: listing.title,
item_count: 1,
item_price: total_amount_in_dollar,
price: total_amount_in_dollar
}
]
},
receiver: {email: seller_email}
},
{
description: "Service charge for purchase of #{listing.title} ",
invoice_data: {
item: [
{
name: "Service charge for purchase of #{listing.title}",
item_count: 1,
item_price: service_charge_in_dollor,
price: service_charge_in_dollor
}
]
},
receiver: {email: system_admin_email}
}
]
)
# For redirecting the customer to the actual paypal site to finish the payment.
redirect_to (ADAPTIVE_GATEWAY.redirect_url_for(response["payKey"]))
end
But using express_checkout, I can't see my shopping cart Contents in transaction details
however during the transaction, item details appears,
For the express checkout my code is like this
def express_checkout
listing = Listing.find(session[:listing_id].to_f)
response = EXPRESS_GATEWAY.setup_purchase(session[:amount].to_f,
ip: request.remote_ip,
return_url: "http://esignature.lvh.me:3000/en/transactions/status",
cancel_return_url: "http://esignature.lvh.me:3000/",
currency: "USD",
allow_guest_checkout: true,
items: [{name: listing.title, description: listing.description, quantity: session[:number_of_days], amount: listing.price_cents},
{name: "Service Charge", amount: session[:service_charge]}
]
)
redirect_to EXPRESS_GATEWAY.redirect_url_for(response.token)
end
def status
if (params[:token].present? && params[:PayerID].present?)
token = params[:token]
#response = EXPRESS_GATEWAY.details_for(token).params
express_purchase_options = {
:ip => request.remote_ip,
:token => params[:token],
:payer_id => params[:PayerID]
}
response = EXPRESS_GATEWAY.purchase(session[:amount].to_f, express_purchase_options)
if response.message == "Success"
listing = Listing.find(session[:listing_id].to_f)
BookingInfo.create!(listing_id: listing.id, start_on: session[:start_date].to_date, end_on: session[:end_date].to_date)
render 'status'
else
render 'status_error'
end
reset_session_params
else
reset_session_params
redirect_to homepage_without_locale_path
end
end
I tried to use set_payment_options method but raise method missing error. Is there any way other way to attach Item details on express checkout.
Are you including the line item details in the DoExpressCheckout call as well? If you are only sending them in the SetExpressCheckout call, they would show in the checkout screen as listed above, but if not included in the DoExpressCheckout call, they would not show in the transaction details.
https://github.com/activemerchant/active_merchant/issues/1912

How to send email to user after payment is done with paypal

I want to sent email to user after transcation done. now paypal is working fine for me, but user is not getting mail notification after transcation done? how to get email notification for user .
Here is my code
This is my controller code
This is my paypal function
def pay
if #order.update order_params
#order.update_attributes(:invoice_id => rand.to_s[2..11])
if current_user.billing_address.blank?
current_user.create_billing_address(#order.billing_address.dup.attributes)
end
if current_user.shipping_address.blank?
current_user.create_shipping_address(#order.shipping_address.dup.attributes)
end
# #cart.calculate_shipping
if #order.total == 0
return redirect_to checkout_thank_you_path
end
# if !params['payment'].present?
# return redirect_to :back, notice: 'Select Payment Gateway!'
# end
# if params['payment']=='paypal'
#order.order_statuses.create(status_type: 1)
item_details=[]
#order.line_items.each do |item|
item_details << {:name => item.title, :quantity => item.quantity, :amount => item.amount.fractional}
end
logger.info item_details.inspect
response = EXPRESS_GATEWAY.setup_purchase(#cart.total.fractional,
:ip => request.remote_ip,
:currency =>"USD",
:items => item_details,
:order_id => #order.invoice_id,
:return_url => checkout_thank_you_url,
:cancel_return_url => cart_url
)
return redirect_to EXPRESS_GATEWAY.redirect_url_for(response.token)
# else
# return redirect_to 'https://www.payumoney.com/'
# end
else
flash[:alert] = 'Billing and shipping address fields are required!'
render :addresses
end
end
This is my thank function for paypal
def thank_you
#order = Order.find(session[:order_id])
details = EXPRESS_GATEWAY.details_for(params[:token])
response = EXPRESS_GATEWAY.purchase(#cart.total.fractional, {
ip: request.remote_ip,
token: params[:token],
payer_id: details.payer_id,
items: #order.line_items.map{|l| {name: l.title, quantity: l.quantity, amount: l.amount.fractional}}
})
if response.success?
# logger.info payment_params.inspect
payment_params = {gateway: 'PayPal Express Checkout', transaction_id: response.params['token'], ip: request.remote_ip, amount: response.params['gross_amount']}
#cart.order.created_at = DateTime.now
#cart.order.status = 'Paid'
#cart.order.save
session.delete :order_id
# OrderMailer.order_confirmation(#order).deliver
# OrderMailer.admin_receipt(#order).deliver
else
redirect_to :cart_checkout, alert: 'Something went wrong. Please try again. If the problem persists, please contact us.'
end
#cart = Cart.new current_or_null_user.id, session[:order_id], session[:currency] # Start a new cart
end
Any help is appreciatable

Resources