Skip to content
This repository has been archived by the owner on Aug 27, 2024. It is now read-only.

Commit

Permalink
Fix issue with multiple error values
Browse files Browse the repository at this point in the history
Closes #2.

Also changes api_login to environment_key and api_secret to
access_secret in a backwards compatible manner.
  • Loading branch information
ntalbott committed Apr 12, 2013
1 parent c3a5bcf commit 173ac3d
Show file tree
Hide file tree
Showing 12 changed files with 140 additions and 97 deletions.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
0.3.0 / April 12, 2013
----------

* api_login -> environment_key
* api_secret -> access_secret
* spreedlycore.com -> core.spreedly.com
* Fixed an issue with multiple errors in a PaymentMethod

0.2.2 / October 18, 2012
----------

Expand Down
36 changes: 18 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
SpreedlyCore
Spreedly
======
spreedly-core-ruby is a Ruby library for accessing the [Spreedly Core API](https://spreedlycore.com/). Spreedly Core is a Software-as-a-Service billing solution that serves two major functions for companies and developers.
spreedly-core-ruby is a Ruby library for accessing the [Spreedly API](https://spreedly.com/). Spreedly is a Software-as-a-Service billing solution that serves two major functions for companies and developers.

* First, it removes your [PCI Compliance](https://www.pcisecuritystandards.org/) requirement by pushing the card data handling and storage outside of your application. This is possible by having your customers POST their credit card info to the Spreedly Core service while embedding a transparent redirect URL back to your application (see "Submit payment form" on [the quick start guide](https://spreedlycore.com/manual/quickstart)).
* First, it removes your [PCI Compliance](https://www.pcisecuritystandards.org/) requirement by pushing the card data handling and storage outside of your application. This is possible by having your customers POST their credit card info to the Spreedly service while embedding a transparent redirect URL back to your application (see "Submit payment form" on [the quick start guide](https://spreedly.com/manual/quickstart)).
* Second, it removes any possibility of your gateway locking you in by owning your customer billing data (yes, this happens). By allowing you to charge any card against whatever gateways you as a company have signed up for, you retain all of your customer data and can switch between gateways as you please. Also, expanding internationally won't require an additional technical integration with yet another gateway.

Credit where credit is due: our friends over at [403 Labs](http://www.403labs.com/) carried most of the weight in cutting the initial version of this gem, and we can't thank them enough for their work.

Quickstart
----------
Head over to the [Spreedly Core Website](https://www.spreedlycore.com) to sign up for an account. It's free to get started and play with test gateways/transactions using our specified test card data.
Head over to the [Spreedly Website](https://www.spreedly.com) to sign up for an account. It's free to get started and play with test gateways/transactions using our specified test card data.

RubyGems:

export SPREEDLYCORE_API_LOGIN=your_login_here
export SPREEDLYCORE_API_SECRET=your_secret_here
export SPREEDLYCORE_ENVIRONMENT_KEY=your_environment_key_here
export SPREEDLYCORE_ACCESS_SECRET=your_secret_here
gem install spreedly-core-ruby
irb
require 'rubygems'
Expand All @@ -26,12 +26,12 @@ The first thing we'll need to do is set up a test gateway that we can run transa
tg = SpreedlyCore::TestGateway.get_or_create
tg.use!

Now that you have a test gateway set up, we'll need to set up your payment form to post the credit card data directly to Spreedly Core. Spreedly Core will receive your customer's credit card data, and immediately transfer them back to the location you define inside the web payments form. The user won't know that they're being taken off site to record to the card data, and you as the developer will be left with a token identifier. The token identifier is used to make your charges against, and to access the customer's non-sensitive billing information.
Now that you have a test gateway set up, we'll need to set up your payment form to post the credit card data directly to Spreedly. Spreedly will receive your customer's credit card data, and immediately transfer them back to the location you define inside the web payments form. The user won't know that they're being taken off site to record to the card data, and you as the developer will be left with a token identifier. The token identifier is used to make your charges against, and to access the customer's non-sensitive billing information.

<form action="https://spreedlycore.com/v1/payment_methods" method="POST">
<form action="https://core.spreedly.com/v1/payment_methods" method="POST">
<fieldset>
<input name="redirect_url" type="hidden" value="http://example.com/transparent_redirect_complete" />
<input name="api_login" type="hidden" value="Ll6fAtoVSTyVMlJEmtpoJV8Shw5" />
<input name="environment_key" type="hidden" value="Ll6fAtoVSTyVMlJEmtpoJV8Shw5" />
<label for="credit_card_first_name">First name</label>
<input id="credit_card_first_name" name="credit_card[first_name]" type="text" />

Expand All @@ -52,11 +52,11 @@ Now that you have a test gateway set up, we'll need to set up your payment form
</fieldset>
</form>

Take special note of the **api_login** and **redirect_url** params hidden in the form, as Spreedly Core will use both of these fields to authenticate the developer's account and to send the customer back to the right location in your app.
Take special note of the **environment_key** and **redirect_url** params hidden in the form, as Spreedly will use both of these fields to authenticate the developer's account and to send the customer back to the right location in your app.

A note about test card data
----------------
If you've just signed up and have not entered your billing information (or selected a Heroku paid plan), you will only be permitted to deal with [test credit card data](https://spreedlycore.com/manual/test-data).
If you've just signed up and have not entered your billing information (or selected a Heroku paid plan), you will only be permitted to deal with [test credit card data](https://core.spreedly.com/manual/test-data).

Once you've created your web form and submitted one of the test cards above, you should be returned to your app with a token identifier by which to identify your newly created payment method. Let's go ahead and look up that payment method by the token returned to your app, and we'll charge $5.50 to it.

Expand All @@ -71,7 +71,7 @@ Once you've created your web form and submitted one of the test cards above, you

Saving Payment Methods
----------
Spreedly Core allows you to retain payment methods provided by your customer for future use. In general, removing the friction from your checkout process is one of the best things you can do for your application, and using Spreedly Core will allow you to avoid making your customer input their payment details for every purchase.
Spreedly allows you to retain payment methods provided by your customer for future use. In general, removing the friction from your checkout process is one of the best things you can do for your application, and using Spreedly will allow you to avoid making your customer input their payment details for every purchase.

payment_token = 'abc123' # extracted from the URL params
payment_method = SpreedlyCore::PaymentMethod.find(payment_token)
Expand All @@ -81,7 +81,7 @@ Spreedly Core allows you to retain payment methods provided by your customer for
retain_transaction.succeeded? # true
end

Payment methods that you no longer want to retain can be redacted from Spreedly Core. A redacted payment method has its sensitive information removed.
Payment methods that you no longer want to retain can be redacted from Spreedly. A redacted payment method has its sensitive information removed.

payment_token = 'abc123' # extracted from the URL params
payment_method = SpreedlyCore::PaymentMethod.find(payment_token)
Expand Down Expand Up @@ -128,7 +128,7 @@ Handling Exceptions
--------
There are 3 types of exceptions which can be raised by the library:

1. SpreedlyCore::TimeOutError is raised if communication with Spreedly Core takes longer than 10 seconds
1. SpreedlyCore::TimeOutError is raised if communication with Spreedly takes longer than 10 seconds
2. SpreedlyCore::InvalidResponse is raised when the response code is unexpected (I.E. we expect a HTTP response code of 200 bunt instead got a 500) or if the response does not contain an expected attribute. For example, the response from retaining a payment method should contain an XML attribute of "transaction". If this is not found (for example a HTTP response 404 or 500 is returned), then an InvalidResponse is raised.
3. SpreedlyCore::UnprocessableRequest is raised when the response code is 422. This denotes a validation error where one or more of the data fields submitted were not valid, or the whole record was unable to be saved/updated. Inspection of the exception message will give an explanation of the issue.

Expand All @@ -144,12 +144,12 @@ For example, let's look up a payment method that does not exist:
end


Configuring SpreedlyCore for Use in Production (Rails example)
Configuring Spreedly for Use in Production (Rails example)
----------
When you're ready for primetime, you'll need to complete a couple more steps to start processing real transactions.

1. First, you'll need to get your business (or personal) payment details on file with Spreedly Core so that we can collect transaction and card retention fees. For those of you using Heroku, simply change your Spreedly Core addon to the paid tier.
2. Second, you'll need to acquire a gateway that you can plug into the back of Spreedly Core. Any of the major players will work, and you're not at risk of lock-in because Spreedly Core happily plays middle man. Please consult our [list of supported gateways](https://www.spreedlycore.com/manual/gateways) to see exactly what information you'll need to pass to Spreedly Core when creating your gateway profile.
1. First, you'll need to get your business (or personal) payment details on file with Spreedly so that we can collect transaction and card retention fees. For those of you using Heroku, simply change your Spreedly addon to the paid tier.
2. Second, you'll need to acquire a gateway that you can plug into the back of Spreedly. Any of the major players will work, and you're not at risk of lock-in because Spreedly happily plays middle man. Please consult our [list of supported gateways](https://core.spreedly.com/manual/gateways) to see exactly what information you'll need to pass to Spreedly when creating your gateway profile.

For this example, I will be using an Authorize.net account that only has a login and password credential.

Expand All @@ -163,7 +163,7 @@ For this example, I will be using an Authorize.net account that only has a login
For most users, you will start off using only one gateway token, and as such can configure it as an environment variable to hold your gateway token. In addition to the previous environment variables, the `SpreedlyCore.configure` method will also look for a SPREEDLYCORE_GATEWAY_TOKEN environment value.

# create an initializer at config/initializers/spreedly_core.rb
# values already set for ENV['SPREEDLYCORE_API_LOGIN'], ENV['SPREEDLYCORE_API_SECRET'], and ENV['SPREEDLYCORE_GATEWAY_TOKEN']
# values already set for ENV['SPREEDLYCORE_ENVIRONMENT_KEY'], ENV['SPREEDLYCORE_ACCESS_SECRET'], and ENV['SPREEDLYCORE_GATEWAY_TOKEN']
SpreedlyCore.configure

If you wish to require additional credit card fields, the initializer is the best place to set this up.
Expand Down
57 changes: 33 additions & 24 deletions lib/spreedly-core-ruby.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
require 'active_support/core_ext/hash/conversions'

module SpreedlyCore
# Hash of user friendly credit card name to SpreedlyCore API name
# Hash of user friendly credit card name to Spreedly API name
CARD_TYPES = {
"Visa" => "visa",
"MasterCard" => "master",
Expand All @@ -22,7 +22,7 @@ module SpreedlyCore

class Error < RuntimeError; end

# Custom exception which occurs when a request to SpreedlyCore times out
# Custom exception which occurs when a request to Spreedly times out
# See SpreedlyCore::Base.default_timeout
class TimeOutError < Error; end
class InvalidResponse < Error
Expand All @@ -42,23 +42,23 @@ def initialize(errors)
end
end

# Configure SpreedlyCore with a particular account.
# Configure Spreedly with a particular account.
# Strongly prefers environment variables for credentials
# and will issue a stern warning should they not be present.
# Reluctantly accepts :login and :secret as options
# Reluctantly accepts :environment_key and :access_secret as options
def self.configure(options = {})
login = ENV['SPREEDLYCORE_API_LOGIN']
secret = ENV['SPREEDLYCORE_API_SECRET']
environment_key = (ENV["SPREEDLYCORE_ENVIRONMENT_KEY"] || ENV['SPREEDLYCORE_API_LOGIN'])
secret = (ENV["SPREEDLYCORE_ACCESS_SECRET"] || ENV['SPREEDLYCORE_API_SECRET'])
gateway_token = ENV['SPREEDLYCORE_GATEWAY_TOKEN']

if options[:api_login]
Kernel.warn("ENV and arg both present for api_login. Defaulting to arg value") if login
login = options[:api_login]
if(options[:environment_key] || options[:api_login])
Kernel.warn("ENV and arg both present for environment_key. Defaulting to arg value") if environment_key
environment_key = (options[:environment_key] || options[:api_login])
end

if options[:api_secret]
Kernel.warn("ENV and arg both present for api_secret. Defaulting to arg value") if secret
secret = options[:api_secret]
if(options[:access_secret] || options[:api_secret])
Kernel.warn("ENV and arg both present for access_secret. Defaulting to arg value") if secret
secret = (options[:access_secret] || options[:api_secret])
end

if options[:gateway_token]
Expand All @@ -67,18 +67,18 @@ def self.configure(options = {})
end
options[:gateway_token] ||= gateway_token

if options[:api_login] || options[:api_secret]
Kernel.warn("It is STRONGLY preferred that you house your Spreedly Core credentials only in environment variables.")
Kernel.warn("This gem prefers only environment variables named SPREEDLYCORE_API_LOGIN, SPREEDLYCORE_API_SECRET, and optionally SPREEDLYCORE_GATEWAY_TOKEN.")
if(options[:environment_key] || options[:access_secret])
Kernel.warn("It is STRONGLY preferred that you house your Spreedly credentials only in environment variables.")
Kernel.warn("This gem prefers only environment variables named SPREEDLYCORE_ENVIRONMENT_KEY, SPREEDLYCORE_ACCESS_SECRET, and optionally SPREEDLYCORE_GATEWAY_TOKEN.")
end

if login.nil? || secret.nil?
raise ArgumentError.new("You must provide a login and a secret. Gem will look for ENV['SPREEDLYCORE_API_LOGIN'] and ENV['SPREEDLYCORE_API_SECRET'], but you may also pass in a hash with :api_login and :api_secret keys.")
if environment_key.nil? || secret.nil?
raise ArgumentError.new("You must provide a environment_key and a secret. Gem will look for ENV['SPREEDLYCORE_ENVIRONMENT_KEY'] and ENV['SPREEDLYCORE_ACCESS_SECRET'], but you may also pass in a hash with :environment_key and :access_secret keys.")
end

options[:endpoint] ||= "https://spreedlycore.com/#{SpreedlyCore::API_VERSION}"
options[:endpoint] ||= "https://core.spreedly.com/#{SpreedlyCore::API_VERSION}"

Base.configure(login, secret, options)
Base.configure(environment_key, secret, options)
end

def self.gateway_token=(gateway_token)
Expand All @@ -89,13 +89,22 @@ def self.gateway_token
Base.gateway_token
end

# returns the configured SpreedlyCore login
def self.login; Base.login; end
# returns the configured Spreedly environment key
def self.environment_key; Base.environment_key; end

# A container for a response from a payment gateway
class Response < Base
attr_reader(:success, :message, :avs_code, :avs_message, :cvv_code,
:cvv_message, :error_code, :error_detail, :created_at,
:updated_at)
attr_reader(
:success,
:message,
:avs_code,
:avs_message,
:cvv_code,
:cvv_message,
:error_code,
:error_detail,
:created_at,
:updated_at
)
end
end
33 changes: 20 additions & 13 deletions lib/spreedly-core-ruby/base.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
require 'spreedly-core-ruby/version'

module SpreedlyCore
# Base class for all SpreedlyCore API requests
# Base class for all Spreedly API requests
class Base
include HTTParty

Expand All @@ -14,14 +14,14 @@ class Base
format :xml
default_timeout 75

def self.configure(login, secret, options = {})
@@login = login
self.basic_auth(@@login, secret)
def self.configure(environment_key, secret, options = {})
@@environment_key = environment_key
self.basic_auth(@@environment_key, secret)
base_uri options[:endpoint]
@@gateway_token = options.delete(:gateway_token)
end

def self.login; @@login; end
def self.environment_key; @@environment_key; end
def self.gateway_token; @@gateway_token; end
def self.gateway_token=(gateway_token); @@gateway_token = gateway_token; end

Expand Down Expand Up @@ -58,7 +58,7 @@ def self.verify_request(request_type, path, options, *allowed_codes, &block)
begin
response = self.send(request_type, path, options)
rescue Timeout::Error, Errno::ETIMEDOUT => e
raise TimeOutError.new("Request to #{path} timed out. Is Spreedly Core down?")
raise TimeOutError.new("Request to #{path} timed out. Is Spreedly down?")
end

if allowed_codes.any? && !allowed_codes.include?(response.code)
Expand Down Expand Up @@ -87,13 +87,20 @@ def initialize(attrs={})
instance_variable_set("@#{k}", v)
end
# errors may be nil, empty, a string, or an array of strings.
@errors = if @errors.nil? || @errors["error"].blank?
[]
elsif @errors["error"].is_a?(String)
[@errors["error"]]
else
@errors["error"]
end
@errors = if(@errors.nil? || @errors["error"].blank?)
[]
elsif @errors["error"].is_a?(String)
[@errors["error"]]
else
@errors["error"].collect do |error|
case error
when Hash
error["__content__"]
else
error
end
end
end
end
end
end
12 changes: 6 additions & 6 deletions lib/spreedly-core-ruby/payment_method.rb
Original file line number Diff line number Diff line change
Expand Up @@ -91,12 +91,12 @@ def validate
@has_been_validated = true
self.class.additional_required_cc_fields.each do |field|
if instance_variable_get("@#{field}").blank?
str_field= field.to_s
friendly_name = if str_field.respond_to?(:humanize)
str_field.humanize
else
str_field.split("_").join(" ")
end
str_field = field.to_s
friendly_name = if(str_field.respond_to?(:humanize))
str_field.humanize
else
str_field.split("_").join(" ")
end

@errors << "#{friendly_name.capitalize} can't be blank"
end
Expand Down
14 changes: 7 additions & 7 deletions lib/spreedly-core-ruby/test_extensions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,18 @@
module SpreedlyCore
module TestHelper
extend self

def cc_data(cc_type, options={})

card_numbers = {:master => [5555555555554444, 5105105105105100],
:visa => [4111111111111111, 4012888888881881],
:american_express => [378282246310005, 371449635398431],
:discover => [6011111111111117, 6011000990139424]
}

card_number = options[:card_number] == :failed ? :last : :first
number = card_numbers[cc_type].send(card_number)

{ :credit_card => {
:first_name => "John",
:last_name => "Foo",
Expand All @@ -26,7 +26,7 @@ def cc_data(cc_type, options={})
:year => Time.now.year + 1 }.merge(options[:credit_card] || {})
}
end

# Return the base uri as a mocking framework would expect
def mocked_base_uri_string
uri = URI.parse(Base.base_uri)
Expand All @@ -38,9 +38,9 @@ def mocked_base_uri_string
end

class PaymentMethod
# Call spreedly core to create a test token.
# Call spreedly to create a test token.
# pass_through_data will be added as the "data" field.
#
#
def self.create_test_token(cc_overrides = {})
card = {
:first_name => "John",
Expand Down
Loading

0 comments on commit 173ac3d

Please sign in to comment.