I was working to make payments through Stripe Gateway through Active Merchant gem on a Rails 4 application.
I came along this script and made a similar script by also watching some other resources as follows:
require 'active_merchant'
# Use the TrustCommerce test servers
ActiveMerchant::Billing::Base.mode = :test
gateway = ActiveMerchant::Billing::StripeGateway.new(:login => Rails.application.secrets.stripe_secret_key)
# ActiveMerchant accepts all amounts as Integer values in cents
amount = 1000 # $10.00
# The card verification value is also known as CVV2, CVC2, or CID
credit_card = ActiveMerchant::Billing::CreditCard.new(
:first_name => 'Bob',
:last_name => 'Bobsen',
:number => '4242424242424242',
:month => '8',
:year => Time.now.year+1,
:verification_value => '000')
purchase_options = {
:ip => "127.0.0.1",
:billing_address => {
:name => "Ryan Bates",
:address1 => "123 Main St.",
:city => "New York",
:state => "NY",
:country => "US",
:zip => "10001"
}
}
# Validating the card automatically detects the card type
if credit_card.validate.empty?
# Capture $10 from the credit card
response = gateway.purchase(amount, credit_card, purchase_options)
if response.success?
puts "Successfully charged $#{sprintf("%.2f", amount / 100)} to the credit card #{credit_card.display_number}"
else
raise StandardError, response.message
end
end
but this script generates an error with the following error log:
/Library/Ruby/Gems/2.0.0/gems/activemerchant-1.58.0/lib/active_merchant/billing/gateways/stripe.rb:469:in `rescue in api_request': uninitialized constant ActiveMerchant::Billing::StripeGateway::JSON (NameError)
from /Library/Ruby/Gems/2.0.0/gems/activemerchant-1.58.0/lib/active_merchant/billing/gateways/stripe.rb:463:in `api_request'
from /Library/Ruby/Gems/2.0.0/gems/activemerchant-1.58.0/lib/active_merchant/billing/gateways/stripe.rb:477:in `commit'
from /Library/Ruby/Gems/2.0.0/gems/activemerchant-1.58.0/lib/active_merchant/billing/gateways/stripe.rb:100:in `block (2 levels) in purchase'
from /Library/Ruby/Gems/2.0.0/gems/activemerchant-1.58.0/lib/active_merchant/billing/response.rb:59:in `process'
from /Library/Ruby/Gems/2.0.0/gems/activemerchant-1.58.0/lib/active_merchant/billing/gateways/stripe.rb:98:in `block in purchase'
from /Library/Ruby/Gems/2.0.0/gems/activemerchant-1.58.0/lib/active_merchant/billing/response.rb:45:in `tap'
from /Library/Ruby/Gems/2.0.0/gems/activemerchant-1.58.0/lib/active_merchant/billing/response.rb:45:in `run'
from /Library/Ruby/Gems/2.0.0/gems/activemerchant-1.58.0/lib/active_merchant/billing/gateways/stripe.rb:93:in `purchase'
from stripe.rb:35:in `<main>'
Can you suggest a workaround for this error?
I think you just need to add require 'json'. there's no need to add strip to your gemfile
so it looks like a simple workaround as suggested by #bkunzi01
i thought that active merchant already used stripe in its ActiveMerchant::Billing::StripeGateway file but it doesn't.
just included require 'stripe' at the top of the script and transaction was successful :)
Related
Hope all is good
I am baffled by why my stripe payment in ruby on rails works on my localhost which is c9.io account but when I deployed my code in Heroku, it gives me this error:
Cannot charge a customer that has no active card
my orders.coffee file:
jQuery ->
Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'))
payment.setupForm()
payment =
setupForm: ->
$('#new_order').submit ->
$('input[type=submit]').attr('disabled', true)
obj = Stripe.card.createToken($('#new_order'), payment.handleStripeResponse)
alert(JSON.stringify(obj));
handleStripeResponse: (status, response) ->
if status == 200
$('#new_order').append($('<input type="hidden" name="stripeToken" />').val(response.id))
$('#new_order')[0].submit()
else
$('#stripe_error').text(response.error.message).show()
$('input[type=submit]').attr('disabled', false)
out come of my orders.coffee in localhost:
my application.html.erb header section
<head>
<title>Estydemo</title>
<%= stylesheet_link_tag 'application', media: 'all'%>
<%= javascript_include_tag 'https://js.stripe.com/v2/', type: 'text/javascript' %>
<%= javascript_include_tag 'application' %>
<%= csrf_meta_tags %>
<%= tag :meta, :name=> 'stripe-key', :content => STRIPE_PUBLIC_KEY %>
</head>
my orders_controller.rb stripe section:
Stripe.api_key = ENV["stripe_api_key"]
#flash[:notice] = Stripe.api_key
#puts "stripe api key is " + Stripe.api_key
token = params[:stripeToken]
begin
customer = Stripe::Customer.create(
:source => token,
:description => "Customer.create"
)
charge = Stripe::Charge.create(
:amount => (#listing.price * 100).floor,
:description => 'charge.create',
:currency => "usd",
:customer => customer.id
)
flash[:notice] = "Thanks for ordering!"
rescue Stripe::CardError => e
flash[:danger] = e.message
end
my application.js
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require_tree .
my stripe dashboard for a sample where I get from heroku
Could anyone let me know why I have such an odd issue?
left one is from heroku and right one is from localhost
If there is more info needed, please ask it away.
So this error means that the charge creation request (Stripe::Charge.create(...)) failed because the customer has no payment source.
This in turn means that when you created the customer:
customer = Stripe::Customer.create(
:source => token,
:description => "Customer.create"
)
token must have been either nil or an empty string, and as a result no source parameter was sent to Stripe. You can check this by looking at the log entry for the customer creation request in your Stripe dashboard.
This in turn means that params[:stripeToken] was itself nil or an empty string.
Unfortunately I'm not sure why that's the case. I'd recommend adding some logs, both in the stripeResponseHandler callback in your CoffeeScript file and in the Rails controller, to check whether the token was created and submitted successfully.
I think when test on Heroku, you create charge with new customer and this customer haven't any card default active. Please add create new card before create charge on orders_controller.rb
Stripe.api_key = ENV["stripe_api_key"]
#flash[:notice] = Stripe.api_key
#puts "stripe api key is " + Stripe.api_key
token = params[:stripeToken]
begin
customer = Stripe::Customer.create(
:source => token,
:description => "Customer.create"
)
card = customer.sources.create({:source => token})
charge = Stripe::Charge.create(
:amount => (#listing.price * 100).floor,
:description => 'charge.create',
:currency => "usd",
:customer => customer.id,
:source => card.id
)
flash[:notice] = "Thanks for ordering!"
rescue Stripe::CardError => e
flash[:danger] = e.message
end
I think your error is simply that you're creating a Stripe customer account and passing the token to the Customer but not passing the token to the actual Charge. This needs to be done in both cases. Many use cases for Stripe can be for creating subscriptions or for processing the payment later which is why the Customer Create will take the token on file. But to create a charge you also need to do this. So I would edit the code to include the token in the Charge create like this:
Edited 11/03
Actually I went ahead and reverted the code back to what you had. From reading through the API some more I think that you may be able to make it work this way just fine. That is if you intend on creating a customer that can be charged again later.The direction I would look then is at the fact that it works locally but not on Heroku. I think this is less about the Stripe code and more about the change to production. Look at the ENV variable and seeing if it's set for both dev and production. But not only that, I would precompile your assets as Heroku tends to have an issue with CSS or jQuery at least for me when I go from dev to production. Run RAILS_ENV=production bundle exec rake assets:precompile and that should do the trick, then push to master.
See: https://devcenter.heroku.com/articles/rails-asset-pipeline
token = params[:stripeToken]
begin
customer = Stripe::Customer.create(
:source => token,
:description => "Customer.create"
)
charge = Stripe::Charge.create(
:amount => (#listing.price * 100).floor,
:description => 'charge.create',
:currency => "usd",
:customer => customer.id
)
flash[:notice] = "Thanks for ordering!"
rescue Stripe::CardError => e
flash[:danger] = e.message
end
If you're just looking to charge them but not retain the information in Stripe you can just use:
token = params[:stripeToken]
begin
charge = Stripe::Charge.create(
:amount => (#listing.price * 100).floor,
:currency => "usd",
:source => token,
:description => "Example charge"
)
flash[:notice] = "Thanks for ordering!"
rescue Stripe::CardError => e
flash[:danger] = e.message
end
Edit 11/07
Ok so in looking through the actual repo, I think that you are having an issue because you don't have the necessary javascript call to create the token in the first place. I would reference the Stripe Api here:
https://stripe.com/docs/stripe.js#collecting-card-details
and insert this into your orders.js file, but that's contingent on the various input fields being named with those classes in the form you use to create the order. I hope this now helps point you in the correct direction. Everything else is looking like it should be good from what I can tell.
Stripe.card.createToken({
number: $('.card-number').val(),
cvc: $('.card-cvc').val(),
exp_month: $('.card-expiry-month').val(),
exp_year: $('.card-expiry-year').val()
}, stripeResponseHandler);
I am working on dashing dashboard and trying to add a Jira widget.In the widget code it is trying to create and initialize a Client object. As shown in code below
require 'Jira'
SCHEDULER.every '5m', :first_in => 0 do |job|
client = Jira::Client.new({
:username => ENV['Talal'],
:password => ENV['Talal123'],
:site => "http://192.168.99.100:32768",
:auth_type => :basic,
:context_path => "/jira"
})
But as I gets to this line client = Jira::Client.new. An exception occurs which states that uninitialized constant Jira::Client.
I believe the gem you should be using is jira-ruby. Once you install it, Bundler should automatically require it for you, meaning if you're in a Rails environment, you shouldn't need to do require 'Jira'.
If you don't want it required application-wide, BTW, you should add this to your Gemfile:
gem 'jira-ruby', require: false
# then in your scheduler, you have to explicitly require it as before:
require 'jira-ruby'
SCHEDULER.every '5m', :first_in => 0 do |job|
client = Jira::Client.new({
:username => ENV['Talal'],
:password => ENV['Talal123'],
:site => "http://192.168.99.100:32768",
:auth_type => :basic,
:context_path => "/jira"
})
Additional information here
I'm trying to make a test payment using the example in the ActiveMerchant documentation and i'm getting a response with result=508, message= Invalid timestamp: Value exceeds allowable limit.
This is the code i am using:
ActiveMerchant::Billing::Base.mode = :test
gateway = ActiveMerchant::Billing::RealexGateway.new(
:login => 'myUsername',
:password => 'myPassword')
amount = 1000 # $10.00
credit_card = ActiveMerchant::Billing::CreditCard.new(
:first_name => 'Bob',
:last_name => 'Bobsen',
:number => 'valid card number',
:month => '8',
:year => '2015',
:verification_value => '123')
if credit_card.valid?
response = gateway.purchase(amount, credit_card)
if response.success?
puts "Successfully charged $#{sprintf("%.2f", amount / 100)} to the credit card #{credit_card.display_number}"
else
raise StandardError, response.message
end
end
Anyone encounter such an error?
Thanks,
Uri
This error means that the timestamp you sent in the request is more than 24 hours out of date. Can you check the time on the server and make sure it is accurate?
This isn't a very good message - apologies for that!
Owen
I am currently working on a Ruby-on-Rails web-application that accepts PayPal payments through PayPal's Express Checkout and ActiveMerchant. I have done several research on ActiveMerchant's support for determining if a customer/buyer has paid using either a verified or unverified PayPal account but I got no luck on finding a helpful guide.
I find it also that ActiveMerchant is currently not well-documented so it's not that helpful at all.
Below are the relevant codes that my project is currently using. On PaymentsController#purchase, I temporarily used the #params['protection_eligibility'] and the #params['protection_eligibility_type'] methods of the ActiveMerchant::Billing::PaypalExpressResponse object that is returned by the EXPRESS_GATEWAY.purchase method call, to assess if a PayPal customer/buyer has a verified/unverified PayPal account. Later I found out that this is not a reliable basis for knowing the customer's account status.
I hope somebody can give me a wisdom on knowing whether a PayPal customer/buyer has a verified/unverified account using Ruby-on-Rails' ActiveMerchant or using other alternatives on Rails.
# config/environments/development.rb
config.after_initialize do
ActiveMerchant::Billing::Base.mode = :test
paypal_options = {
# credentials removed for this StackOverflow question
:login => "",
:password => "",
:signature => ""
}
::EXPRESS_GATEWAY = ActiveMerchant::Billing::PaypalExpressGateway.new(paypal_options)
end
# app/models/payment.rb
class Payment < ActiveRecord::Base
# ...
PAYPAL_CREDIT_TO_PRICE = {
# prices in cents(US)
1 => 75_00,
4 => 200_00,
12 => 550_00
}
STATUSES = ["pending", "complete", "failed"]
TYPES = ["paypal", "paypal-verified", "paypal-unverified", "wiretransfer", "creditcard"]
# ...
end
# app/controllers/payments_controller.rb
class PaymentsController < ApplicationController
# ...
def checkout
session[:credits_qty] = params[:credit_qty].to_i
total_as_cents = Payment::PAYPAL_CREDIT_TO_PRICE[session[:credits_qty]]
setup_purchase_params = {
:allow_guest_checkout => true,
:ip => request.remote_ip,
:return_url => url_for(:action => 'purchase', :only_path => false),
:cancel_return_url => url_for(:controller => 'payments', :action => 'new', :only_path => false),
:items => [{
:name => pluralize(session[:credits_qty], "Credit"),
:number => 1,
:quantity => 1,
:amount => Payment::PAYPAL_CREDIT_TO_PRICE[session[:credits_qty]]
}]
}
setup_response = EXPRESS_GATEWAY.setup_purchase(total_as_cents, setup_purchase_params)
redirect_to EXPRESS_GATEWAY.redirect_url_for(setup_response.token)
end
def purchase
if params[:token].nil? or params[:PayerID].nil?
redirect_to new_payment_url, :notice => I18n.t('flash.payment.paypal.error')
return
end
total_as_cents = Payment::PAYPAL_CREDIT_TO_PRICE[session[:credits_qty]]
purchase_params = {
:ip => request.remote_ip,
:token => params[:token],
:payer_id => params[:PayerID],
:items => [{
:name => pluralize(session[:credits_qty], "Credit"),
:number => 1,
:quantity => 1,
:amount => Payment::PAYPAL_CREDIT_TO_PRICE[session[:credits_qty]]
}]
}
purchase = EXPRESS_GATEWAY.purchase total_as_cents, purchase_params
if purchase.success?
payment = current_user.payments.new
payment.paypal_params = params
payment.credits = session[:credits_qty]
payment.amount = Payment::PAYPAL_CREDIT_TO_PRICE[session[:credits_qty]]
payment.currency = "USD"
payment.status = "complete"
if(purchase.params["receipt_id"] && (purchase.params["success_page_redirect_requested"] == "true"))
payment.payment_type = "creditcard"
else
if purchase.params['protection_eligibility'] == 'Eligible' && purchase.params['protection_eligibility_type'] == 'ItemNotReceivedEligible,UnauthorizedPaymentEligible'
payment.payment_type = 'paypal-verified'
else
payment.payment_type = 'paypal-unverified'
end
end
payment.ip_address = request.remote_ip.to_s
payment.save!
SiteMailer.paypal_payment(payment).deliver
SiteMailer.notice_payment(payment).deliver
notice = I18n.t('flash.payment.status.thanks')
redirect_to profile_url, :notice => notice
else
notice = I18n.t('flash.payment.status.failed', :message => purchase.message)
redirect_to new_payment_url, :notice => notice
end
end
# ...
end
I used PayPal's paypal-sdk-merchant gem to do the job ActiveMerchant wasn't able to help me with (getting the status of a payer's account: verified/unverified PayPal account. I followed the installation of paypal-sdk-merchant on https://github.com/paypal/merchant-sdk-ruby
gem 'paypal-sdk-merchant'
bundle install
rails generate paypal:sdk:install
Then I set-up their samples https://github.com/paypal/merchant-sdk-ruby#samples. After setting-up the samples, go to /samples of your Rails app and you will find a lot of code generator for what ever function you need from PayPal's API. Don't forget to configure your config/paypal.yml. I configured the username, password and signature (can be obtained from your PayPal sandbox specifically your test seller account) and removed the app_id in my case.
I obtained the following code for getting a PayPal payer's account status (verified/unverified) using PayPal's samples (/samples) and placed it on a class method of a model in my app:
def self.get_paypal_payer_status(transaction_id)
require 'paypal-sdk-merchant'
api = PayPal::SDK::Merchant::API.new
get_transaction_details = api.build_get_transaction_details({
:Version => "94.0",
:TransactionID => transaction_id
})
get_transaction_details_response = api.get_transaction_details(get_transaction_details)
get_transaction_details_response.payment_transaction_details.payer_info.payer_status
end
I'm not familiar with ActiveMerchant so I can't tell you specific to that, but with any Express Checkout implementation you can use GetExpressCheckoutDetails to obtain the payers information which will include a PAYERSTATUS parameter with a value of "verified" or "unverified".
It's an optional call, but I would assume ActiveMerchant is probably including it so you just need to track that down and pull that parameter accordingly.
Alternatively, you can use Instant Payment Notification (IPN) to receive transaction information and you will get back a payer_status parameter here as well.
I am trying to get feedzirra running on rails 3, I tried by some methods I have found on the internet.
This is in my gemfile:
source 'http://gems.github.com'
gem 'loofah', '1.0.0.beta.1'
group :after_initialize do
gem 'pauldix-feedzirra'
end
And i've out this after bundle.setup in root.rb
Bundler.require :after_initialize
And this is the code in my model (movie.rb)
class Movie < ActiveRecord::Base
def self.import_from_feed
feed = Feedzirra::Feed.fetch_and_parse("url-to.xml")
add_entries(feed.entries)
end
private
def self.add_entries(entries)
entries.each do |entry|
unless exists? :guid => entry.id
create!(
:title => entry.title,
:synopsis => entry.synopsis,
:cover => entry.cover,
:duration => entry.duration,
:channel => entry.channel,
:imdb_rating => entry.imdb_rating,
:imdb_votes => entry.imdb_votes,
:imdb_id => entry.imdb_votes
)
end
end
end
end
I try to run the import_from_feed function from the console and I keep getting this error:
>> Movie.import_from_feed
NameError: uninitialized constant Movie::Feedzirra
from /Users/myname/Ruby/appname/app/models/movie.rb:3:in `import_from_feed'
from (irb):1
Can someone help me out? Been trying for ages now!
Two things:
Just add the gem, not under :after_initialize
Use the feedzirra gem, not the old pauldix-feedzirra one.