Giter Club home page Giter Club logo

stripe-ruby's Introduction

Stripe Ruby Library

Gem Version Build Status Coverage Status

The Stripe Ruby library provides convenient access to the Stripe API from applications written in the Ruby language. It includes a pre-defined set of classes for API resources that initialize themselves dynamically from API responses which makes it compatible with a wide range of versions of the Stripe API.

The library also provides other features. For example:

  • Easy configuration path for fast setup and use.
  • Helpers for pagination.
  • Built-in mechanisms for the serialization of parameters according to the expectations of Stripe's API.

Documentation

See the Ruby API docs.

See video demonstrations covering how to use the library.

Installation

You don't need this source code unless you want to modify the gem. If you just want to use the package, just run:

gem install stripe

If you want to build the gem from source:

gem build stripe.gemspec

Requirements

  • Ruby 2.3+.

Bundler

If you are installing via bundler, you should be sure to use the https rubygems source in your Gemfile, as any gems fetched over http could potentially be compromised in transit and alter the code of gems fetched securely over https:

source 'https://rubygems.org'

gem 'rails'
gem 'stripe'

Usage

The library needs to be configured with your account's secret key which is available in your Stripe Dashboard. Set Stripe.api_key to its value:

require 'stripe'
Stripe.api_key = 'sk_test_...'

# list customers
Stripe::Customer.list()

# retrieve single customer
Stripe::Customer.retrieve('cus_123456789')

Per-request Configuration

For apps that need to use multiple keys during the lifetime of a process, like one that uses Stripe Connect, it's also possible to set a per-request key and/or account:

require "stripe"

Stripe::Customer.list(
  {},
  {
    api_key: 'sk_test_...',
    stripe_account: 'acct_...',
    stripe_version: '2018-02-28',
  }
)

Stripe::Customer.retrieve(
  'cus_123456789',
  {
    api_key: 'sk_test_...',
    stripe_account: 'acct_...',
    stripe_version: '2018-02-28',
  }
)

Stripe::Customer.retrieve(
  {
    id: 'cus_123456789',
    expand: %w(balance_transaction)
  },
  {
    stripe_version: '2018-02-28',
    api_key: 'sk_test_...',
  }
)

Stripe::Customer.capture(
  'cus_123456789',
  {},
  {
    stripe_version: '2018-02-28',
    api_key: 'sk_test_...',
  }
)

Keep in mind that there are different method signatures depending on the action:

  • When operating on a collection (e.g. .list, .create) the method signature is method(params, opts).
  • When operating on resource (e.g. .capture, .update) the method signature is method(id, params, opts).
  • One exception is that retrieve, despite being an operation on a resource, has the signature retrieve(id, opts). In addition, it will accept a Hash for the id param but will extract the id key out and use the others as options.

Accessing resource properties

Both indexer and accessors can be used to retrieve values of resource properties.

customer = Stripe::Customer.retrieve('cus_123456789')
puts customer['id']
puts customer.id

NOTE: If the resource property is not defined, the accessors will raise an exception, while the indexer will return nil.

customer = Stripe::Customer.retrieve('cus_123456789')
puts customer['unknown'] # nil
puts customer.unknown # raises NoMethodError

Accessing a response object

Get access to response objects by using the last_response property of the returned resource:

customer = Stripe::Customer.retrieve('cus_123456789')

print(customer.last_response.http_status) # to retrieve status code
print(customer.last_response.http_headers) # to retrieve headers

Configuring a proxy

A proxy can be configured with Stripe.proxy:

Stripe.proxy = 'https://user:[email protected]:1234'

Configuring an API Version

By default, the library will use the API version pinned to the account making a request. This can be overridden with this global option:

Stripe.api_version = '2018-02-28'

See versioning in the API reference for more information.

Configuring CA Bundles

By default, the library will use its own internal bundle of known CA certificates, but it's possible to configure your own:

Stripe.ca_bundle_path = 'path/to/ca/bundle'

Configuring Automatic Retries

You can enable automatic retries on requests that fail due to a transient problem by configuring the maximum number of retries:

Stripe.max_network_retries = 2

Various errors can trigger a retry, like a connection error or a timeout, and also certain API responses like HTTP status 409 Conflict.

Idempotency keys are added to requests to guarantee that retries are safe.

Configuring Timeouts

Open, read and write timeouts are configurable:

Stripe.open_timeout = 30 # in seconds
Stripe.read_timeout = 80
Stripe.write_timeout = 30 # only supported on Ruby 2.6+

Please take care to set conservative read timeouts. Some API requests can take some time, and a short timeout increases the likelihood of a problem within our servers.

Logging

The library can be configured to emit logging that will give you better insight into what it's doing. The info logging level is usually most appropriate for production use, but debug is also available for more verbosity.

There are a few options for enabling it:

  1. Set the environment variable STRIPE_LOG to the value debug or info:

    $ export STRIPE_LOG=info
  2. Set Stripe.log_level:

    Stripe.log_level = Stripe::LEVEL_INFO

Instrumentation

The library has various hooks that user code can tie into by passing a block to Stripe::Instrumentation.subscribe to be notified about specific events.

request_begin

