I have been having a lot of difficulty with this, I just can't see where I am going wrong. Although I am fairly rookie, I am trying to do something a ton of app developers must routinely succeed in doing - process an Apple Pay charge through Stripe's example Sinatra / Ruby backend available at:
https://github.com/stripe/example-ios-backend
I believe I have done everything fine:
My Stripe account is set up, I am in test mode, I have verified my bank, it all looks fine.
I am using Test API keys, secret and publishable : the following is the code in my slightly modified web.ry file: you can see that the app working at least at the ‘/‘ endpoint if you go to: https://ibidurubypay.herokuapp.com - please note I have absolutely NO IDEA what I am doing in Rails - the only mods I have made are:
I have inserted the Stripe test key
I have slightly modified the initial return message to check changes are being updated on Heroku
I changed the currency to GBP (stripe account is GBP)
Code is:
require 'sinatra'
require 'stripe'
require 'dotenv'
require 'json'
Dotenv.load
Stripe.api_key = ENV['sk_test_mystripetestkeymystripetestkey']
get '/' do
status 200
return "Great, terrific, your backend is set up. Now you can configure the Stripe example iOS apps to point here."
end
post '/charge' do
# Get the credit card details submitted by the form
source = params[:source] || params[:stripe_token] || params[:stripeToken]
customer = params[:customer]
# Create the charge on Stripe's servers - this will charge the user's card
begin
charge = Stripe::Charge.create(
:amount => params[:amount], # this number should be in cents
:currency => "gbp",
:customer => customer,
:source => source,
:description => "Example Charge"
)
rescue Stripe::StripeError => e
status 402
return "Error creating charge: #{e.message}"
end
status 200
return "Charge successfully created"
end
get '/customers/:customer/cards' do
customer = params[:customer]
begin
# Retrieves the customer's cards
customer = Stripe::Customer.retrieve(customer)
rescue Stripe::StripeError => e
status 402
return "Error retrieving cards: #{e.message}"
end
status 200
content_type :json
cards = customer.sources.all(:object => "card")
selected_card = cards.find {|c| c.id == customer.default_source}
return { :cards => cards.data, selected_card: selected_card }.to_json
end
post '/customers/:customer/sources' do
source = params[:source]
customer = params[:customer]
# Adds the token to the customer's sources
begin
customer = Stripe::Customer.retrieve(customer)
customer.sources.create({:source => source})
rescue Stripe::StripeError => e
status 402
return "Error adding token to customer: #{e.message}"
end
status 200
return "Successfully added source."
end
post '/customers/:customer/select_source' do
source = params[:source]
customer = params[:customer]
# Sets the customer's default source
begin
customer = Stripe::Customer.retrieve(customer)
customer.default_source = source
customer.save
rescue Stripe::StripeError => e
status 402
return "Error selecting default source: #{e.message}"
end
status 200
return "Successfully selected default source."
end
delete '/customers/:customer/cards/:card' do
card = params[:card]
customer = params[:customer]
# Deletes the source from the customer
begin
customer = Stripe::Customer.retrieve(customer)
customer.sources.retrieve(card).delete()
rescue Stripe::StripeError => e
status 402
return "Error deleting card"
end
status 200
return "Successfully deleted card."
end
As you can see the Ruby web app is running fine…
Switching to Xcode, I then go and download Stripe's example apps at: https://github.com/stripe/stripe-ios/tree/master/Example
I open ‘Stripe.xcworkspace’ in the ‘stripe-ios-master’ folder.
In my Apple Developer account, I go set up a new app ‘com.AH.thenameigaveit’ Merchant
I ticked ApplePay and then set up a Merchant Identifier with: merchant.com.AH.thenameigaveit
I go to Stripe and create a CSR certificate which I then link up with my Merchant ID in Apple Dev.
I got my new Apple CER file and uploaded it to Stripe - and I was able to verify that it was successfully installed.
Back in Xcode I hit Fix Issue for provisioning profile problem and it all gets accepted.
My entitlements file says ‘com.apple.developer.in-app-payments’
Now in Xcode I go to ViewController.swift in Stripe's 'Simple' example and change the values of the various user variables as follows:
stripePublishableKey = “'pk_test_mystripetestkeymystripetestkey'” my test publishable key
backendChargeURLString = “https://ibidurubypay.herokuapp.com”
appleMerchantId = “merchant.com.AH.thenameigaveit”
Note the Stripe 'Simple' example Swift code refers to currency as USD whereas my web.ry script refers to “gbp”, however from what I can tell in the past when I tried it a couple of times each way, that looks as if it shouldn’t matter as the currency value is not passed to the Ruby script (and my Stripe account is in GBP.)
So, time to build and run to an iPhone 6 plus with Apple Pay activated on it with a live Visa credit card… app builds successfully first time..
First time around it says :”Payment request is invalid: check your entitlements”, so I go to Capabilities and make sure the correct Merchant ID is checked against ApplePay - build again and this time we get further - the Apple Pay screen comes up perfectly on the screen, specifying the Apple Pay linked credit card to pay $10 for the cool shirt.. - I do the touch, it comes up with ‘Processing Payment’ then shortly after ‘Payment Not Completed!’ and the Apple Pay dialog retreats back down the screen taking back to the option to ‘Buy a shirt’
So, I know absolutely nothing about communicating with this server backend except to try and glean some info coming back from the call, so I insert:
print ("data: \(data), \r\r response: \(response), \r\r error: \(error)")
which gives me:
data: Optional(),
response: Optional( { URL:
*(ASBEFORE)*ibidurubypay.herokuapp.com/charge } { status code: 402, headers {
Connection = "keep-alive";
"Content-Length" = 248;
"Content-Type" = "text/html;charset=utf-8";
Date = "Tue, 28 Jun 2016 00:16:43 GMT";
Server = "WEBrick/1.3.1 (Ruby/2.1.2/2014-05-08)";
Via = "1.1 vegur";
"X-Content-Type-Options" = nosniff;
"X-Frame-Options" = SAMEORIGIN;
"X-Xss-Protection" = "1; mode=block"; } }),
error: nil
That appears to be a Card Decline message, but there’s nothing wrong with the card.
On my Stripe account at the portal, a token was successfully created at the time: 2016/06/28 01:16:42
…however, there is no evidence of the 402 decline I can see anywhere here, maybe I am not looking in the right place…
I would be really grateful if anyone could let me know what’s going wrong - I am tearing my hair out, I have been stumped on this on and off for days.
ok, so I had asked the guys from Stripe this question and blow me over they solved it straight off - the issue was:
Stripe.api_key = ENV['sk_test_mystripetestkeymystripetestkey'] in my Ruby script...
EITHER: it should be:
Stripe.api_key = 'sk_test_mystripetestkeymystripetestkey' (note no ENV[])
OR: BETTER: if should be as it was originally downloaded from Stripe, an environment variable, which I then set up in Stripe, so in the script:
Stripe.api_key = ENV['STRIPE_TEST_SECRET_KEY']
then update your Heroku configuration to create an environment variable named STRIPE_TEST_SECRET_KEY with your test API key as the value: https://devcenter.heroku.com/articles/config-vars
Easy as pie once you know how, thank you Stripe for great support!
Related
I'm setting up an API integration in my rails application with the Facebook Ads/Marketing API. I'm attempting to test very basic options with my Sandbox Ad Account and cannot seem to get them to work. This is error I keep getting:
FacebookAds::ClientError: Unsupported post request.
Object with ID '119033245616727' does not exist, cannot be loaded due
to missing permissions, or does not support this operation.
Please read the Graph API documentation at
https://developers.facebook.com/docs/graph-api: (fbtrace_id: GyiFjx24NY/)
from /Users/kelly/.rvm/gems/ruby-2.3.0/gems/facebookads-0.2.11.0/lib/facebook_ads/api_request.rb:67:in `create_response'
To run the test, I used their Marketing API quickstart to get my access token, app secret and ad account id.
This is my rails config:
Gemfile:
gem 'facebookads' #https://github.com/facebook/facebook-ruby-ads-sdk
My Test Module:
module Advertising
module Facebook
class API
attr_accessor :access_token
attr_accessor :app_secret
attr_accessor :ad_account_id
def initialize
#access_token = 'EAAYVZBezhACwBAKwMk7fhAJO2WFlUeUaCcASveD9gb6ZCKBzEAJIzDToagt4Vy5n6Ue9QpOwyb0SWYCSHHf4A2jbdTOb99GTBjhSOu5WnU03mnKymd2YgmquOJHg4lPx3iZBonYTzriU27OnlBXDMXdIZApwt45SSqQ8SLs5xaMM3lVEsm0r6WXSoos5yiOiqfMB83SfnntzUzqkEywQ'
#app_secret = '15326d2073b04504ef72267bf36a8bd4'
#ad_account_id = '119033245616727'
end
def test1
FacebookAds.configure do |config|
config.access_token = #access_token
config.app_secret = #app_secret
end
ad_account = FacebookAds::AdAccount.get(ad_account_id)
ad_account.campaigns.create(
objective: 'LINK_CLICKS',
status: 'PAUSED',
buying_type: 'AUCTION',
name: 'My Campaign'
)
end
def test2
# With session
session = FacebookAds::Session.new(access_token: #access_token, app_secret: #app_secret)
ad_account = FacebookAds::AdAccount.get(ad_account_id, session)
puts "This is my account name: #{ad_account.name}"
end
end
end
end
Then I'm running this in the rails console:
ad = Advertising::Facebook::API.new()
ad.test1
# OR
ad.test2
This is a newly created facebook app. These are the settings:
Status: In Development
App ID: 1713013025472556
App Secret: 15326d2073b04504ef72267bf36a8bd4
I added the Marketing API to the products section and created a Sandbox Ad Account called T2 Sandbox (119033245616727).
When setting your ad_account_id, add 'act_' in front of the ID. As the SDK will not do this for you.
I have an Authorize.net account for CC processing on my ecommerce site, and I use ActiveMerchant to authoenticate transactions. It worked just fine until a while ago, and then it stopped. I cannot figure out why. When I run it in test mode, it works fine, creates the transactions and successfully authorizes the funds. But when I try with real account, it fails. When I run it from the console, here is the code:
cc_hash =
:first_name => 'Donald',
:last_name => 'Duck',
:number => '4007000000027',
:month => '8',
:year => Time.now.year+1,
:verification_value => '000'
}
card = ActiveMerchant::Billing::CreditCard.new(cc_hash)
#--- valid?
RYeller.bar
if card.valid?
puts "card valid"
else
puts "card not valid"
end
#ActiveMerchant::Billing::Base.mode = :test
#gateway = ActiveMerchant::Billing::AuthorizeNetGateway.new(:login=>'scrubbed',:password=>'scrubbed')
ActiveMerchant::Billing::Base.mode = :production
gateway = ActiveMerchant::Billing::AuthorizeNetGateway.new(:login=>'scrubbed',:password=>'scrubbed')
amount = rand(1000)+2500
options = {}
options[:order_id] = "WEBSITE 26"
options[:description] = 'WEBSITE TEST'
#--- authorize transaction
response = gateway.authorize(amount, card, options)
puts response.inspect
When I run this in test mode, in my sandbox account (the two lines commented out in the code above) - it works fine. When I run it on my real account (the code as is above) - I get an error: "An error occurred during processing. Call Merchant Service Provider." The full response hash is:
#<ActiveMerchant::Billing::Response:0x1078607d8 #fraud_review=false, #params={"response_reason_code"=>"35", "avs_result_code"=>"P", "transaction_id"=>"scrubbed", "response_code"=>2, "response_reason_text"=>"An error occurred during processing. Call Merchant Service Provider.", "card_code"=>"P"}, #message="An error occurred during processing. Call Merchant Service Provider", #authorization="scrubbed", #test=false, #cvv_result={"message"=>"Not Processed", "code"=>"P"}, #success=false, #avs_result={"message"=>"Postal code matches, but street address not verified.", "street_match"=>nil, "postal_match"=>"Y", "code"=>"P"}>
I am using a test CC number and the card.valid? test returns true.
When I look at the transaction in Authorize.net, I see all the transaction created and all the info properly there, but the Transaction Code is General Error.
Any ideas? Help greatly appreciated, I am at the end of my rope here and sinking fast.
Is your production Authorize.net in test mode? If not, Donanld Duck isn't going to be able to check out with a fake credit card.
You should be able to login to your production Authorize.net account and see the test order as a decline. If you do then everything is working and you will need to test with a real card to get a successful transaction. If you want to test with a fake card you will need to set you production account back to testing.
I am using the Ruby Gem "databascdotcom" to integrate Salesforce in a Rails app and all works fine until i try it with sandbox account type "Configuration Only".
The following code work fine when i used with salesforce product account.
Here is my code
def SalesForceFeed
#oppID = params[:oppid]
client = Databasedotcom::Client.new client.client_id #=> foo client.client_secret #=> bar
client.authenticate :username => "foo#bar.com", :password => "ThePasswordTheSecurityToken" #=> "the-oauth-token"
client.materialize("Opportunity")
begin
#client=SalesForce::Connection.new.client
#opp = Opportunity.find_by_Id(#oppID)
rescue Exception=>e
end
But when i try to use it with salesforce sandbox account with username like "foo#bar.com.sandbox"
I m getting following error "expired access/refresh token"
Any ideas?
Got the issue.
Just need to add
host= "test.salesforce.com"
Thanks All
I was trying to implement paypal payment gateway.
But I am getting an error:
This transaction is invalid. Please return to the recipient's website to complete your transaction using their regular checkout flow.
In Gem File
gem 'activemerchant', :require => 'active_merchant'
In development.rb
config.after_initialize do
ActiveMerchant::Billing::Base.mode = :test
paypal_options = {
:login => "************",
:password => "************",
:signature => "************",
}
::STANDARD_GATEWAY = ActiveMerchant::Billing::PaypalGateway.new(paypal_options)
::EXPRESS_GATEWAY = ActiveMerchant::Billing::PaypalExpressGateway.new(paypal_options)
end
Sample code I am using in my controller
response = EXPRESS_GATEWAY.setup_purchase(10000,
:ip => request.remote_ip,
:return_url => new_order_url,
:cancel_return_url => orders_url
)
p response
p response.token
redirect_to EXPRESS_GATEWAY.redirect_url_for(response.token)
O/p for response:
#<ActiveMerchant::Billing::PaypalExpressResponse:0x007f90bbababa0 #params={"timestamp"=>"2011-12-17T21:41:21Z", "ack"=>"Failure", "correlation_id"=>"c152e1862f475", "version"=>"62.0", "build"=>"2271164", "message"=>"Security header is not valid", "error_codes"=>"10002", "Timestamp"=>"2011-12-17T21:41:21Z", "Ack"=>"Failure", "CorrelationID"=>"c152e1862f475", "Errors"=>{"ShortMessage"=>"Security error", "LongMessage"=>"Security header is not valid", "ErrorCode"=>"10002", "SeverityCode"=>"Error"}, "Version"=>"62.0", "Build"=>"2271164"}, #message="Security header is not valid", #success=false, #test=true, #authorization=nil, #fraud_review=false, #avs_result={"code"=>nil, "message"=>nil, "street_match"=>nil, "postal_match"=>nil}, #cvv_result={"code"=>nil, "message"=>nil}>
o/p for response.token
nil
So I think the problem is response.token is nil
any suggestions why this is happening?
Probably the first thing you checked but are the login, password and signature the ones for the sandboxed user and not your own login to the sandbox. You need to log in to the sandboxed users account and the get the signature from in there.
So when you log into sandbox.paypal.com and then go to Test Accounts, select the one you want the details for and press Enter Sandbox Test Site. In the new window enter the details for the fake user (email should be prefilled). Once logged in go to Profile -> API Access and request or view the API signature.
Sorry if you've already tried this but I couldn't post a comment to ask ;)
The following code
purchase = #order.authorize_payment(#credit_card, options)
is_success = purchase.success?
if is_success
...
else
flash[:notice] = "!! " + purchase.message + "" +
purchase.params['missingField'].to_s
redirect_to :action => :payment, :id => #order.id
end
results in "!! Failed with 500 Internal Server Error" in my flash[:notice]. There is no stacktrace, no webserver error, all that I know is that purchase.message is populated and purchase.success? is false.
I am really at a loss to figure out how to troubleshoot this. I think it might be an ssl requirement, but I can't either see the soap request, or test basic connectivity with cybersource (my payment gateway).
I establish my gateway with this code (after config.after_initialize do):
ActiveMerchant::Billing::Base.mode = :production # :test
ActiveMerchant::Billing::CreditCard.require_verification_value = false
ActiveMerchant::Billing::CyberSourceGateway.wiredump_device = File.new(File.join([Rails.root, "log", "cybersource.log"]), "a") # doesn't work (!)
# we need to open an external file to get the password
mypassphrase = File.open('/var/www/foo/shared/passphrase.txt').read
OrderTransaction.gateway = ActiveMerchant::Billing::CyberSourceGateway.new(:login => 'vxxxxxxx',
:password => mypassphrase.to_s,
:test => false,
:vat_reg_number => 'your VAT registration number',
# sets the states/provinces where you have a physical presense for tax purposes
:nexus => "GA OH",
# don‘t want to use AVS so continue processing even if AVS would have failed
:ignore_avs => true,
# don‘t want to use CVV so continue processing even if CVV would have failed
:ignore_cvv => true,
:money_format => :dollars
)
Can I see the soap request? Are there ways to test part of this? Any help greatly appreciated.
Best,
Tim
ActiveMerchant::Billing::CyberSourceGateway.logger = your_logger
So, late response but...
I've done a good amount of work with the Cybersource gateway, and the only way to see the SOAP request/response of the cybersource gateway currently is to open up the gem and edit it.
If you modify the commit method of lib/active_merchant/billing/gateways/cybersource.rb, you can do something like this:
def commit(request, options)
puts "*** POSTING TO: #{test? ? TEST_URL : LIVE_URL}"
request = build_request(request, options)
puts "*** POSTING:"
puts request
begin
post_response = ssl_post(test? ? TEST_URL : LIVE_URL, request)
rescue ActiveMerchant::ResponseError => e
puts "ERROR!"
puts e.response
end
puts post_response
It would be nice if there was a way to get that response without going through that hassle, I'll see if there's a way to pass that information up through the response object that's returned and add it to my fork.