Invoked when an HTTP request starts. Receives RequestBeginEvent with the following properties:

  • method: HTTP method. (Symbol)
  • path: Request path. (String)
  • user_data: A hash on which users can set arbitrary data, and which will be passed through to request_end invocations. This could be used, for example, to assign unique IDs to each request, and it'd work even if many requests are running in parallel. All subscribers share the same object for any particular request, so they must be careful to use unique keys that will not conflict with other subscribers. (Hash)

request_end

Invoked when an HTTP request finishes, regardless of whether it terminated with a success or error. Receives RequestEndEvent with the following properties:

  • duration: Request duration in seconds. (Float)
  • http_status: HTTP response code (Integer) if available, or nil in case of a lower level network error.
  • method: HTTP method. (Symbol)
  • num_retries: The number of retries. (Integer)
  • path: Request path. (String)
  • user_data: A hash on which users may have set arbitrary data in request_begin. See above for more information. (Hash)
  • request_id: HTTP request identifier. (String)
  • response_header: The response headers. (Hash)
  • response_body = The response body. (String)
  • request_header = The request headers. (Hash)
  • request_body = The request body. (String)

Example

For example:

Stripe::Instrumentation.subscribe(:request_end) do |request_event|
  # Filter out high-cardinality ids from `path`
  path_parts = request_event.path.split("/").drop(2)
  resource = path_parts.map { |part| part.match?(/\A[a-z_]+\z/) ? part : ":id" }.join("/")

  tags = {
    method: request_event.method,
    resource: resource,
    code: request_event.http_status,
    retries: request_event.num_retries
  }
  StatsD.distribution('stripe_request', request_event.duration, tags: tags)
end

Writing a Plugin

If you're writing a plugin that uses the library, we'd appreciate it if you identified using #set_app_info:

Stripe.set_app_info('MyAwesomePlugin', version: '1.2.34', url: 'https://myawesomeplugin.info')

This information is passed along when the library makes calls to the Stripe API.

Telemetry

By default, the library sends telemetry to Stripe regarding request latency and feature usage. These numbers help Stripe improve the overall latency of its API for all users, and improve popular features.

You can disable this behavior if you prefer:

Stripe.enable_telemetry = false

Beta SDKs

Stripe has features in the beta phase that can be accessed via the beta version of this package. We would love for you to try these and share feedback with us before these features reach the stable phase. To install a beta version use gem install with the exact version you'd like to use:

gem install stripe -v 7.1.0.pre.beta.2

Note There can be breaking changes between beta versions. Therefore we recommend pinning the package version to a specific beta version in your Gemfile. This way you can install the same version each time without breaking changes unless you are intentionally looking for the latest beta version.

We highly recommend keeping an eye on when the beta feature you are interested in goes from beta to stable so that you can move from using a beta version of the SDK to the stable version.

If your beta feature requires a Stripe-Version header to be sent, set the Stripe.api_version field using Stripe.add_beta_version:

Stripe.add_beta_version("feature_beta", "v3")

Support

New features and bug fixes are released on the latest major version of the Stripe Ruby library. If you are on an older major version, we recommend that you upgrade to the latest in order to use the new features and bug fixes including those for security vulnerabilities. Older major versions of the package will continue to be available for use, but will not be receiving any updates.

Development

The test suite depends on stripe-mock, so make sure to fetch and run it from a background terminal (stripe-mock's README also contains instructions for installing via Homebrew and other methods):

go get -u github.com/stripe/stripe-mock
stripe-mock

Run all tests:

bundle exec rake test

Run a single test suite:

bundle exec ruby -Ilib/ test/stripe/util_test.rb

Run a single test:

bundle exec ruby -Ilib/ test/stripe/util_test.rb -n /should.convert.names.to.symbols/

Run the linter:

bundle exec rake rubocop

Update bundled CA certificates from the Mozilla cURL release:

bundle exec rake update_certs

Update the bundled stripe-mock by editing the version number found in .travis.yml.

stripe-ruby's People

Contributors

ab avatar amber-stripe avatar andrewpthorp avatar anniel-stripe avatar bkrausz avatar boucher avatar brandur avatar brandur-stripe avatar briancollins avatar dcr-stripe avatar ebroder avatar evan-stripe avatar gdb avatar helenye-stripe avatar jim-stripe avatar kamil-stripe avatar kjc-stripe avatar kyleconroy avatar ob-stripe avatar pakrym-stripe avatar ramya-stripe avatar rasmus-stripe avatar rattrayalex-stripe avatar remi-stripe avatar richardm-stripe avatar russell-stripe avatar russelldavis avatar spakanati avatar stripe-openapi[bot] avatar timcraft avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

stripe-ruby's Issues

Error trying to retrieve events

---------- Forwarded message ----------
From: Amit Saxena
Subject: Getting error while trying to access stripe events API via Ruby gem

Hi,

I am working on webhooks and while trying to access existing events via rails console, I get the following exception:

irb(main):018:0> Stripe::Event.all
NoMethodError: undefined method encode_json' for :disputed:Symbol ย  ย from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.11/lib/active_support/json/encoding.rb:214:inencode_json'
ย  ย from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.11/lib/active_support/json/encoding.rb:214:in map' ย  ย from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.11/lib/active_support/json/encoding.rb:214:inencode_json'
ย  ย from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.11/lib/active_support/json/encoding.rb:214:in encode_json' ย  ย from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.11/lib/active_support/json/encoding.rb:214:inmap'
ย  ย from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.11/lib/active_support/json/encoding.rb:214:in encode_json' ย  ย from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.11/lib/active_support/json/encoding.rb:214:inencode_json'
ย  ย from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.11/lib/active_support/json/encoding.rb:214:in map' ย  ย from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.11/lib/active_support/json/encoding.rb:214:inencode_json'
ย  ย from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.11/lib/active_support/json/encoding.rb:214:in encode_json' ย  ย from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.11/lib/active_support/json/encoding.rb:214:inmap'
ย  ย from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.11/lib/active_support/json/encoding.rb:214:in encode_json' ย  ย from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.11/lib/active_support/json/encoding.rb:47:inencode'
ย  ย from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.11/lib/active_support/json/encoding.rb:77:in check_for_circular_references' ย  ย from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.11/lib/active_support/json/encoding.rb:45:inencode'
ย  ย from /usr/lib/ruby/gems/1.8/gems/activesupport-3.0.11/lib/active_support/json/encoding.rb:247:in encode_json' ... 9 levels... ย  ย from /usr/lib/ruby/gems/1.8/gems/json-1.6.5/lib/json/common.rb:278:ingenerate'
ย  ย from /usr/lib/ruby/gems/1.8/gems/json-1.6.5/lib/json/common.rb:278:in pretty_generate' ย  ย from /usr/lib/ruby/gems/1.8/gems/stripe-1.6.0/lib/stripe.rb:179:ininspect'
ย  ย from /usr/lib/ruby/1.8/irb.rb:310:in output_value' ย  ย from /usr/lib/ruby/1.8/irb.rb:159:ineval_input'
ย  ย from /usr/lib/ruby/1.8/irb.rb:271:in signal_status' ย  ย from /usr/lib/ruby/1.8/irb.rb:155:ineval_input'
ย  ย from /usr/lib/ruby/1.8/irb.rb:154:in eval_input' ย  ย from /usr/lib/ruby/1.8/irb.rb:71:instart'
ย  ย from /usr/lib/ruby/1.8/irb.rb:70:in catch' ย  ย from /usr/lib/ruby/1.8/irb.rb:70:instart'
ย  ย from /usr/lib/ruby/gems/1.8/gems/railties-3.0.11/lib/rails/commands/console.rb:44:in start' ย  ย from /usr/lib/ruby/gems/1.8/gems/railties-3.0.11/lib/rails/commands/console.rb:8:instart'
ย  ย from /usr/lib/ruby/gems/1.8/gems/railties-3.0.11/lib/rails/commands.rb:23
ย  ย from script/rails:6:in `require'
ย  ย from script/rails:6irb(main):019:0>

Can't update bank account for recipient?

Not able to update bank account for the recipient. However, I'm able to update all other fields except BANK_ACCOUNT which is an embedded object:

rp = Stripe::Recipient.retrieve({RECIPIENT_ID})
rp.active_account.routing_number = {NEW_ROUTING_NUMBER}
rp.save

Impossible to update a customer without retrieving it first.

Maybe it's by design, but it do not really look like it is:

>> c = Stripe::Customer.new("cus_1EqKjPaFs4ZwDD")
=> #<Stripe::Customer:0x3ff839d432b4 id=cus_1EqKjPaFs4ZwDD> JSON: {
  "id": "cus_1EqKjPaFs4ZwDD"
}
>> c.coupon = 'C0UP0N'
>> c.save
Stripe::InvalidRequestError: (Status 400) A parameter provided in the URL (id) was repeated as a GET or POST parameter. You can only provide this information as a portion of the URL.
    from ~/.rvm/gems/ruby-1.9.3-p327/gems/stripe-1.7.9/lib/stripe.rb:218:in `handle_api_error'
    from ~/.rvm/gems/ruby-1.9.3-p327/gems/stripe-1.7.9/lib/stripe.rb:179:in `rescue in request'
    from ~/.rvm/gems/ruby-1.9.3-p327/gems/stripe-1.7.9/lib/stripe.rb:165:in `request'
    from ~/.rvm/gems/ruby-1.9.3-p327/gems/stripe-1.7.9/lib/stripe/api_operations/update.rb:11:in `save'
    from (irb):84
    from ~/.rvm/gems/ruby-1.9.3-p327/gems/railties-3.2.11/lib/rails/commands/console.rb:47:in `start'
    from ~/.rvm/gems/ruby-1.9.3-p327/gems/railties-3.2.11/lib/rails/commands/console.rb:8:in `start'
    from ~/.rvm/gems/ruby-1.9.3-p327/gems/railties-3.2.11/lib/rails/commands.rb:41:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

It's very easy to work around it by refreshing the customer before saving, but being able to avoid this extra refresh would save a lot of time in the cases where this request have to be performed synchronously.

Regards.

Stripe List object doesn't repond in a predictable manner

What I tried:

Stripe::Charge.all(:count => 1)[0]

What I expected:

The first charge object

What happened:

NoMethodError: undefined method `to_sym' for 0:Fixnum

Normally things that are returned from an all method respond like an array.

Getting "Object doesn't support #inspect" on all API calls

Added gem to a Rails 3.1 app. When trying to make API calls from the console (dev mode), I get this:

ruby-1.9.2-p290 :004 > Stripe::Charge.all
(Object doesn't support #inspect)
=>

This happens for all calls I've tried. Gem version is 1.6.0.

Rails version is 3.1.3 on Ruby 1.9.2 (RVM).

Stripe::Customer should always respond_to? :active_card

We just migrated a bunch of accounts over to Stripe and some didn't have a credit card attached to it. Our code naively assumed that if a customer didn't have an active card, that customer.active_card would return nil. In fact, it raises a NoMethodError.

I think it'd be a lot cleaner from a client perspective if it did just return nil in that case.

ActiveSupport's Object#try doesn't work for Plan#id

 pry(#<OrganizationSerializer>)> object.stripe_plan.try :id
=> nil

 pry(#<OrganizationSerializer>)> object.stripe_plan
=> #<Stripe::Plan:0x3fd51dc5cfec> JSON: {
  "id": "pro",
  "interval": "month",
  "name": "Pro",
  "amount": 5000,
  "currency": "usd",
  "object": "plan",
  "livemode": false,
  "interval_count": 1,
  "trial_period_days": 30
}
 pry(#<OrganizationSerializer>)> object.stripe_plan.id
=> "pro"
 pry(#<OrganizationSerializer>)> object.stripe_plan && object.stripe_plan.id
=> "pro"

http segfaults

I know stripe does not write the http class but I have been getting segfaults with rails(3.0.7 ruby 1.8.7 and 1.9.3-rc1 rvmed). This is in development mode with webrick. I might try another server locally to see if it helps. I have not had any issues til i save the plan. Code is based off of railscast video.

def save_with_payment(token)
if valid?
customer = Stripe::Customer.create(:description=> email, :plan=> 'pro', :card=> token)
self.stripe_customer_token = customer.id
save!
end
rescue Stripe::InvalidRequestError => e
logger.error "Stripe error while creating customer: #{e.message}"
errors.add :base, "There was a problem with your credit card."
false
end

/Users/becker/.rvm/rubies/ruby-1.9.3-rc1/lib/ruby/1.9.1/net/http.rb:799: [BUG] Segmentation fault
ruby 1.9.3dev (2011-09-23 revision 33323) [x86_64-darwin10.8.0]

-- Control frame information -----------------------------------------------
c:0081 p:---- s:0456 b:0456 l:000455 d:000455 CFUNC :connect
c:0080 p:0011 s:0453 b:0453 l:0013e0 d:000452 BLOCK /Users/becker/.rvm/rubies/ruby-1.9.3-rc1/lib/ruby/1.9.1/net/http.rb:799
c:0079 p:0111 s:0451 b:0451 l:0018a0 d:0018a0 METHOD /Users/becker/.rvm/rubies/ruby-1.9.3-rc1/lib/ruby/1.9.1/timeout.rb:68
c:0078 p:0026 s:0439 b:0439 l:000438 d:000438 METHOD /Users/becker/.rvm/rubies/ruby-1.9.3-rc1/lib/ruby/1.9.1/timeout.rb:99
c:0077 p:0485 s:0433 b:0433 l:0013e0 d:0013e0 METHOD /Users/becker/.rvm/rubies/ruby-1.9.3-rc1/lib/ruby/1.9.1/net/http.rb:799
c:0076 p:0011 s:0425 b:0425 l:000424 d:000424 METHOD /Users/becker/.rvm/rubies/ruby-1.9.3-rc1/lib/ruby/1.9.1/net/http.rb:755
c:0075 p:0048 s:0422 b:0422 l:000421 d:000421 METHOD /Users/becker/.rvm/rubies/ruby-1.9.3-rc1/lib/ruby/1.9.1/net/http.rb:744
c:0074 p:0297 s:0419 b:0419 l:002570 d:002570 METHOD /Users/becker/.rvm/gems/ruby-1.9.3-rc1@git/gems/rest-client-1.6.1/lib/restclient/request.rb:166
c:0073 p:0075 s:0411 b:0411 l:000410 d:000410 METHOD /Users/becker/.rvm/gems/ruby-1.9.3-rc1@git/gems/rest-client-1.6.1/lib/restclient/request.rb:60
c:0072 p:0021 s:0406 b:0406 l:000405 d:000405 METHOD /Users/becker/.rvm/gems/ruby-1.9.3-rc1@git/gems/rest-client-1.6.1/lib/restclient/request.rb:31
c:0071 p:0021 s:0401 b:0401 l:000400 d:000400 METHOD /Users/becker/.rvm/gems/ruby-1.9.3-rc1@git/gems/stripe-1.6.0/lib/stripe.rb:570
c:0070 p:0568 s:0397 b:0397 l:000396 d:000396 METHOD /Users/becker/.rvm/gems/ruby-1.9.3-rc1@git/gems/stripe-1.6.0/lib/stripe.rb:532
c:0069 p:0037 s:0378 b:0378 l:000377 d:000377 METHOD /Users/becker/.rvm/gems/ruby-1.9.3-rc1@git/gems/stripe-1.6.0/lib/stripe.rb:105
c:0068 p:0051 s:0372 b:0372 l:000371 d:000371 METHOD /Users/becker/trash/github/git/app/models/user.rb:24

`respond_to?` does not work correctly after updating

I just updated to the lastest version (from 1.7.0 to 1.7.11) and respond_to? no longer works as expected:

c = Stripe::Customer.retrieve("cus_1MFxqjlury3cRr")
c.id                # => "cus_1MFxqjlury3cRr"
c.respond_to?(:id)  # => false

I've got a work around in my code so it's not urgent. Nevertheless, it seems flat wrong unless I'm missing something?

Inconsistency in active_account/bank_account

recipient.active_account returns the account, but even though it lists active_account= in the methods, you can't change the account info that way... recipient.bank_account doesn't exist, but recipient.bank_account= does

Common interface for checking if customer deleted

It seems that only deleted customers respond to deleted. Any good reason why existing customers don't as well?

Maybe there's something I'm missing, but having to write code like the following feels dirty:

if customer.respond_to?(:deleted) && customer.deleted
   # ...

What about a simple Customer#deleted? helper method?

License missing from gemspec

RubyGems.org doesn't report a license for your gem. This is because it is not specified in the gemspec of your last release.

via e.g.

spec.license = 'MIT'
# or
spec.licenses = ['MIT', 'GPL-2']

Including a license in your gemspec is an easy way for rubygems.org and other tools to check how your gem is licensed. As you can imagine, scanning your repository for a LICENSE file or parsing the README, and then attempting to identify the license or licenses is much more difficult and more error prone. So, even for projects that already specify a license, including a license in your gemspec is a good practice. See, for example, how rubygems.org uses the gemspec to display the rails gem license.

There is even a License Finder gem to help companies/individuals ensure all gems they use meet their licensing needs. This tool depends on license information being available in the gemspec. This is an important enough issue that even Bundler now generates gems with a default 'MIT' license.

I hope you'll consider specifying a license in your gemspec. If not, please just close the issue with a nice message. In either case, I'll follow up. Thanks for your time!

Appendix:

If you need help choosing a license (sorry, I haven't checked your readme or looked for a license file), GitHub has created a license picker tool. Code without a license specified defaults to 'All rights reserved'-- denying others all rights to use of the code.
Here's a list of the license names I've found and their frequencies

p.s. In case you're wondering how I found you and why I made this issue, it's because I'm collecting stats on gems (I was originally looking for download data) and decided to collect license metadata,too, and make issues for gemspecs not specifying a license as a public service :). See the previous link or my blog post about this project for more information.

Update History.txt

The latest Stripe release is 1.6.0, but the history.txt file hasn't been updated since 1.5.0. It'd be helpful to see what changed and if there are any special upgrade considerations.

How can I test stripe in my own app?

Does this library provide any convenience methods to test Stripe in my own app to avoid API calls being hit?

If I'm using RSpec for model specs and Capybara for integration, can I avoid Stripe or at least minimize hits?

retrieve card does not work

hey guys, looks like the retrieve method is looking inside the list,

customer = Stripe::Customer.retrieve(some_customer_id)
card = customer.cards.retrieve(customer.default_card)

returns

undefined method `retrieve' for #<Stripe::ListObject:0x007fab7d33b5c8>

temporally I'm using this in order to find the card information

card   = customer.cards.data.detect {|c| c[:id] == customer.default_card }

i thought a work around is to call the method directly from the Class https://github.com/stripe/stripe-ruby/blob/master/lib/stripe/card.rb
something like:

card = Stripe::Card.retrieve(customer.default_card)

but seems that the card class is not accessible neither,

so how can i edit a card address ?

Thanks in advance

Error calling API methods that don't take parameters

[9] pry(main)> i = Stripe::Invoice.retrieve('in_0QcOry1N475ytv')
[...]
[10] pry(main)> i.pay
NoMethodError: undefined method `each' for nil:NilClass
from /home/evan/stripe/stripe-ruby/lib/stripe/util.rb:76:in `flatten_params'

This is because the default value in Stripe.request for params is nil; it should probably be {} instead

Stripe 1.7.8 issue

Users/kap/.rbenv/versions/1.9.3-p286/lib/ruby/gems/1.9.1/gems/bundler-1.2.1/lib/bundler/rubygems_integration.rb:147:in `block in replace_gem': rest-client is not part of the bundle. Add it to Gemfile. (Gem::LoadError)
    from /Users/kapilisrani/.rbenv/versions/1.9.3-p286/lib/ruby/gems/1.9.1/gems/stripe-1.7.8/lib/stripe.rb:8:in `<top (required)>'
    from /Users/kapilisrani/.rbenv/versions/1.9.3-p286/lib/ruby/gems/1.9.1/gems/bundler-1.2.1/lib/bundler/runtime.rb:68:in `require'

no method cards for customer

I tried to get all cards from a customer, using that line from the documentation:

Stripe::Customer.retrieve("cu_2es53Mwr1No9mm").cards.all(:count => 3)

But I get this error.

NoMethodError - undefined method `cards' for #<Stripe::Customer:0x007fa6ad5de9a8>:
   () Users/xxx/.rbenv/versions/2.0.0-p247/lib/ruby/gems/2.0.0/bundler/gems/stripe-ruby-49724d755db7/lib/stripe/stripe_object.rb:157:in `method_missing'

I don't use Stripe.com but another service based on Stripe API, webpay.jp. Could it be the origin of the problem?

Upgrading from <= 1.6.2 to 1.6.3 breaks response processing

When creating a charge via Stripe::Charge.create, previously working code which handled the response broke when upgrading to 1.6.3 due to a change in response formatting. I assume such a breaking change a patch point release was unintentional and therefore a bug.

res = Stripe::Charge.create :amount => amount, :currency => 'usd', :card => stripe_token, :description => desc
res = res.as_json
if res.has_key? 'error' # Fails here
  # Do something with the error
else
  # Continue normally
end

Upon initial inspection, the issue appears to be due to the format of the JSON value in the response object returned by create. Examples formatted to illustrate these differences are below. Note that these example values from the reply were captured prior to the as_json call. Even though the example value from 1.6.3 appears to be a JSON object, calling as_json yields an array as illustrated in the 2nd pair of examples, suggesting another (possibly related) issue.

In 1.6.2

{
    "amount": 500,
    "amount_refunded": 0,
    "card": {
        "address_country": null,
        "address_line1": null,
        "address_line1_check": null,
        "address_line2": null,
        "address_state": null,
        "address_zip": null,
        "address_zip_check": null,
        "country": "US",
        "cvc_check": "pass",
        "exp_month": 5,
        "exp_year": 2020,
        "fingerprint": "7A89aFgCQUXHPXMX",
        "last4": "4242",
        "name": "Some User",
        "object": "card",
        "type": "Visa"
    },
    "created": 1336330256,
    "currency": "usd",
    "customer": null,
    "description": "order #20 for: [email protected]",
    "disputed": false,
    "failure_message": null,
    "fee": 45,
    "id": "ch_g6hd4p3mAiFlFz",
    "invoice": null,
    "livemode": false,
    "object": "charge",
    "paid": true,
    "refunded": false
}

In 1.6.3

{
    "amount": 500,
    "amount_refunded": 0,
    "card": [
        [
            "address_country",
            null
        ],
        [
            "address_line1",
            null
        ],
        [
            "address_line1_check",
            null
        ],
        [
            "address_line2",
            null
        ],
        [
            "address_state",
            null
        ],
        [
            "address_zip",
            null
        ],
        [
            "address_zip_check",
            null
        ],
        [
            "country",
            "US"
        ],
        [
            "cvc_check",
            "pass"
        ],
        [
            "exp_month",
            5
        ],
        [
            "exp_year",
            2020
        ],
        [
            "fingerprint",
            "7A89aFgCQUXHPXMX"
        ],
        [
            "last4",
            "4242"
        ],
        [
            "name",
            "Some User"
        ],
        [
            "object",
            "card"
        ],
        [
            "type",
            "Visa"
        ]
    ],
    "created": 1336329891,
    "currency": "usd",
    "customer": null,
    "description": "order #19 for: [email protected]",
    "disputed": false,
    "failure_message": null,
    "fee": 45,
    "id": "ch_Nw4PniwA214bwP",
    "invoice": null,
    "livemode": false,
    "object": "charge",
    "paid": true,
    "refunded": false
}

In 1.6.2 after calling as_json on res in the sample code

{"id"=>"ch_BcJay4zTA2vjrT",
 "amount"=>500,
 "amount_refunded"=>0,
 "created"=>1336331213,
 "currency"=>"usd",
 "customer"=>"null",
 "description"=>"order #21 for: [email protected]",
 "disputed"=>"false",
 "failure_message"=>"null",
 "fee"=>45,
 "invoice"=>"null",
 "livemode"=>"false",
 "object"=>"charge",
 "paid"=>"true",
 "refunded"=>"false",
 "card"=>
  {"address_country"=>"null",
   "address_line1"=>"null",
   "address_line1_check"=>"null",
   "address_line2"=>"null",
   "address_state"=>"null",
   "address_zip"=>"null",
   "address_zip_check"=>"null",
   "country"=>"US",
   "cvc_check"=>"pass",
   "exp_month"=>5,
   "exp_year"=>2020,
   "fingerprint"=>"7A89aFgCQUXHPXMX",
   "last4"=>"4242",
   "name"=>"Some User",
   "object"=>"card",
   "type"=>"Visa"}}

In 1.6.3 after calling as_json on res in the sample code

[["id", "ch_0634H0YZbg2Swv"],
 ["amount", 500],
 ["amount_refunded", 0],
 ["created", 1336329328],
 ["currency", "usd"],
 ["customer", "null"],
 ["description", "order #15 for: [email protected]"],
 ["disputed", "false"],
 ["failure_message", "null"],
 ["fee", 45],
 ["invoice", "null"],
 ["livemode", "false"],
 ["object", "charge"],
 ["paid", "true"],
 ["refunded", "false"],
 ["card",
  [["address_country", "null"],
   ["address_line1", "null"],
   ["address_line1_check", "null"],
   ["address_line2", "null"],
   ["address_state", "null"],
   ["address_zip", "null"],
   ["address_zip_check", "null"],
   ["country", "US"],
   ["cvc_check", "pass"],
   ["exp_month", 5],
   ["exp_year", 2020],
   ["fingerprint", "7A89aFgCQUXHPXMX"],
   ["last4", "4242"],
   ["name", "Some User"],
   ["object", "card"],
   ["type", "Visa"]]]]

Missing tags

As far as I can tell, none of the 1.6.x releases have been tagged.

Switch to MultiJSON

It'd be nice if the JSON processor were swappable. MultiJSON should provide that flexibility with a nice default parser available as a fallback.

Property deletion causes an error when setting nil to nil

I believe this pull request #82 has an undesired consequence.

If, for example, I am setting a coupon to nil on a customer and the customer has no coupon, I get an exception.

I don't think it should call out to delete the coupon if it is nil already--it should just act like there is no change.

What do you think?

cc/ @rheaton

Retrieve _all_ stripe customers

Currently, the all method paginates results. This is fine to decrease load on your API servers, but is not helpful in many cases.

Specifically, because you do not have a Search API, the only way around this is to fetch all customers and do searching manually.

Thus, I propose the addition of this method:

def all(pages)
  (0..pages).to_a.map do |index|
    Stripe::Customer.all(count: 100, offset: index*100)
  end.map(&:data).flatten
end

I wanted to make a PR, but when I tried to figure out where to add the method, it doesn't really fit anywhere. Maybe list.rb and then rename the function to all_pages or something... a bit awkward.

Anyway, feel free to close this issue if you don't like the idea of an all method, but I found it helpful for my uses.

Certain fields that can be missing cause StripeObjects to throw NoMethodError

I get this for instance:

NoMethodError: undefined method `description' for #<Stripe::Customer:0x17bb1518>

My guess is that customer was deleted and the description is now missing.
I can program defensively to prevent it from being raised (I am, atm) , but I'd rather have it solved by Stripe::Customer instead.

I can submit a pull req. if you guys want one. I'm just not sure how I should fix this.

Should I define a description method for Customer and call on super only if the value is present?
Should there be some kind of addition to StripeObject that defines a list of fields for which a nil must always be returned even if the field is not present?

Maybe the best thing to do is just make sure the API does return a nil field for description & others.

Stripe Connect: Staging Env or Programmatically Set Callback / Webhook Url

Many application setup have a localhost development, a staging env for testing and showing stakeholders, and production

Stripe connect provides two environment and one of them has to be under ssl. It would be nice to have one more environment or make the callback url a variable so we can show non developers the progress of our application.

Wrapping webhook params into stripe objects

Is it possible to take the values given to us in the event params object and wrap them in a properly type-casted stripe object?

I tried a simple invoice = Stripe::Invoice.new(params[:data][:object]) within an invoice.created event but it assigns all the values into the id field and doesn't typecast them.

All I'm trying to do is have the values type casted automatically. Perhaps there's a simpler solution I'm overlooking?

Whitespace fixups

The previous pull request introduced some whitespace inconsistencies. We should fix.

Add a to_hash function to StripeObject

It is a bit awkward working with StripeObjects right now. I can't loop through them, I can't do a lot of things I normally would do with a hash.

You might actually just want to make stripe object inherit hash.

undefined method `closed?'

This happens when using:

 customer = Stripe::Customer.create( :description => "description test",
                                                                   :email => "test email")

The error it gives out is this:
undefined method `closed?' for #Hash:0x007faf15d86c58

This happened when I started using prawn gem for creating pdf invoice (https://github.com/prawnpdf/prawn)

1.8.2 breaks when passing in an API key to a resource action

I recently upgraded to 1.8.2.It seems like a bug was introduced in this commit:

6b044e9

We pass the API key into each call to maintain clearly separate accounts with Stripe Connect. This commit breaks the BEARER authorization header when passing it in. It assumes it's set as a global class variable.

For example:

> Stripe::Plan.create({:id=>'test33', :amount=>1000, :currency=>"USD", :interval=>"month", :interval_count=>1, :name=>"Delete this plan"}, 'sk_test_gtgKmvg0HsQZj52US0S1bS3J')

Stripe::AuthenticationError: You did not provide an API key, though you did set your Authorization header to "Bearer". Using Bearer auth, your Authorization header should look something like 'Authorization: Bearer YOUR_SECRET_KEY'. See https://stripe.com/docs/api#authentication for details, or we can help at https://support.stripe.com/.
from .../gems/stripe-1.8.2/lib/stripe.rb:220:in `handle_api_error'

Here are some relevant code snippets. This sets the api key for the request method:

https://github.com/stripe/stripe-ruby/blob/master/lib/stripe.rb#L60

But when loading the request headers, it simply looks at the instance variable which is nil in our case.

https://github.com/stripe/stripe-ruby/blob/master/lib/stripe.rb#L171

Downgrading to 1.8.1 works for now. Let me know if you have any other questions.

(I also sent this to [email protected], but thought that this may be a better place for it.)

TypeError: wrong argument type JSON::Pure::Generator::State (expected Data)

Stripe::Event.retrieve('evt_gfhfCYH4XkbWSN')
TypeError: wrong argument type JSON::Pure::Generator::State (expected Data)
  from /path/to/ruby/gems/json_pure-1.7.3/lib/json/pure/generator.rb:316:in `to_json'
  from /path/to/ruby/gems/json_pure-1.7.3/lib/json/pure/generator.rb:316:in `block in json_transform'
  from /path/to/ruby/gems/json_pure-1.7.3/lib/json/pure/generator.rb:309:in `each'
  from /path/to/ruby/gems/json_pure-1.7.3/lib/json/pure/generator.rb:309:in `json_transform'
  from /path/to/ruby/gems/json_pure-1.7.3/lib/json/pure/generator.rb:291:in `to_json'
  from /path/to/ruby/gems/multi_json-1.3.6/lib/multi_json/adapters/json_common.rb:11:in `dump'
  from /path/to/ruby/gems/multi_json-1.3.6/lib/multi_json.rb:111:in `dump'
  from /path/to/ruby/gems/stripe-1.7.0/lib/stripe.rb:126:in `dump'
  from /path/to/ruby/gems/stripe-1.7.0/lib/stripe.rb:219:in `inspect'
  from /path/to/ruby/gems/railties-3.2.3/lib/rails/commands/console.rb:47:in `start'
  from /path/to/ruby/gems/railties-3.2.3/lib/rails/commands/console.rb:8:in `start'
  from /path/to/ruby/gems/railties-3.2.3/lib/rails/commands.rb:41:in `<top (required)>'

Unable to store last4 and card type using JSON From stripe customer creation

After creating a customer successfully, I can inspect the object with:

Rails.logger.debug("single card object has: #{customer.cards.data.card.inspect}")

which returns a json like this:

#<Stripe: : Customer: 0x2801284>JSON: {
    "id": "cus_2WXxmvhBJgSmNY",
    "object": "customer",
    "cards": {
      "object": "list",
        "data": [
           {
              "id": "card_2WXxcCsdY0Jjav",
               "object": "card",
               "last4": "4242",
               "type": "Visa",
               "exp_month": 1,
               "exp_year": 2014,
           }
        ]
           },
     "default_card": "card_2WXxcCsdY0Jjav"
 }

But I will do Customer.cards.data.last4 it gives a NOMethodError. Eg
NoMethodError (undefined method `last4' for #Array:0x00000003da45f0)

If I remove the last4 and just call Customer.cards.data, it gives

#<Stripe: : Card: 0x1ed7dc0>JSON: {
      "id": "card_2Wmd80yQ76XZKH",
       "object": "card",
       "last4": "4242",
       "type": "Visa",
       "exp_month": 1,
      "exp_year ": 2015,
 }

Now I seem to have the direct card object but if I do

   card =  Customer.cards.data
   self.last4 = card.last4

I still get a noMethodError

Here is shortened version of my model:

     class Payment < ActiveRecord::Base
         def create_customer_in_stripe(params)
             if self.user.stripe_card_token.blank?
               user_email = self.user.email
               customer = Stripe::Customer.create(email: user_email, card: params[:token])
               card  = customer.cards.data

               self.card_last4  = card.last4
               self.card_type = card.type
               self.card_exp_month = card.exp_month
               self.card_exp_year = card.exp_year
              self.user.save
          end
          self.save!
       end
    end

Lower the value of api request timeout

At the moment the open_timeout and timeout values are 30 and 80 respectively.

On heroku they have a hard timeout of 30seconds per request, so when Stripe times out it causes the request to fail ungracefully.

I suppose an alternative would be to allow users to specify their own timeout values?

Stripe ruby not compatible with older versions of rest-client

Hiya guys,

Stripe dies hard on making any request with older versions of rest client.

Tested:

rest-client 1.0.3 dies (no method error for body on RestClient::Response)
rest-client 1.6.1 works as expected

I didn't binary search the releases in between to find where it started working.

I forged the repo and put in an explicit version number for rest-client which would cause it to work for people. See my fork. I encourage you to pull it if you think that makes sense.

No sudo for gem install in README

Because most rubyists use rvm, rbenv or other version management systems, and some of these systems override original gem command, I suggest that you show gem install command without sudo in your README.

I think there are higher risks to cause errors or problems, if a guy runs sudo gem install stripe without knowing what he's actually doing by himself.

gemspec needs to be updated for file split

Our gemspec currently has

  s.files = %w{
    bin/stripe-console
    lib/stripe.rb
    lib/stripe/version.rb
    lib/data/ca-certificates.crt
  }

which results in...a gem distinctly lacking in code.

gems/activesupport-3.2.1/lib/active_support/core_ext/object/to_json.rb:15:in `to_json': wrong number of arguments (2 for 1) (ArgumentError)

The following causes an ArgumentError in 1.9.2:

require 'active_record'
require 'stripe'

ActiveRecord::Base.establish_connection('adapter' => 'postgresql', 'host' => 'localhost')
Stripe.api_key = "SNIP"
puts Stripe::Customer.all.inspect

/Users/briancollins/.rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.2.1/lib/active_support/core_ext/object/to_json.rb:15:in `to_json': wrong number of arguments (2 for 1) (ArgumentError)
from /Users/briancollins/.rvm/gems/ruby-1.9.2-p290/gems/stripe-1.6.2/lib/stripe.rb:216:in `to_json'
from /Users/briancollins/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/json/common.rb:270:in `generate'
from /Users/briancollins/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/json/common.rb:270:in `pretty_generate'
from /Users/briancollins/.rvm/gems/ruby-1.9.2-p290/gems/stripe-1.6.2/lib/stripe.rb:179:in `inspect'
from test.rb:7:in `<main>'

This monkey-patch "fixes":

module Stripe
  class StripeObject
    def to_json(*a)
      @values.to_json(*a)
    rescue ArgumentError
      @values.to_json
    end
  end
end

Gemspec is invalid

Complains about missing:

This prevents bundler from installing bins or native extensions, but that may not affect its functionality.
The validation message from Rubygems was:
["vendor/stripe-json/lib/json/pure.rb", "vendor/stripe-json/lib/json/common.rb", "vendor/stripe-json/lib/json/version.rb", "vendor/stripe-json/lib/json/pure/generator.rb", "vendor/stripe-json/lib/json/pure/parser.rb"] are not files

Singleton can't be dumped

cus = Stripe::Customer.retrieve("abcdef")
Marshal.dump(cus)     # TypeError: singleton can't be dumped

This prevents caching the returned objects with Rails.cache, for example. Potential solution would be to implement #marshal_load and #marshal_dump for the base class.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.