* Introduce types to ruby
* rubocop
* forgot these files
* other request methods
* more tests, fix for raw request
* Add README entry for types
* rebase and regen
* add justfile
* add just to ci and split out commands
* Fix justfile
* update readme and CI
* update justfile
* update CI
* update justfile import
* remove unused block
* added test for parsing v2 thin events with livemode and reason
* added attr_reader to ThinEvent for livemode and reason
* added EventReason and EventReasonRequest type to thin_event.rb
* Always return the result of .refresh in .retrieve
With the refactor of v13, there are now cases where `self` is not
mutated in the call to refresh and instead a new object is returned.
This change ensures that the new object is always returned by returning
the result of refresh instead.
* Update install instructions for stripe-mock
This fixes the typo of `mangers` to be `managers` in the documentation
for the `default_connection_managers` method on the `ThreadContext`
class in `lib/stripe/stripe_client.rb`.
Co-authored-by: prathmesh-stripe <165320323+prathmesh-stripe@users.noreply.github.com>
Conventionally `bin` folder is home to scripts that are meant to be run by developers working on the project, whereas the `exe` folder is used for executables that are meant to be exported by the gem.
The guidance from the Bundler team around this has been live since 2015: https://bundler.io/blog/2015/03/20/moving-bins-to-exe.html
This PR simplifies the gemspec and updates the `bin` folder to `exe` in the gemspec and removes some of the unnecessarily cleanup that was introduced previously.
When interpolating a Time object in a String, Ruby calls `to_s` under the hood.
For Rails applications defining a `default` string format, this triggers deprecation warnings as of v7.0.7: https://github.com/rails/rails/pull/48555
This change fixes that by explicitly formatting the timestamp (using the same `YYYY-MM-DD HH:mm:ss` format currently implicitly used).
* Add response field to RequestEndEvent
* Add request body field to RequestEventEnd
* Add request headers field to RequestEventEnd
* Create a RequestContext class
* Create a ResponseContext class
* Update tests
We have user feedback on the lack of clarity around whether or not we maintain and improve older major versions of the SDK. This PR adds a support section clarifying this
This change aims to reduce the packed gem size by removing needless files from `s.files`.
Also, `s.test_files` is also removed because it is not defined in the gemspec reference.
(see <https://guides.rubygems.org/specification-reference/>)
- Size changed: 215K -> 264K
- Files changed: 221 files -> 120 files
This is just a cosmetic change that renames `Stripe.configuration` to
just `Stripe.config`. We use the shorter "config" in most other places
including `StripeClient#config`, so I feel that this is overall more
consistent.
This change is backwards compatible because the new accessor came in
with #968, and that hasn't been given a formal release yet.
I've left the class name as `StripeConfiguration` which IMO is fine. The
class uses the expanded form of the name while vars and accessors use
the shorter `config`. Also, `StripeConfiguration` has been around a
little bit longer, so renaming it is somewhat backwards incompatible
too.
Follows up #968.
As a relic from when we had global configuration, anytime any config
value is changed on any client, we still clear all connection managers
everywhere on every thread, even though this is not necessary. This
means that we lose all open connections, etc.
Here, we make changes so that if a configuration is changed, we only
clear the configuration managers pertaining to that one particular
configuration, thus conserving resources globally.
Co-authored-by: Brandur <brandur@brandur.org>
When populating `StripeObject`s, we add accessors to them so that people
can access fields like `obj.currency`.
This was probably only meant to apply to API resources, but through
what might have been an accident of history, we've also traditionally
unmarshaled any hash that comes back from the API as a `StripeObject`,
including `metadata` fields. This allows some convenience because users
can access values like `obj.metadata.my_field`, but is also obviously a
minefield for potential problems.
In issue #969, what's essentially happening is that because there's a
metadata field named `class`, we've overwritten the object's normal
`class` method with our own custom one that accesses the metadata value.
Amazingly, the object can still marshal/unmarshal mostly properly, but
fails on this line as we try to access `obj.class` and that turns out to
be a metadata value instead of a class:
``` ruby
when StripeObject
obj.class.construct_from(
...
```
Here I solve the problem by banning accessors added with the name
`class`. This has a slight risk of backward incompatibility in that
users that previously had metadata named "class" will now have to use
square bracket accessors instead like `obj.metadata[:class]`, but
honestly, I just can't see anything good in allowing "class" to be used
as an accessor.
An alternative solution might be to alias `class` in `StripeObject` and
then make sure we always use that in places like `initialize_from` and
`deep_copy`.
The best long term solution would be to stop add accessors to metadata
objects. This just seems like a bad idea given that there are still
myriads of Ruby built-ins that could potentially be overwritten. This is
definitely a considerably-sized breaking change though, so we'd have to
do it on a major.
This changes allows for each instance of StripeClient to have its own
configuration object instead of relying on the global config. Each
instance can be configured to override any global config values
previously set.
`Customer#delete_discount` has been broken for some time in that it
tries to re-initialize `self` (which is a customer) with a received
discount response. This is incorrect and leads to various problems.
Here, we redefine the return value of `delete_discount` as a discount,
and have it no longer mutate the object on which is was called. We add a
comment as well just to help flag some of the behavior which could
potentially be confusing.
Fixes#963.
* Codegen for openapi 474461f
* Add and fix tests for the latest stripe-mock
Some of the tests had to be changed/mocked because stripe-mock has a bug
where the includable sub-lists it returns have the wrong url set.
Because of this, when you call create/list/etc. on one of those sub-lists
the calls fails due to that URL being incorrect.
Moved one test to use charge+refund (auto-expanded) and another used a
mock to have the right URL returned.
Adds a `Stripe::StripeConfiguration` object to manage internal and user
supplied configuration options.
This is primarily motivated by #921 in order to provide a way to set
options on for an instance of `StripeClient`.
As seen in #928, the `refresh` method doesn't work for an event class.
This is because event has a field called `request`, and it ends up
replacing the `request` method that it inherited from being an API
resource, so when `refresh` tries to make a request, it fails because it
tries to invoke it on the accessor added for the event's property.
Here we give `request` a much more unique name so that it will never
conflict with a property field again, and update all internal references
to use the new name. We use `alias` to make the old name available for
backwards compatibility reasons because its been around for so long that
people are probably calling it.
Fixes#928.
The params for AccountLink changed in `v0.93.0`, which will cause the
test suite to fail unless `stripe-mock` is pinned to an earlier version.
Fixes#934
Adds a new `generate_header` method for the webhooks module, following
up #915. This method doesn't help in any way with webhook verification,
but may be useful to users in their test suites as it allows them to
easily simulate the contents of a header that Stripe might have sent.
We briefly discussed an alternative design here, but this one seems like
the best fit:
https://github.com/stripe/stripe-ruby/pull/915#issuecomment-620164654
Exposes the `.compute_signature` method, which may be useful when
testing webhook signing in test suites.
I change the API slightly so that a caller isn't forced to do as much
string mangling, and to match the one that we already have in stripe-go:
``` go
func ComputeSignature(t time.Time, payload []byte, secret string) []byte {
```
Add basic documentation and test case. I also change a few things around
so that we send `Time` objects around more often where applicable, and
don't change then to Unix integers until the last moment that we need
to.
The one other alternative API I considered is this one, which would
default the timestamp to the current time to allow the method to be
called with one fewer arg:
``` ruby
def self.compute_signature(payload, secret: timestamp: Time.now)
```
I decided against it in the end though because it does remove some
explicitness, and it's not a big deal to just pass in `Time.now`,
especially given that this is not expected to be a commonly used method.
Fixes#912.
Minor changes that locks us on the 2.0.0 release candidate for
`shoulda-context`. This makes almost no difference to our test suite
except that it removes a long-standing warning for an assigned but
unused variable (which is our last warning!).
See more context here:
https://github.com/thoughtbot/shoulda-context/issues/57#issuecomment-610702695
Co-authored-by: Brandur <brandur@brandur.org>
Adds an easy accessor on `StripeError` which indicates whether the error
occurred previously, but was replayed on this request because the user
passed the same idempotency key as that original request.
Fixes#905.
Adds a new instrumentation callback called `request_begin` which, as the
name suggests, is invoked before an HTTP request is dispatched. As
outlined originally in #900, the idea is that this will enable a set of
hooks that can be used for distributed tracing.
The PR also renames the existing `request` callback to `request_end`,
although the old name is still invoked for the time being for backwards
compatibility.
A special `user_data` property is passed to `request_begin` which allows
subscribers to set custom data that will be passed through to
`request_end` for any given request. This allows, for example, a user
assigned ID to be set for the request and recognized on both ends.
I chose the naming `_begin` and `_end` (as opposed to start/finish or
any other combination) based on the naming conventions of Ruby itself.
Fixes#900.
Bumps the minimum version of webmock to 3.8.0 which contains a fix for a
Ruby 2.7 warning. This last change makes the whole project completely
warning-free!
Co-authored-by: Brandur <brandur@brandur.org>
I just noticed while running tests that we produce some accidental
output because both of `Source#source_transactions` and
`SubscriptionItem#usage_record_summaries` are considered deprecated and
have warnings attached.
Here we capture output to `$stderr` and assert on it from the test cases
that call these deprecated methods -- this pattern is already well
established elsewhere in the test suite.
Basically went through trying to make the whole stripe-ruby test run
Ruby 2.7 friendly. @dennisvdvliet got most of the internal stuff, but we
still have a couple external dependencies that are producing warning.
Here we upgrade Rubocop to 0.79, which curbs some warnings. A few lints
were moved and/or renamed, so I've modified the `.rubocop.yml`
appropriately, but there's no major changes there.
The last broken dependency is Webmock, and luckily I think it's pretty
easy to fix, so I'll send them a PR and see what happens.
* Add simple instrumentation callback
We used to insert Faraday::Request::Instrumentation into our Faraday middleware
stack to be able to instrument Stripe calls with StatsD. With Faraday being
removed in version 5, this required some rework. This commit implements a simple
callback system that can be used with any kind of instrumentation system.
* Add a topic to Stripe::Instrumentation notifications
... and a :request topic to subscribe to
* Use a RequestEvent value object instead of positional args in callback
This way the RequestLogContext object doesn't get exposed externally. Since the
same value object can be received by multiple subscribers it is frozen to
prevent accidental mutations across threads.
* Relocate tests for instrumentation and add more tests
There are two kinds of API operations: collection and element specific.
The signature between the two is slightly different:
- **collection**: (params, opts)
- **element specific**: (id, params, opts)
If a user doesn't realize the difference, they may attempt to use the
collection signature when performing an element specific operation like:
```
Stripe::PaymentIntent.cancel('pi_1234', 'sk_test_key')
# Results in an error: NoMethodError: undefined method `key?' for "sk_test"
```
The resulting error message isn't very useful for debugging.
Instead,this PR adds a message letting the user know what it's expecting:
`request params should be either a Hash or nil (was a String)`
* Support backwards pagination with list's `#auto_paging_each`
Previously, `#auto_paging_each` would always try to paginate forward,
even if it was clear based on the list's current filters that the user
had been intending to iterate backwards by specifying an `ending_before`
filter exclusively.
Here we implement backwards iteration by detecting this condition,
reversing the current list data, and making new requests for the
previous page (instead of the next one) as needed, which allows the user
to handle elements in reverse logical order.
Reversing the current page's list is intended as a minor user feature,
but may possibly be contentious. For background, when backwards
iterating in the API, results are still returned in "normal" order. So
if I specifying `ending_before=7`, the next page would look like `[4, 5,
6`] instead of `[6, 5, 4]`. In `#auto_paging_each` I reverse it to `[6,
5, 4]` so it feels to the user like they're handling elements in the
order they're iterating, which I think is okay. The reason it might be
contentious though is that it could be a tad confusing to someone who
already understands the normal `ending_before` ordering in the API.
Fixes#864.
* Allow `ending_before` and `starting_after` to remain in hydrated list object
Previously, if you specified a non-nil non-string opt value, like a
symbol for `idempotency_key`, you'd get a pretty user-unfriendly error
from `Net::HTTP`:
```
/Users/brandur/.rbenv/versions/2.4.5/lib/ruby/2.4.0/net/http/header.rb:21:in `block in initialize_http_header': undefined method `strip' for :foo:Symbol (NoMethodError)
```
Here, we introduce a new argument error that makes it a little easier
for someone to read. The impetus for the change is that we had an
internal product quality report where someone ran into this and was
confused.
I'm pretty sure this change is backward compatible because `Net::HTTP`
would call `strip` on anything that was passed in as a value, and
generally just strings would support that. There may be some other less
common data type that was accidentally compatible that someone was
using, but that case should be quite unusual.
One thing I tend to do a lot is create little test scripts to help debug
or reproduce problems with stripe-ruby. The problem is that they get
picked up by Rubocop, produce a whole bunch of errors, and then make it
more difficult if my changes to actual library files are producing
problems.
Here I exclude these by introducing a convention for having them start
with `example_*`. This isn't particularly great, but will work.
If #857 comes in, it turns out that we don't need Timecop anymore (it
doesn't freeze the monotic clock, so I had to find another way) -- here
we remove all mentions of it and drop the dependency.
I don't find it causes too much trouble so I'm not against bringing it
back in the future if we need it again, but it seems good for project
cleanliness to take it out for now.
Drops the use of `Time.now` in favor of using the system's monotonic
clock for various operations that calculate and use elapsed duration.
The latter is preferable because in some cases `Time.now` can be
unstable, like if it's set manually by a system administrator or an NTP
daemon.
I don't expect that the previous code would actually have caused trouble
in the vast majority of normal situations, so I'm not going to backport
anything, but this seems like good hygiene.
For better or worse I had to wrap the monotonic time calls in a new
`Util` function because (1) the normal invocation is long enough to have
caused a lot of overruns on our 80 character line lengths, and (2)
Timecop doesn't stub the monotonic clock, so the `Util` method gives us
a nice place that we can stub on where necessary.
As seen in stripe-node, adds support for the `Stripe-Should-Retry`
header which is sent by the API when it explicitly would like us to
either retry or _not_ retry.
I'll add `Retry-After` separately at some point, but I punted it on it
for now given that we're not using it yet.
See: https://github.com/stripe/stripe-node/pull/692
Introduces a system for garbage collecting connection managers in an
attempt to solve #850.
Previously, the number of connection managers (and by extension the
number of connections that they were holding) would stay stable if a
program used a stable number of threads. However, if threads were used
disposably, the number of active connection managers out there could
continue to grow unchecked, and each of those could be holding one or
more dead connections which are no longer open, but still holding a file
descriptor waiting to be unlinked in disposed of by Ruby's GC.
This PR introduces a connection manager garbage collector that runs
periodically whenever a new connection manager is created. Connection
managers get a timestamp to indicate when they were last used, and the
GC runs through each one and prunes any that haven't seen use within a
certain threshold (currently, 120 seconds). This should have the effect
of removing connection managers as they're not needed anymore, and thus
resolving the socket leakage seen in #850.
I had to make a couple implementation tweaks to get this working
correctly. Namely:
* The `StripeClient` class now tracks thread contexts instead of
connection managers. This is so that when we're disposing of a
connection manager, we can set `default_connection_manager` on its
parent thread context to `nil` so that it's not still tracking a
connection manager that we're trying to get rid of.
* `StripeClient` instances can still be instantiated as before, but no
longer internalize a reference to their own connection manager,
instead falling back to the one in the current thread context. The
rationale is that when trying to dispose of a connection manager, we'd
also have to dispose of its reference in any outstanding
`StripeClient` instances that might still be tracking it, and that
starts to get a little unwieldy. I've left `#connection_manager` in
place for backwards compatibility, but marked it as deprecated.
Previously, we had quite a few error tests that were written like this:
``` ruby
begin
client.execute_request(:post, "/v1/charges")
rescue Stripe::InvalidRequestError => e
assert_equal(404, e.http_status)
assert_equal(true, e.json_body.is_a?(Hash))
end
```
The trouble with that pattern is that although they'll _usually_ work,
the test will incorrectly pass if no error at all is thrown because the
`rescue` never activates and therefore the assertions never run.
We change them to use `assert_raises` like so:
``` ruby
e = assert_raises Stripe::InvalidRequestError do
client.execute_request(:post, "/v1/charges")
end
assert_equal(404, e.http_status)
assert_equal(true, e.json_body.is_a?(Hash))
```
The weird part is that many of the tests were already using
`assert_raises`, so here we're just converting them all over to use the
same convention.
I've also made a few whitespace tweaks. None of them are significant,
but they were an attempt to standardize a little on the whitespace
layout of many of these tests which were similar.
Follows up #845 to make sure that this sort of regression is much more
difficult in the future by adding a test that makes sure a request ID is
threaded all the way from an HTTP response back through to an error
object. I verified that the test failed before #845 came in.
When requesting error#request_id it returned nil although the request id was available in the request headers. With version 5 and switch to Net::HTTP this value is now a string, not a symbol which means that the request_id was not stored on the error correctly.
Tweaks the retry logic so that 429s which have the special status code
lock_timeout are retried automatically.
Similar to what was recently implemented in Go: stripe/stripe-go#935
A tiny refactor where we extract the warning you get when setting SSL
verify mode to `VERIFY_NONE` into its own method. No real impetus for
this except that it extracts very nicely, and that gets us to a smaller
`create_connection` method.
One thing I forgot to look into was how long Ruby will hold a connection
open by default. It turns out that the language default is very low at
only two seconds. Here we increase it to 30 seconds, which is a more
reasonable default. I took this number from Go's `DefaultTransport`,
which seems to have been working pretty well so far.
I tested with a script that keeps a connection idle to Stripe for a long
period of time before issuing a new request and everything seems to be
working well.
* Convert library to use built-in `Net::HTTP`
Moves the library off of Faraday and over onto the standard library's
built-in `Net::HTTP` module. The upside of the transition is that we
break away from a few dependencies that have caused us a fair bit of
trouble in the past, the downside is that we need more of our own code
to do things (although surprisingly, not that much more).
The biggest new pieces are:
* `ConnectionManager`: A per-thread class that manages a connection to
each Stripe infrastructure URL (like `api.stripe.com`,
`connect.stripe.com`, etc.) so that we can reuse them between
requests. It's also responsible for setting up and configuring new
`Net::HTTP` connections, which is a little more heavyweight
code-wise compared to other libraries. All of this could have lived in
`StripeClient`, but I extracted it because that class has gotten so
big.
* `MultipartEncoder`: A class that does multipart form encoding for file
uploads. Unfortunately, Ruby doesn't bundle anything like this. I
built this by referencing the Go implementation because the original
RFC is not very detailed or well-written. I also made sure that it was
behaving similarly to our other custom implementations like
stripe-node, and that it can really upload a file outside the test
suite.
There's some risk here in that it's easy to miss something across one of
these big transitions. I've tried to test out various error cases
through tests, but also by leaving scripts running as I terminate my
network connection and bring it back. That said, we'd certainly release
on a major version bump because some of the interface (like setting
`Stripe.default_client`) changes.
* Drop support for old versions of Ruby
Drops support for Ruby 2.1 (EOL March 31, 2017) and 2.2 (EOL March 31,
2018). They're removed from `.travis.yml` and the gemspec and RuboCop
configuration have also been updated to the new lower bound.
Most of the diff here are minor updates to styling as required by
RuboCop:
* String literals are frozen by default, so the `.freeze` we had
everywhere is now considered redundant.
* We can now use Ruby 1.9 style hash syntax with string keys like `{
"foo": "bar" }`.
* Converted a few heredocs over to use squiggly (leading whitespace
removed) syntax.
As discussed in Slack, I didn't drop support for Ruby 2.3 (EOL March 31,
2019) as we still have quite a few users on it. As far as I know
dropping it doesn't get us access to any major syntax improvements or
anything, so it's probably not a big deal.
* Make `CardError`'s `code` parameter named instead of positional (#816)
Makes the `code` parameter on `CardError` named instead of positional.
This makes it more consistent with the rest of the constructor's
parameters and makes instantiating `CardError` from `StripeClient`
cleaner.
This is a minor breaking change so we're aiming to release it for the
next major version of stripe-ruby.
* Bump Rubocop to latest version (#818)
* Ruby minimum version increase followup (#819)
* Remove old deprecated methods (#820)
* Remove all alias for list methods (#823)
* Remove UsageRecord.create method (#826)
* Remove IssuerFraudRecord (#827)
* Add ErrorObject to StripeError exceptions (#811)
* Tweak retry logic to be a little more like stripe-node (#828)
Tweaks the retry logic to be a little more like stripe-node's. In
particular, we also retry under these conditions:
* If we receive a 500 on a non-`POST` request.
* If we receive a 503.
I made it slightly different from stripe-node which checks for a 500
with `>= 500`. I don't really like that -- if we want to retry specific
status codes we should be explicit about it.
We're actively re-examining ways on how to make it easier for clients to
figure out when to retry right now, but I figure V5 is a good time to
tweak this because the modifications change the method signature of
`should_retry?` slightly, and it's technically a public method.
* Fix inverted sign for 500 retries (#830)
I messed up in #828 by (1) accidentally flipping the comparison against
`:post` when checking whether to retry on 500, and (2) forgetting to
write new tests for the condition, which is how (1) got through.
This patch fixes both those problems.
* Remove a few more very old deprecated methods (#831)
I noticed that we had a couple of other deprecated methods on `Stripe`
and `StripeObject` that have been around for a long time. May as well
get rid of them too -- luckily they were using `Gem::Deprecate` so
they've been producing annoying deprecated warnings for quite a while
now.
* Remove extraneous slash at the end of the line
* Reset connections when connection-changing configuration changes (#829)
Adds a few basic features around connection and connection manager
management:
* `clear` on connection manager, which calls `finish` on each active
connection and then disposes of it.
* A centralized cross-thread tracking system for connection managers in
`StripeClient` and `clear_all_connection_managers` which clears all
known connection managers across all threads in a thread-safe way.
The addition of these allow us to modify the implementation of some of
our configuration on `Stripe` so that it can reset all currently open
connections when its value changes.
This fixes a currently problem with the library whereby certain
configuration must be set before the first request or it remains fixed
on any open connections. For example, if `Stripe.proxy` is set after a
request is made from the library, it has no effect because the proxy
must have been set when the connection was originally being initialized.
The impetus for getting this out is that I noticed that we will need
this internally in a few places when we're upgrading to stripe-ruby V5.
Those spots used to be able to hack around the unavailability of this
feature by just accessing the Faraday connection directly and resetting
state on it, but in V5 `StripeClient#conn` is gone, and that's no longer
possible.
* Minor cleanup in `StripeClient` (#832)
I ended up having to relax the maximum method line length in a few
previous PRs, so I wanted to try one more cleanup pass in
`execute_request` to see if I could get it back at all.
The answer was "not by much" (without reducing clarity), but I found a
few places that could be tweaked. Unfortunately, ~50 lines is probably
the "right" length for this method in that you _could_ extract it
further, but you'd end up passing huge amounts of state all over the
place in method parameters, and it really wouldn't look that good.
* Do better bookkeeping when tracking state in `Thread.current` (#833)
This is largely just another cleanup patch, but does a couple main
things:
* Hoists the `last_response` value into thread state. This is a very
minor nicety, but effectively makes `StripeClient` fully thread-safe,
which seems like a minor nicety. Two calls to `#request` to the same
`StripeObject` can now be executed on two different threads and their
results won't interfere with each other.
* Moves state off one-off `Thread.current` keys and into a single one
for the whole client which stores a new simple type of record called
`ThreadContext`. Again, this doesn't change much, but adds some minor
type safety and lets us document each field we expect to have in a
thread's context.
* Add Invoice.list_upcoming_line_items method (#834)
Raises a slightly more helpful error message when passing a non-string
to a custom method (currently, it reads "no implicit conversion of Hash
into String", which is terrible).
This a partial remediation for the problem encountered in #809.
* Revert "Use Util.convert_to_stripe_object instead of initialize_from"
This reverts commit ea736eba1b8f33d8febbf0b1be0957f34f7b04db.
* Make SetupIntents use initialize_from instead of Util.convert_to_stripe_object
* Fix issuing card details, which must have been broken prior to ea736eb
Add space at the end of the second line so the complete message separates the word `not` and `working`
message before
```
Stripe::APIConnectionError: Unexpected error communicating when trying to connect to Stripe. You may be seeing this message because your DNS is notworking. To check, try running `host stripe.com` from the command line.
```
message after
```
Stripe::APIConnectionError: Unexpected error communicating when trying to connect to Stripe. You may be seeing this message because your DNS is not working. To check, try running `host stripe.com` from the command line.
```
* Bump Rubocop to 0.57.2
* Style/StderrPuts: Use warn instead of .puts
* Style/ExpandPathArguments: Use expand_path('../test_helper', __dir__) instead of expand_path('../../test_helper', __FILE__)
* Style/Encoding: Unnecessary utf-8 encoding comment
* Style/StringLiterals: Prefer double-quoted strings
* Style/AccessModifierDeclarations
* Style/FormatStringToken: Prefer annotated tokens
* Naming/UncommunicativeMethodParamName
* Metrics/LineLength: set maximum line length to 100 characters
* Style/IfUnlessModifier: Favor modifier if usage when having a single-line body
* Style/ClassVars
* Metrics/LineLength: set maximum line length to 80 characters (default)
* Style/AccessModifierDeclarations: EnforcedStyle: inline
When uploading a file, we previously made a check on whether it
supported both `#read` and `#path` before wrapping it in a
`Faraday::UploadIO` and sending it off. The second check on `#path`
isn't strictly necessary, and as reported in #761 can prevent objects
created by `open-uri` from being compatible with file upload.
Here we remove the check `#path` so that we just require that objects
support `#read`, and in addition error when an object is passed that's
not file-compatible and not a string. This should prevent users from
seeing the very confusing "Invalid hash" error in these situations.
Fixes#761.
In some cases there can be a method that's detected with
`method_defined?`, but which cannot be removed with `remove_method`,
even though it's on the same class. The only case so far that we've
noticed this is when a class is reopened for monkey patching like in
issue #749.
We'll still try to discourage this sort of use, but here we swallow the
error and issue a warning so at least the program doesn't crash.
Fixes#749.
In #741 I tried to do something too clever by replacing instances of
`Faraday::UploadIO` found in parameters with a human-readable string to
improve `STRIPE_LOG` logging output.
I thought I'd tested it at the time, but apparently not (or not well
enough), and this change caused the regression detailed in #742.
My findings about how Faraday encodes multipart were apparently wrong
and it does use these parameters, so here we remove the step where we
try to nicen them for logging. The logs look a little worse, but it's
not that big of a deal.
I've tested this patch against the API and confirmed that it addresses
the problem.
Fixes#742.
Makes a few tweaks to hopefully simplify clarity things:
* `FaradayStripeEncoder` now becomes the way to encode all of form,
multipart form, and query parameters.
* Introduce a cache in it so that we don't have to encode everything
twice (once for logging, and once for the request body).
* Try to sanitize logging a bit by replacing `Faraday::UploadIO`s found
in incoming parameters with a string representation of the file (note
that all other styles of file input like `File` or `Tempfile` have
been converted to `Faraday::UploadIO` by the time they reach the
encoder).
As reported in #608, integer-indexed maps currently work when passed as
part of the body, but they are reverted to non-indexed maps when passed
in the query.
It turns out that we actually had two problems:
1. We weren't calling our `Util.encode_parameters` on our query
parameters anywhere, and it's this method will does the integer
encoding.
2. Even when I fixed (1) by calling `Util.encode_parameters`, Faraday
would still strip the integer indexes as they were transformed in
its default `NestedParamsEncoder`.
Here we fix both issues by calling `Util.encode_parameters` and sending
Faraday a custom encoder which bypasses its normal shenanigans.
Unfortunately, this has turned out to be somewhat difficult to test
because the integer-indexed maps also seem to confuse Webmock, which
strips them down to standard maps (I even tried testing against a
string, and it still got it wrong). I did use stripe-mock though to
verify that we are now sending the right payload.
Fixes#608.
A tiny tweak to add the port chosen by stripe-mock to the "starting
stripe-mock" output. This gives the user a little more information
(which might be handy if something isn't working), and brings it inline
with Go's output format: https://github.com/stripe/stripe-go/pull/780
When starting a stripe-mock for a custom OpenAPI spec, pass `-http-port
0` on startup, which tells stripe-mock to select a port, then extract
that port from its output.
This is not a total win because we now have to rely on string matching,
but it is better in that (1) it gets a port more efficiently, (2) it
eliminates a race condition where another process could take the port we
found before stripe-mock gets to start, and (3) it starts a little
faster as we take advantage of the fact that we know stripe-mock has
started when we've found a port in its output (in my tests it took ~0.2
to 0.3 seconds compared to a 1 second sleep).
Connect with Express accounts uses a slightly different version of the
OAuth authorize URL [1] in that it's prefixed with `/express`.
Here we add a new option to `Stripe::OAuth.authorize_url` which allows
`express: true` to be passed in to generate the Express variant.
Note that the token endpoint has no equivalent so we don't need the
option there.
Fixes#717.
[1] https://stripe.com/docs/connect/oauth-reference#express-account-differences
Tweaks telemetry implementation slightly to be inline with the recent
implementation in stripe-php. Telemetry isn't much good if a request ID
wasn't present, so we only send telemetry if it was.
This changes the library's default connection over to use the adapter
for `Net::HTTP::Persistent`, which is a connection pooling library for
Ruby.
In the long run, I think we should probably just drop Faraday ... the
amount of value it's getting us is extremely tenuous and its API is
difficult to work with. I hate to do it at this point though because
technically people could be writing custom middleware for it.
Overrides `#eql?` (hash equality) and `#hash` so that Stripe objects can
be used more easily as Hash keys and that certain other frameworks that
rely on these methods will have an easier time (e.g. RSpec's `change`,
see #687).
I think this might be a little controversial if we weren't already
overriding the `#==` implementation, but because we are, I think it
makes sense to extent it to these two methods as well.
I was testing with a new version of stripe-mock and it caught a few
problems with query parameter validation on. This patch contains some
minor fixes to address them.
Changes all arrays from classic Rack encoding:
``` sh
arr[]=...&arr[]=...&arr[]=...
```
To integer-indexed encoding:
``` sh
arr[0]=...&arr[1]=...&arr[2]=...
```
We think that this should be tractable now that we've fully converted
all endpoints over to the new AbstractAPIMethod infrastructure on the
backend (although we should do a little more testing to make sure that
all endpoints still work).
As part of the conversion, we also remove any places that we were "spot
encoding" to get required integer-indexed syntax. This should now all be
built in.
Remi pointed out in #666 that we basically just have to keep adding more
more onto the `Max` exception for both these rules every time we add a
new API resource.
Here I suggest that we modify the check on method length in two ways:
1. Permanently disable the cop on `Util.object_classes`. This is just
going to keep growing until we change are approach to it.
2. Choose a more reasonable maximum of 50 lines for elsewhere (IMO, the
default of 10 is just too short). Most of our methods already come in
below this, but there's a couple outliers like `#execute_request` in
`StripeClient`. If we knock over some of those, we could lower this
number again, but I suspect that we'd probably want somewhere closer
to 30 (instead of 10) event then.
I also disable the check on module length completely. I'm not convinced
this is a very good heuristic for code quality.
This changes the predicate supplied to the #colorize method to ensure
that if a logger is set, the colorizing ANSI escape codes are not applied.
This definitely appears to have been the intention behind the original
implementation, but the tests didn't reflect how .log_internal was
actually called. In reality, it is always supplied with an `out:`
argument, not nil. This caused all logger bound output to also be
colorized.
Adds Ruby 2.5 to the test matrix.
I also switched us over to aliases of each major Ruby version because I
think it makes more sense to be locked to whatever the latest release in
each is.
I found a bug recently in stripe-mock which causes it not to actually be
validating that parameters not in the spec are not being sent (the
actual Stripe API does check for this).
After applying a fix, I found that stripe-ruby's test suite no longer
passes against it, and the reason is that there are some subtle mistakes
throughout. This patch corrects them to be in line with what the API
actually expects.
Adds the magic `frozen_string_literal: true` comment to every file and
enables a Rubocop rule to make sure that it's always going to be there
going forward as well.
See here for more background [1], but the basic idea is that unlike many
other languages, static strings in code are mutable by default. This has
since been acknowledged as not a particularly good idea, and the
intention is to rectify the mistake when Ruby 3 comes out, where all
string literals will be frozen. The `frozen_string_literal` magic
comment was introduced in Ruby 2.3 as a way of easing the transition,
and allows libraries and projects to freeze their literals in advance.
I don't think this is breaking in any way: it's possible that users
might've been pulling out one of are literals somehow and mutating it,
but that would probably not have been useful for anything and would
certainly not be recommended, so I'm quite comfortable pushing this
change through as a minor version.
As discussed in #641.
[1] https://stackoverflow.com/a/37799399
If specifying both query parameters in a path/URL down to Faraday (e.g.,
`/v1/invoices/upcoming?coupon=25OFF`) _and_ query parameters in a hash
(e.g., `{ customer: "cus_123" }`), it will silently overwrite the ones
in the path with the ones in the hash. This can cause problems where
some critical parameters are discarded and causes an error, as seen in
issue #646.
This patch modifies `#execute_request` so that before going out to
Faraday we check whether the incoming path has query parameters. If it
does, we decode them and add them to our `query_params` hash so that
all parameters from either place are preserved.
Fixes#646.
I don't remember why I wrote this originally, but found it sitting
locally uncommitted. It seems like a useful example to have in the
README, so add it in.
`stripe-mock` can now respond accurately for file API endpoints thanks
to a few improvements in how it handles `multipart/form-data` payloads
and the OpenAPI spec.
Here we upgrade `stripe-mock` to 0.15.0 and remove the manual stubbing
that we had previously.
The most important changes here are that deleted objects are now
represented more accurately, and that IDs used in URLs are "reflected"
back into responses so that test suites can treat return objects a
little more realistically than they could before.
This should resolve incompatibilities between `stripe-ruby` and newer
versions of `stripe-mock`.
The test suite is currently throwing a bunch of warnings from some
recent changes I made -- although we initialize `@additive_params` when
setting one with `self.additive_object_param`, we don't when we check
one with `self.additive_object_param?`. This often isn't a problem
because every API resource sets `metadata`, but it is from the test
suite and probably for vanilla `StripeObject`s too.
So we have a bit of a problem right now when it comes to replacing a
`StripeObject` that's embedded in an API resource.
Most of the time when someone does this, they want to _replace_ an
object embedded in another object. Take setting a source on a
subscription for example:
``` ruby
subscription.source = {
object: 'card',
number: 123,
}
subscription.save
```
In the case above, the serialized parameters should come out as:
```
source[object]=card&source[number]=123
```
That should apply even if the previous source had something else set on
it which we're not going to set this time -- say an optional parameter
like `source[address_state]`. Those should not be present at all in the
final serialized parameters.
(Another example is setting a `payout_schedule` as seen in #631 which is
PR is intended to address.)
There is an exception to this rule in the form of metadata though.
Metadata is a bit of a strange case in that the API will treat it as
additive, so if we send `metadata[foo]`, that will set the `foo` key,
but it won't overwrite any other keys that were already present.
This is a problem because when a user fully sets `metadata` to a new
object in Ruby, what they're probably trying to do is _replace_ it
rather than add to it. For example:
``` ruby
subscription.metadata
=> { old: 'bar' }
subscription.metadata = {
new: 'baz'
}
subscription.save
```
To accomplish what the user is probably trying to do, we actually need
to send `metadata[old]=&metadata[new]=baz` so that we empty the value of
`old` while simultaneously setting `new` to `baz`.
In summary, metadata behaves different from other embedded objects in a
fairly fundamental way, and because the code is currently only set up to
handle the metadata case, it's not behaving correctly when other types
of objects are being set. A lot of the time emptying values like we do
for `metadata` is benign, but as we've seen in #631, sometimes it's not.
In this patch, I modify serialization to only empty out object values
when we see that parameter is `metadata`.
I'm really not crazy about the implementation here _at all_, but I'm
having trouble thinking of a better way to do it. One possibility is to
introduce a new class annotation like `empty_embedded_object :metadata`,
but that will have to go everywhere and might be error-prone in case
someone forgets it on a new resource type. If anyone has a suggestion
for an alternative (or can let me know if I'm missing something), I'd
love to hear it.
This PR is an alternate to #631.
A few weeks back a new error type `idempotency_error` was introduced in
the API. I put it in to respond to #503, but then forgot to add support
for it in this library. This patch introduces a new exception class that
represents it.
stripe-mock 0.4.0 comes with the up-to-date exchange rates API. Here we
bump the required version and remove the manual exchange rate stubbing
in stripe-ruby's test suite.
Makes the `operations` argument to `nested_resource_class_methods`
required and adds explicit lists to any invocations that were missing
one.
The impetus here is that I think it's more easily digestible if each
call site is explicit about what operations it supports and therefore
which methods it's about to create on the class.
Excludes `idempotency_key` from opts to persist between API requests.
Obviously the same idempotency key is not something that we ever want to
use again.
Fixes#598.
There's really no reason for these to have been two separate lists.
Also, add `uri` as an explicit dependency (so far it's been getting
included by luck with other libraries).
While converting this changelog over, I improperly added links that were
copied from stripe-dotnet. The numbers were right, but the links was
wrong because it was going to the wrong project. This patch corrects all
those bad links.
Converts `History.txt` to a Markdown-based changelog in the same style
as the one established in stripe-dotnet [1].
We leave `History.txt` in place with a reference to the new file so that
existing links will not be broken.
[1] https://github.com/stripe/stripe-dotnet/pull/1026
Backtracks a little bit #586 by bringing back custom `StripeObject`
encoding and decoding methods for Ruby's `Marshal`. These work by just
persisting values and some opts, and skipping everything else. It's
mostly the same as what we had before, but implemented a little more
cleanly so that we don't actually need to invoke `Marshal` anywhere
ourselves.
In #586 we still managed to remove all the uses of `Marshal` in our own
codebase to make the linter happy. Even though we wouldn't recommend the
use of `Marshal`, this code at least enables it for anyone using a Rails
cache or similar mechanism.
Addresses #90.
This patch modifies the debugging-level logging logic slightly so that
if it's a `GET` request that includes a query string, we log that string
just like we would've for a request body on a `POST` or like.
This especially comes in handy when looking when trying to resolve
something like a problem with the upcoming invoices endpoint like we saw
in #576, but will be useful in a number of situations.
We were previously using a bit of a hack to get a free deep copy
implementation through Ruby's marshaling framework. Lint call this out
as a security problem though, and rightfully so: when combined with
unsanitized user input, unmarshaling can result in very serious security
breaches involving arbitrary code execution.
This patch removes all uses of marshal/unmarshal in favor of
implementing a deep copy method for `StripeObject`. I also reworked some
of the constants around what keys are available for `opts`. I'm still
not completely happy with the results, but I think it's going to need a
slightly larger refactor in order to get somewhere truly good.
There is what could be a breaking change for people doing non-standard
stuff with the library: the opts that we copy with an object are now
whitelisted, so if they were being used to pass around extraneous data,
that might not work as expected anymore. But because this is a contract
that we never committed to, I don't think I'd bump the major version for
change.
Removes Rubocop TODO around guard clauses and fixes the outstanding
offenses.
This is starting to get into territory that feels of more dubious value
to me, but at least it did get me writing a couple more tests, so let's
see how it goes by keeping this on.
I wanted to see what fixing Rubocop TODOs was like, so I tried to
eliminate all the easy ones. Most of these were pretty easy, and the
changes required are relatively minimal.
Some of the stuff left is harder. Pretty much everything under
`Metrics/*` is going to be a pretty big yak shave. A few of the others
are just going to need a little more work (e.g. `Style/ClassVars` and
`Style/GuardClause`). Going to stop here for now.
Because we're a library, our `Gemfile.lock` is in `.gitinore` (see [1]).
This means that you'd be otherwise be vulnerable to the whims of
whatever version of Rubocop is installed on the local system.
Because Rubocop changes fairly quickly and those changes tend to lead to
either errors or warnings on its runs, lock the gem to a particular
version in our `Gemfile`. We should try to keep the locked version
relatively current.
[1] http://yehudakatz.com/2010/12/16/clarifying-the-roles-of-the-gemspec-and-gemfile/
A few changes:
* Add a new `Util.log_error` method which will forward to the equivalent
of `#error` on a logger.
* Move errors produced by `StripeClient` to use `Util.log_error`.
* Change standard stdout logging behavior to log to stderr in the case
of `Util.log_error.
* Change `Stripe.log_level` values to be an enum in a similar fashion as
the standard library's built in `Logger`.
Adds support for setting `Stripe.logger` to a logger that's compatible
with `Logger` from Ruby's standard library. In set, the library will no
longer log to stdout, and instead emit straight to the logger and defer
decision on what log level to print to it.
Addresses a request in #566.
Hopefully the last tweak in a while, but a discussion on [1] tipped me
off that this was missing. Here we add a `Stripe-Account` for a request
and response to logging. Follows #566 and #567.
[1] https://github.com/stripe/stripe-node/issues/364
This one is minor, but I realized after shipping #566 that it would be
nice if the number of retries was also logged for every request. This
patch follows up #566 by adding that in.
I also renamed `retry_count` to `num_retries` because I subjectively
think this name is a little better.
Adds logging support for stripe-ruby in a similar way that we did it for
stripe-python [1], with the idea that users you can optionally get some
additional low-cost-to-configure logging for operational visibility or
debugging.
I made a few tweaks from the Python implementation (which I'll try to
contribute back to there):
* Added an elapsed parameter to responses so you can tell how long they
lasted.
* Mixed in idempotency_key to all lines that users have a way to
aggregate logs related to a request from start to finish.
* Standardized naming between different log lines as much as possible.
* Detect a TTY and produce output that's colorized and formatted.
[1] https://github.com/stripe/stripe-python/pull/269
Moves away from Committee and towards stripe-mock, an external
self-contained executable API stub server based on OpenAPI [1]. The
motivation here is that instead of making stripe-ruby a special
snowflake, we can use a single well-tested and feature-rich mock
implementation to drive every API's test suite.
[1] https://github.com/stripe/stripe-mock
Currently, with a normal API resource, you can unset fields by
specifying a `nil` to that field's setter:
``` ruby
c = Charge.retrieve('ch_123')
c.customer = nil
c.save
```
This actually gets serialized as the form `customer=` (i.e. an empty
string), but we had to use the empty string to handle unsets because
form encoding has no concept of a `nil`/`null`.
To try and prevent usage errors, we actually prevent you from setting
fields with an empty string:
``` ruby
c = Charge.retrieve('ch_123')
c.customer = '' # error! use nil instead
```
When specifying parameters though, this doesn't work anywhere nearly as
well because usage patterns like this are very common in Ruby:
``` ruby
charge_opts = {
params[:amount],
params[:currency],
params[:customer],
}
charge = Charge.create(charge_opts)
```
Each one of `params` above may or may not be `nil`, so we've
traditionally filtered those fields out during the invocation of
`Charge.create`.
Recently, I suggested to Slava that we may be able to change this
behavior, and we ended up putting in a patch as part of #557. Users
brought to my attention that this would be far too disruptive of a
change in #560 though, and having thought about it more carefully, I
agree. There's also an argument that filtered `nil` values are just a
better API, especially in Ruby where patterns like the one above are
frequently in effect.
So the best thing I can think of currently is to leave things as they
were before #557, and just require that users use an explicit empty
string when passes in parameter hashes:
``` ruby
Charge.update(customer: '') # will try to unset customer
```
Empty strings will continue to error for `StripeObject` fields like they
always have.
I don't think this is a perfect solution by any means (the different
between values on `StripeObject` versus using parameters is weird), but
it's the least disruptive thing that I can think of right now that gets
us the functionality that we need for endpoints like
`/v1/invoices/upcoming`.
Fixes#560.
It was brought up in #562 that in case we receive an OAuth error that we
don't know about, `specific_oauth_error` will fall through with a `nil`,
then picked up by `specific_api_error` which will always try to handle
the error as if it were a `Hash` (even if we know it's not!) and thus
lead to typing problems at runtime.
This patch throws a generic `OAuthError` in cases where a code comes
back that we don't recognize. I'm still crazy about the fact that we
don't have a better way of recognizing an OAuth error in particular, but
it should do the trick.
An error in OAuth deauthorization could return the error code of
`invalid_client`, but that isn't handled by the code. That leads to a
`TypeError` instead of a clean, understandable error.
Tweaks the serialization behavior so that when a resource is explicitly
set to a resource's field and that resource is subsequently saved, then
if it looks like the set resource was persisted we extract its ID and
send it up to the API.
By slight extension we also throw an `ArgumentError` if it looks like
that set resource was _not_ persisted because if the user set it
explicitly then it was probably not their intention to have it silently
ignored by the library in the event of a problem.
Redefining the constant like this produces a warning:
```
$ bundle exec rake
/Users/brandur/stripe/stripe-ruby/test/stripe/ephemeral_key_test.rb:75: warning: already initialized constant Stripe::EphemeralKeyTest::FIXTURE
/Users/brandur/stripe/stripe-ruby/test/stripe/ephemeral_key_test.rb:6: warning: previous definition of FIXTURE was here
Loaded suite /Users/brandur/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/rake-11.1.2/lib/rake/rake_test_loader
Started
...
```
They also don't appear to be used, so it should be fine just to strip
them out of the test suite.
Timeouts are about to come to stripe-java [1], so for consistency we
mirror the README section that we're going to be adding over there.
[1] https://github.com/stripe/stripe-java/pull/369
This doesn't come back directly from the API so the suite is empty, but
just for completeness add a test file for the newly created
`InvoiceLineItem` model.
Adds support for "app info" (a mechanism that allows a plugin's author
to identify that plugin) in Ruby. This is already supported in PHP and
we're adding it elsewhere.
Previously, the value of whatever accessor was missing was left out of
the call to build it. This had the effect of skipping over the
lazily-built predicate method when the missing accessor is for a
boolean.
Of course, I realize this all is a bit contrived as most of the time
folks aren't assigning these values manually to stripe objects. However,
in my testing it caught me by surprised that the behavior is asymmetric
depending on how and when values are assigned.
As such I believe this is a less surprising implementation.
The Transfer object used to represent all movements of funds in Stripe. It
split in three resources:
- Transfer: this describes the movement of funds between Stripe accounts
and is specific to Stripe Connect.
- Payout: this describes the movement of funds from a Stripe account to a
bank account, debit card or any future payout method.
- RecipientTransfer: this describes the movement of funds from a Stripe
account to a Recipient's card or Bank Account. This is here for legacy
reasons and can only be accessed from an expanded BalanceTransaction.
This change is behind an API version so old API versions would still use
the Transfer object for everything while new API version would see the
split.
This applies beyond the new object as some properties/methods are removed
from Transfer and other properties are renamed on other objects.
See [1] for details, but a few conventions changed around the structure
of the OpenAPI repository and the data within the fixtures file. Here we
put in some minor changes to compensate for them.
[1] https://github.com/stripe/openapi/pull/3
The Faraday::Response object does not respond to #code. The correct
message is #status. It seems this case was previously unhandled by the
test suite as there was no case for the server responding "success" with
an invalid JSON body.
Naming a directory `spec` in a Ruby project is terribly ambiguous. This
clarifies the purpose of this directory and makes it easier to find if
you know that you're looking for OpenAPI.
As described in #506, file uploads were broken on the way over to
Faraday and unfortunately I didn't catch it because the file upload
creation test wasn't using a matcher that was strict enough to really
catch anything.
Here we add the multipart middleware to our Faraday connection, add a
compatibility layer to `FileUpload` so that we can support `File` like
the rest-client based version always did (Faraday generally expects an
`UploadIO` object), and then tighten up our tests so that we'd be able
to catch future regressions.
Fixes#506.
Adds a section on configuring a custom client, makes certain sections
more terse, and rewrites the "configuration section" to be more
consistent and prominent.
I'd originally added this class for the first stub pass that used
OpenAPI because I thought we'd need the ability to finetune some of our
stubbed responses. It turns out that we've been able to get away without
it so far so I'm removing it for now. This commit can be reverted if it
turns out that we need it back later.
Now that we're powering all test suites with the fixture data that's
generated along with the OpenAPI spec, we don't need this secondary
sample data anymore. Remove all of it except for helpers to simulate
different types of error responses.
Follows the path established in 2d75c8f by porting the rest of
stripe-ruby's tests over to OpenAPI. There are a few other changes here
where I've removed some tests that are duplicated or don't make much
sense, or reorganized how we test certain things, but this commit is
largely the same migration operation applied in bulk a few dozen test
suites.
Ports the charge test suite over to use the stub server which is powered
by the OpenAPI spec and its fixtures.
We also introduce a number of conventions here especially around test
case naming and assertions that we'll diffuse to all other test suites
as we port them over. The entire set of tests is internally inconsistent
because of how each new module and resource was added incrementally over
time and while no strong conventions existed.
Adds some testing infrastructure that reads in the OpenAPI spec and its
fixtures. These changes will allow us to starting porting over each of
stripe-ruby's test suites.
This adds an OpenAPI spec for the Stripe API and sample responses for
all top-level resources. We will use the spec and the samples to power
the stripe-ruby test suite.
This has been discussed, but we'll finally be doing it for the next
major version so that we can introduce a few features that depend on
gems that don't support 1.9.
This has been discussed, but we'll finally be doing it for the next
major version so that we can introduce a few features that depend on
gems that don't support 1.9.
Colocates the helper methods for looking up a uname by renaming them to
have the same prefix as the base method (i.e. `get_uname`).
Also adds an additional rescue in case we try to run an executable on a
system but it wasn't founded (this should never happen).
Also adds some tests to make sure that each method gets at least a very
basic amount of exercise in the test suite.
Just adds a super simplistic test for the errors module. The win here is
to (hopefully) lower the friction a little bit the next time a feature
is introduced into errors because there's now suite where a new test can
be written.
Right now we have every error class in a separate file which doesn't do
anyone a lot of good, especially given that most of them are just stubs
that derive directly from `StripeError`.
This patch pulls them all into one file and gives them some
documentation. It follows #487 and #488 as minor refactoring work.
Alphabetizes the list of named model requires in stripe.rb. This makes
it a little easier to spot things, and makes the correct spot to insert
a new model fully deterministic.
This continues along the path of #487 in introducing minor cleanups.
This one is unfortunately a lot of churn, but it's incredibly
frustrating how difficult it is to find methods in this file.
Here we alphabetize the methods, but do nothing else. Alphabetization
only occurs within visibility blocks, so visibility is not affected at
all.
As described in #481, adding a protected field like `legal_entity` as
part of an update API operation can cause some issues like a custom
encoding scheme not being considered and special handling around empty
values being ignored.
As a an easy fix for this, let's disallow access to protected fields in
the same way that we disallow them from being set directly on an
instance of a given model.
Helps address (but is not a complete fix for) #481.
This is a pretty pedestrian change, but here we alphabetize the list of
StripeObject class mappings so that it's easier to scan it for
accidental omissions.
* Add support for multiplan subscriptions:
Serialize indexed arrays into hashes with index keys in subscription create, subscription update, and upcoming invoice
Add a SubscriptionItem object that supports creation, deletion, update, listing, and retrieval
* Remove helpers that convert items array to indexed hash
Right now we are retrying *most* non-HTTP exceptions. This is
problematic because in something like a test context, even a rogue name
error could initiate a retry. It's also bad for production because there
are quite a number of socket errors [1] for which we don't want to
retry.
Fixes#462.
[1] https://ruby-doc.org/stdlib-2.3.0/libdoc/socket/rdoc/Socket.html
Our fairly old requirements for rest-client (and therefore mime-types)
are starting to cause some dependency hell problems for some customers.
Try relaxing these constraints and locking 1.9 specifically into
compatible versions.
Since #433, saving API resources nested under other API resources has
not been the default. Instead, any instances where this should occur
have been special cased with specific method implementations that would
set the `#save_with_parent` flag when a field is written.
This ended up causing some problems because as seen in #457, because
places that we need to do this aren't well vetted, some were forgotten.
This makes implementation of new fields that need this behavior simpler
by implementing a `.save_nested_resource` metraprogramming method on the
`APIResource` class. This can be called as necessary by any concrete API
resource implementations.
We replace existing implementatinos and also add one to `Subscription`,
which had previously been suffering from a similar problem where its
`#source` had not received a special case.
Add deprecated `#bank_account=` to maintain backwards compatibility.
This would have been broken by #433, so this change keeps the
functionality alive in case someone has not upgraded since.
In #433, we built a framework under which subresources are usually not
persisted, but in certain cases they can be. At the time,
`Customer#source` was the only field that I knew about that had to be
flagged into it.
Issue #456 has raised that we also be doing `Account#external_account`.
This patch adds support for that.
Fixes#456.
This produces an error when we detect an "array of maps" that cannot be
encoded with `application/x-www-form-urlencoded`; that is to say, one
that does not have each hash starting with a consistent key that will
allow a Rack-compliant server to recognize boundaries.
So for example, this is fine:
```
items: [
{ :type => 'sku', :parent => 'sku_94ZYSC0wppRTbk' },
{ :type => 'discount', :amount => -10000, :currency => 'cad', :description => 'potato' }
],
```
But this is _not_ okay:
```
items: [
{ :type => 'sku', :parent => 'sku_94ZYSC0wppRTbk' },
{ :amount => -10000, :currency => 'cad', :description => 'potato', :type => 'discount' }
],
```
(`type` should be moved to the beginning of the array.)
The purpose of this change is to give users better feedback when they
run into an encoding problem like this one. Currently, they just get
something confusing from the server, and someone on support usually
needs to examine a request log to figure out what happened.
CI will fail until the changes in #453 are brought in.
This moves away from rest-client's convention of using symbols as header
names so as to present less obfuscation as to how these are actually
named when they go over the wire.
Because headers can be injected via the bindings' API I was initially
worried that this change might break something, but upon inspection of
rest-client source, I can see now that headers take precedence as
assigned by their insertion order into the header hash, and are
"stringified" in that same loop [1]. This means that even if a user
injects a symbolized header name (`:idempotency_key`), it will still
correctly overwrite the one generated by stripe-ruby despite that using
the string format (`"Idempotency-Key"`).
[1] https://github.com/rest-client/rest-client/blob/master/lib/restclient/request.rb#L603,L625
Alphabetizing maps being encoded by key can cause problems because the
server side Rack relies on the fact that that a new array item will
start with a repeated key.
For example, given this encoding:
```
items: [
{ :type => 'sku', :parent => 'sku_94ZYSC0wppRTbk' },
{ :type => 'discount', :amount => -10000, :currency => 'cad', :description => 'potato' }
],
```
We need to have `type` appear first so that an array boundary is
recognized. So the encoded form should take:
```
items[][type]=sku&items[][parent]=...&items[][type]=discount&items[][amount]=...
```
But currently `type` gets sorted to the back, so we get something more
like:
```
items[][parent]=...&items[][type]=...&items[][amount]=...&items[][currency]=...&items[][description]=...&items[][type]=potato
```
Which the server will receive as this:
```
items: [
{ :type => 'sku', :parent => 'sku_94ZYSC0wppRTbk', :amount => -10000, :currency => 'cad', :description => 'potato' }
{ :type => 'discount' }
],
```
Here we remove the alphabetization to fix the problem and correct a bad
test.
This removes a hack in the code that's designed to work around a
rest-client bug which was added back in 2011. Unfortunately neither
comments nor commit messages bother to tell us what the nature of the
bug actually was, but based on what it's rescuing, it might be
rest-client/rest-client#58, which has been fixed for over five years
now.
Following up on the work done in #436, let's continue to try and simply
the error handling paths by taking this out.
Two changes:
1. The HTTP retry path has been refactored to make retries on errors
that are not RestClient exceptions possible by bringing the logic up a
level. This also has the effect of somewhat simplifying the exception
handling logic which can be somewhat difficult to reason about right
now.
2. Retry on `RestClient::Conflict` (a 409 from the API) as discussed in
issue #431.
Fixes#431.
Introduce a `#save_with_parent` flag that allows the default behavior of
never saving API resources nested under a parent to be overridden, a
feature that we so far only know to need for updating a source under a
customer.
CI is failing for a number of Ruby versions because shoulda is pulling
in should-matchers, which then pulls in activesupport. activesupport's
new 5.0.0 version is being picked up, and that requires at least Ruby
2.2.2.
Luckily the solution is easy, we're not using shoulda-matchers, only
shoulda-context, so just tighten up our dependencies a little and the
problem goes away.
* Rename the `Update` operation to `Save`
* Add the `update` class method to all saveable resources
* Add tests for update method
* Add tests for plans, invoice items, and application fees
* allow subs to be retrieved & created with new v1/subs API endpoint
* edit tests to check for url
* fix customer subscription URLs to go through v1/customers
- When performing requests on the behalf of a managed account, `stripe_account` option must be passed everytime, this can become redundant
- Allowing to set the `stripe_account` globally makes thing easier for wrapping every request in a single method, the same way as it is for defining the `api_key` globally
I'm not sure exactly what changed here (did we change the `$VERBOSE`
setting?), but I'm not seeing a whole lot of warnings when running the
test suites locally and in CI. For example:
```
Started
........................................./home/travis/build/stripe/stripe-ruby/lib/stripe/api_operations/list.rb:6: warning: instance variable @opts not initialized
............../home/travis/build/stripe/stripe-ruby/lib/stripe/api_operations/list.rb:6: warning: instance variable @opts not initialized
../home/travis/build/stripe/stripe-ruby/lib/stripe/api_operations/list.rb:6: warning: instance variable @opts not initialized
......../home/travis/build/stripe/stripe-ruby/lib/stripe/api_operations/list.rb:6: warning: instance variable @opts not initialized
.../home/travis/build/stripe/stripe-ruby/lib/stripe/api_operations/list.rb:6: warning: instance variable @opts not initialized
........./home/travis/build/stripe/stripe-ruby/lib/stripe/api_operations/list.rb:6: warning: instance variable @opts not initialized
...
..../home/travis/build/stripe/stripe-ruby/lib/stripe/api_operations/list.rb:6: warning: instance variable @opts not initialized
....../home/travis/build/stripe/stripe-ruby/lib/stripe/api_operations/list.rb:6: warning: instance variable @opts not initialized
..../home/travis/build/stripe/stripe-ruby/lib/stripe/api_operations/list.rb:6: warning: instance variable @opts not initialized
......./home/travis/build/stripe/stripe-ruby/lib/stripe/api_operations/list.rb:6: warning: instance variable @opts not initialized
........./home/travis/build/stripe/stripe-ruby/lib/stripe/api_operations/list.rb:6: warning: instance variable @opts not initialized
........../home/travis/build/stripe/stripe-ruby/lib/stripe/api_operations/list.rb:6: warning: instance variable @opts not initialized
................./home/travis/build/stripe/stripe-ruby/lib/stripe/api_operations/list.rb:6: warning: instance variable @opts not initialized
.../home/travis/build/stripe/stripe-ruby/lib/stripe/api_operations/list.rb:6: warning: instance variable @opts not initialized
..../home/travis/build/stripe/stripe-ruby/lib/stripe/api_operations/list.rb:6: warning: instance variable @opts not initialized
....../home/travis/build/stripe/stripe-ruby/lib/stripe/api_operations/list.rb:6: warning: instance variable @opts not initialized
..........
........./home/travis/build/stripe/stripe-ruby/lib/stripe/api_operations/list.rb:6: warning: instance variable @opts not initialized
....../home/travis/build/stripe/stripe-ruby/lib/stripe/api_operations/list.rb:6: warning: instance variable @opts not initialized
......../home/travis/build/stripe/stripe-ruby/lib/stripe/api_operations/list.rb:6: warning: instance variable @opts not initialized
......../home/travis/build/stripe/stripe-ruby/lib/stripe/api_operations/list.rb:6: warning: instance variable @opts not initialized
............./home/travis/build/stripe/stripe-ruby/lib/stripe/stripe_object.rb:35: warning: instance variable @values not initialized
./home/travis/build/stripe/stripe-ruby/lib/stripe/stripe_object.rb:35: warning: instance variable @values not initialized
...................../home/travis/build/stripe/stripe-ruby/lib/stripe/transfer.rb:8: warning: instance variable @api_key not initialized
..............
..
Finished in 0.785621037 seconds.
```
Most of these are due to unused or uninitialized variables. This patch
fixes all warnings by fixing offending code.
This is consistent with API library behavior in other languages, and with our
API documentation (which doesn't mention needing to handle this type of error).
Prior to my last major serialization refactor, there was a check in the
code that would remove any subobjects from serialization that were of
their own proper resource type (for example, if a charge contained a
customer, that customer would be removed).
What I didn't realize at the time is that the old serialization code had
a bug/quirk that would allow *certain types* of subobjects that were API
resources to make it through unscathed.
In short, the behavior requirement here is *directly* contradictory.
There was a test in place that would make sure that `customer` was
removed from this hash:
``` ruby
{
:id => 'ch_id',
:object => 'charge',
:customer => {
:object => 'customer',
:id => 'customer_id'
}
}
```
But, as reported in #406, we expect, and indeed need, for `source` (a
card) to make it through to the API in this hash:
``` ruby
{
:id => 'cus_id',
:object => 'customer',
:source => {
:object => 'card',
:id => 'card_id'
}
}
```
My proposal here is to just remove the check on serializing API
resources. The normal code that only sends up keys/hashes that have
changed is still in place, so in the first example, `customer` still
isn't sent unless the user has directly manipulated a field on that
subobject. I propose that in those cases we allow the API itself to
reject the request rather than try to cut it off at the client level.
Unfortunately, there is some possibility that removing those API
resources is important for some reason, but of course there's no
documentation on it beyond the after-the-fact post-justification that I
wrote during my last refactor. I can't think of any reason that it would
be too destructive, but there is some level of risk.
Certain platforms will throw an error if this variable is accessed
without being initialized. Assign it a value instead of relying on the
OR operator to give it a default.
Here we predicate the installation of Byebug on being on the MRI. This
allows us to `bundle install` on alternate platforms like JRuby.
Also performs some Gemfile management: add latest MRI and JRuby versions
and remove special case Gemfiles.
This attempts to give some semblance of thread safety to parallel
library requests by pre-assigning a certificate store, the
initialization of which seems to be a weak point for thread safety. Note
that while this does seem to empirically improve the situation, it
doesn't guarantee actual thread safety.
A longer term solution to the problem is probably to assign a per-thread
HTTP client for much stronger guarantees, but this is a little further
out. More discussion on that topic in #313.
Fixes#382.
In #394 we renamed `url` to `resource_url` in order to prevent name
collisions in API resource that also have a `url` property.
Unfortunately, this didn't account for the fact that when making API
calls on a list object we rely on a returned `url` property to build a
request, and this had been renamed to `resource_url`. Test should have
caught this, but they were written to work differently than how live
API calls actually function.
This patch repairs the problem by adding a `resource_url` to list
objects, and modifies test to be more accurate to reality so that
they'll catch this class of problem in the future.
Fixes#395.
This pull does two major things:
1. Refactors `serialize_params` to be more concise and readable while
still complying to our existing test suite. Unfortunately over time
this method has become a ball of mud that's very difficult to reason
about, as recently evidenced by #384.
2. Moves `serialize_params` from class method to instance method (while
still keeping for old class method for backwards compatibility). This
is to give it a more sane interface.
Hashes are converted to StripeObject when used as params of save.
They need to be converted to hash on serialize.
Signed-off-by: François de Metz <francois@stormz.me>
Signed-off-by: Cyril Duez <cyril@stormz.me>
`params` and `opts` are not currently passed through when using the
`#refund` helper on `ApplicationFee`. This was an omission on the
original refactor to use the new endpoint, and wasn't an intentional
design.
Fixes#386.
This is kind of a bike shed, but at this point it's a little more clear
that Markdown has won the format wars and that people are a little more
used to seeing/editing it.
This moves the `README` to Markdown and also includes some minor
cleanup:
* Fixes a broken reference link (`curl`).
* Normalizes lines to 80 characters.
* Normalizes code snippets to be prefixed by four spaces.
* Normalizes sentence to be separately by only a single space.
An unfortunate side effect of #364 is that it broke compatibility for
users on very old API versions because their `refunds` field will come
back as an array.
This adds a compatibility layer that will allow even users on old API
versions to seamlessly upgrade their gem versions.
Our CA bundle has fallen quite out of date since it was last pulled.
This patch updates it and adds a Rake task to make this task more
repeatable.
One thing worth noting is I've switched us over from the Ubuntu bundle
to the Mozilla bundle that's maintained by cURL. The bundle seemed to be
previously extracted by a custom script that I don't really want to
maintain. cURL and Excon both use the Mozilla bundle and it should be a
safe replacement.
As requested in #370, this will allow advanced users to configure a
certificate bundle that is expected to be more up-to-date than what
we've managed to include with the gem.
As discussed previously in #354 and alluded to in #363, this patch
deprecates the `#refund` helpers on `Charge` and `ApplicationFee` in
favor of the resource-centric approach (i.e. `charge.refunds.create`).
We do this for a few reasons:
1. The new approach is far preferred and uses our modern endpoints. It's
also been the mechanism suggested by the documentation for ages now.
2. The old approach is somewhat risky in that a forgotten "s" can lead
to an accidental refund (i.e. `charge.refund` instead of
`charge.refunds`).
Follows up #354. Fixes#363.
This is kind of a weird one because it'll only cause a failure when
serializing a subobject or hash of a `StripeObject`, but it's good
practice to initialize instance variables anyway.
Fixes#360.
Follows up the patch in #351, which I now believe is wrong. The trouble
is that we were mutating the application fee object, when in reality an
application fee refund is actually a completely new resource (see
[creating a refund][create-refund]). This patch edits the original
attempt to cut a new object and updates tests accordingly.
Once again, related to stripe/stripe-php#208.
[create-refund]: https://stripe.com/docs/api#create_fee_refund
We attempt to do a special encoding trick when serializing
`additional_owners` under an account: when updating a value, we actually
send the update parameters up as an integer-indexed hash rather than an
array. So instead of this:
field[]=item1&field[]=item2&field[]=item3
We send this:
field[0]=item1&field[1]=item2&field[2]=item3
The trouble is that this had previously been built into the core library
as the default handling for all arrays. Because of this, it was
impossible to resize a non-`additional_owners` array as described in
more detail in #340.
This patch special cases `additional_owners` and brings sane behavior
back to normal arrays along with a test suite so that we try to build
some better guarantees around both the general and non-general cases.
I find myself using these quite a bit when looking into problems, and
currently have to manually re-add them to the Gemfile/gemspec to get
them in the bundle and make them available in tests.
Here we gate the debugger to only come in for Ruby > 2 so as to avoid
problems with various compatibility problems between debuggers and
versions of Ruby. If there's a demand for a pre-Ruby 2 debugger, we can
add that separately.
Any major objections to this one? Thanks.
Unfortunately usage of `#update_attributes` had rolled over from a time
where `#update_attributes_with_options` was still in use and `opts` were
being passed in as an optional argument which had the result of further
nesting the hash internally (i.e. `:opts => { :opts => ... } }`).
This patch fixes that problem, adds a regression test to prevent it from
reappearing, and banishes the unused `#update_attributes_with_options`.
Fixes#334.
I added this for a regression suite so that 1.8.7 could pass its tests,
but unfortunately this caused a regression in the way that parameters
are encoded for arrays of hashes. This patch reverts the change and adds
tests to detect a future regression.
(And 1.8.7 is expected to fail on this initial commit.)
When additional filters were provided for pagination like an expansion
or a predicate, they would not propagate to any call after the first.
This patch addresses that issue by storing all filters and moving them
to any new page objects being created.
Fixes#331.
Adds a special helper to `StripeObject` that helps a developer to
determine whether or not an object is deleted.
As described originally in #257, this is a bit of a special case because
a non-deleted object does not respond with `deleted` as part of its
representation, so while a deleted object would have this accessor
available automatically, non-deleted objects would not. This made use of
the SDK awkward because the presence of the method was not guaranteed.
Fixes#257 (again, heh).
This dials down the safety of `StripeObject`'s `#update_attributes`
method so that it allows properties to be assigned that it doesn't yet
know about. We're doing this for a few reasons:
1. To reflect the current behavior of accessors (i.e. `obj.name = ...`)
through `method_missing`.
2. To allow `#update_attributes` to assign properties on new projects
that don't yet know their schema from an API call.
Fixes#324.
As discussed in #325, this deprecates the public visibility of
`#refresh_from` (by renaming it). It also adds some deprecation
infrastructure to produce warnings when it's used.
Replaces my original attempt in #319 in a way that doesn't depend on
`URI.encode_www_form` which doesn't exist in 1.8.7. This should
hopefully get us the best of all worlds.
Caveats around use of `+` instead of `%20` as detailed in #319 still
apply.
Fixes#286.
Pulls the test suite out of #319 so that we can get some coverage around
parameter encoding. This should prevent any recurrence of #318.
Also includes a little bit of refactoring.
Lets not be too shy about just using `extend` instead of `include` here
when it's more appropriate to do so. The advantage to this approach is
that the module can be either extended _or_ included with this change,
but couldn't be without it due to the `ClassMethods` meta-magic.
List has already started doing this as of #314, so we don't have to be
afraid of breaking convention here.
Usage on a top-level collection:
```
Stripe::Customer.list.auto_paging_each do |customer|
puts customer
end
```
Usage on a subcollection:
``` ruby
customer.invoices.auto_paging_each do |invoice|
puts invoice
end
```
We've also renamed `#all` to `#list` to prevent confusion ("all" implies
that all resources are being returned, and in Stripe's paginated API
this was not the case). An alias has been provided for backward API
compatibility.
Fixes#167.
Replaces #211 and #248.
As detailed in issue #119, we've somewhat unfortunately been allowing
object attributes to be passed in during a #save because we mix any
arguments directly into the serialized hash (it seems that this was
originally intended to be used more for meta parameters that go to the
request).
As also noted in #119, this use causes problems when certain types of
parameters (like subobjects) are used. We're now left in the somewhat
awkward position of either:
1. Removing this functionality on #save and breaking what may be
behavior that people depend on.
2. Fully support this mass assignment.
This patch takes the second path by extracting a new #update_attributes
method and using it from #save. It's still far from a perfect approach
because keys that have the same name as certain options (e.g. `req_url`)
are not going to work, but it should capture the behavior that most
people want.
Fixes#119.
This patch adds question marks helpers (e.g. #paid?) for any values in a
StripeObject that are a boolean. This is fairly idiomatic Ruby in that
it behaves similarly to other libraries like ActiveRecord.
Note that a caveat here is that nullable booleans will not get a helper
added for them if their current value is null. For this reason, we
should eventually prefer to derive these methods from some sort of
programmatic API manifest.
Replaces #257 and #274.
This makes ListObject behave a little more like an Array in that it gets
an #empty? helper. This should fit pretty well with the Enumerable
methods that it already has.
Replaces #193.
Granular running of tests is one of Minitest's many gotchas. This
change adds some more information on how to run individual test suites
and individual tests which is useful when debugging.
This pulls the `Enumerable` mixin into `ListObject`. There is some
question in pulls like #167 as to the future of `ListObject` and how it
might change when pagination is introduced, but because we're unlikely
to make any backward incompatible changes to the API, it's likely that
`ListObject` will continue to represent a page of data that's been
extracted from the API. Given that assumption, pulling `Enumerable` in
should be relatively safe.
Fixes#227.
When constructing an object using .construct_from treat keys that are
strings the same as keys which are symbols by calling Util's
symbolize_names on an input hash. This makes guarantees around
consistency a little better.
Fixes#151.
Modifies the behavior of an update so that it can create an object if it
was new. This allows an "upsert"-like functionality where the SDK will
tend to do the right/expected thing.
This is a tad janky in that it checks for the existence of a class-level
`.create` method which is expected to come from a different module, but
most modules in the project are already fairly deeply intertwined and
co-dependent.
Fixes#165.
Looks like it's meant for Ruby apps, not gems. It shows the dependency info
from the gemfile rather than the gemspec, which is misleading.
cc @bkrausz @kyleconroy
This will be way faster on linux systems than shelling out to uname.
Also add hostname from Socket.gethostname since that information is
provided by `uname -a` but not /proc/version.
* This error message said "Cards cannot be retrieved without a customer
ID. Retrieve a card using customer.cards.retrieve('card_id')"
This is incorrect. `customer.cards` throws a `NoMethodError: undefined
method `cards' for #<Stripe::Customer:0x0000010c8bdca8>`.
* The correct method is `Stripe::Customer#sources`, and this fixes the
error message.
Allow developers to use Stripe test data when stubbing responses
locally. This should help mitigate the risk of API drift with stubbed
responses.
* Move response helpers to their own file
- Runs all tests at once instead of one at a time, this way we don't pay
the cost of constantly reloading the environment. Takes test time from 20
seconds to 4.
- Removes the separate testing using activesupport/all, which wasn't actually
doing anything since the tests were running in a separate process.
Thanks to @JoshCheek for surfacing these issues.
Check for `@values` in StripeObject#method_not_found.
This is necessary because we check for `@values` in `respond_to_missing?` now, but this isn't necessarily always set. For example, in deserializing from YAML, Psych creates the object using `allocate` and not `new`, which ends up skipping any initializing of instance variables. See #122 for more details.
It's helpful to be able to test the bindings with instances of the
Stripe API running locally, or running on a server that doesn't support
SSL. When :verify_ssl_certs is false, don't check the SSL cert against
the blacklist, as there probably isn't a certificate to check.
If a StripeObject is being deserialized by psych, @values.has_key? is
called before @values is initialized which prevents proper
deserialization from occurring. Checking for existence first resolves
the issue.
This commit adds `Customer#create_subscription`, which allows a
subscription to be created on a customer without first fetching the
customer record.
Previously:
```
customer = Stripe::Customer.retrieve('cus_abc123def') # GET request
customer.subscriptions.create(plan: 'cool-plan-1') # POST request
```
**No alteration has been made to the above method; the preceding
implementation still functions as it did previously.**
With `#create_subscription`:
```
customer = Stripe::Customer.new('cus_abc123def') # No request
customer.create_subscription(plan: 'cool-plan-1') # POST request
```
This method removes the initial `GET` request and instead issues a
`POST` directly to create the subscription.
This reverts commit d6ebab33109ff2501ba9709d2ac1dd666be0ab67.
We'll support the legacy single-subscription API style
indefinitely, and also we generaly try to make it so that
people can use modern bindings with out-of-date API versions.
Our list calls return their results wrapped in an object so that we
can include extra information. We use this, e.g., to include the URL
to query for more records in the Transfer#transactions sublist.
When you get a ListObject, if you want to actually manipulate it as a
list, you have to call `#data` first to get the actual underlying
list.
This adds an exception to the `#[]` method to make what's going on
clearer.
Fixes#68
Make the SSL checks, user agent assembly, and request header
generation separate methods.
Also switch to class instance variables instead of class variables and
accessors instead of custom functions, and wrap lines to 80
characters.
Original patches come with thanks to Stevie Graham (with some style
fixups from me).
(fixes#53, fixes#54)
It seems to embrace the 'Ruby Way' (and more convenient in my own code) to be able to access an upcoming invoice from the customer itself rather than de-reference the customer id and ask the Invoice class itself for that info.
Attempting to spawn a subprocess to get the uname threw an out of
memory error. Since the uname is only needed to provide diagnostic
info in the User-Agent, it shouldn't cause stripe to fail.
Rationale:
Sometime you don't care about the current state of a resource
you just want to update one of it's attributes.
It should only require one request.
fixes#52
```ruby
c = Stripe::Customer.new("cus_1EqKjPaFs4ZwDD")
c.description = 'Ny new Description'
c.save
```
Before:
```json
{
error: {
type: "invalid_request_error",
message: "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.",
param: "id",
}
}
```
After:
Successfully update the customer and return it's whole state.
<!-- Describe why this change is being made. Briefly include history and context, high-level what this PR does, and what the world looks like afterward. -->
### What?
<!--
List out the key changes made in this PR, e.g.
- implements the antimatter particle trace in the nitronium microfilament drive
- updated tests -->
### See Also
<!-- Include any links or additional information that help explain this change. -->
We welcome bug reports, feature requests, and code contributions in a pull request.
For most pull requests, we request that you identify or create an associated issue that has the necessary context. We use these issues to reach agreement on an approach and save the PR author from having to redo work. Fixing typos or documentation issues likely do not need an issue; for any issue that introduces substantial code changes, changes the public interface, or if you aren't sure, please find or [create an issue](https://www.github.com/stripe/stripe-ruby/issues/new/choose).
## Contributor License Agreement
All contributors must sign the Contributor License Agreement (CLA) before we can accept their contribution. If you have not yet signed the agreement, you will be given an option to do so when you open a pull request. You can then sign by clicking on the badge in the comment from @CLAassistant.
## Generated code
This project has a combination of manually maintained code and code generated from our private code generator. If your contribution involves changes to generated code, please call this out in the issue or pull request as we will likely need to make a change to our code generator before accepting the contribution.
To identify files with purely generated code, look for the comment `File generated from our OpenAPI spec.` at the start of the file. Generated blocks of code within hand-written files will be between comments that say `The beginning of the section generated from our OpenAPI spec` and `The end of the section generated from our OpenAPI spec`.
## Compatibility with supported language and runtime versions
This project supports [many different langauge and runtime versions](README.md#requirements) and we are unable to accept any contribution that does not work on _all_ supported versions. If, after discussing the approach in the associated issue, your change must use an API / feature that isn't available in all supported versions, please call this out explicitly in the issue or pull request so we can help figure out the best way forward.
## Set up your dev environment
Please refer to this project's [README.md](README.md#development) for instructions on how to set up your development environment.
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](https://stripe.com/docs/api?lang=ruby).
## 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:
```sh
gem install stripe
```
If you want to build the gem from source:
```sh
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:
```ruby
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][api-keys]. Set `Stripe.api_key` to its
value:
```ruby
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][connect], it's also possible to set a
per-request key and/or account:
```ruby
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.
### StripeClient vs legacy pattern
We introduced the `StripeClient` class in v13 of the Ruby SDK. The legacy pattern used prior to that version is still available to use but will be marked as deprecated soon. Review the [migration guide to use StripeClient](https://github.com/stripe/stripe-ruby/wiki/Migration-guide-for-v13) to move from the legacy pattern.
Once the legacy pattern is deprecated, new API endpoints will only be accessible in the StripeClient. While there are no current plans to remove the legacy pattern for existing API endpoints, this may change in the future.
### Accessing resource properties
Both indexer and accessors can be used to retrieve values of resource properties.
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:
```ruby
Stripe.enable_telemetry = false
```
### Types
In [v14.0.0](https://github.com/stripe/stripe-python/releases/tag/v7.1.0) and newer, the library provides RBI
static type annotations. See [the wiki](https://github.com/stripe/stripe-ruby/wiki/Static-Type-Annotations)
for an detailed guide.
Please note that these types are available only for static analysis and we only support RBIs at the moment.
Please [report an issue](https://github.com/stripe/stripe-ruby/issues/new/choose)
if you find discrepancies or have issues using types.
The RBIs can be found in the `rbi/stripe/` directory, and to decrease `Tapioca` loading time we pack the gem with the
combined RBI at `rbi/stripe.rbi`.
#### Types and the Versioning Policy
We release type changes in minor releases. While stripe-ruby follows semantic versioning, our semantic
versions describe the runtime behavior of the library alone. Our type annotations are not reflected in the
semantic version. That is, upgrading to a new minor version of `stripe-ruby` might result in your type checker
producing a type error that it didn't before. You can use `~> x.x` or `x.x.x` constrain the version
of `stripe-ruby` in your Gemfile to a certain version or range of `stripe-ruby`.
#### Types and API Versions
The types describe the [Stripe API version](https://stripe.com/docs/api/versioning)
that was the latest at the time of release. This is the version that your library sends
by default. If you are overriding `Stripe.api_version` / `stripe_version` on the StripeClient,
or using a webhook endpoint tied to an older version, be aware that the data
you see at runtime may not match the types.
### Public Preview SDKs
Stripe has features in the [public preview phase](https://docs.stripe.com/release-phases) that can be accessed via versions of this package that have the `-beta.X` suffix like `11.2.0-beta.2`.
We would love for you to try these as we incrementally release new features and improve them based on your feedback.
To install, choose the version that includes support for the preview feature you are interested in by reviewing the [releases page](https://github.com/stripe/stripe-ruby/releases/) and use it in the `gem install` command:
You can find the latest version to use in this command from the [releases page](https://github.com/stripe/stripe-ruby/releases/)
> **Note**
> There can be breaking changes between two versions of the public preview SDKs without a bump in the major version. Therefore we recommend pinning the package version to a specific 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 version of the public preview SDK.
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.
Some preview features require a name and version to be set in the `Stripe-Version` header like `feature_beta=v3`. If your preview feature has this requirement, use the `Stripe.add_beta_version` function (available only in the public preview SDKs):
```python
Stripe.add_beta_version("feature_beta", "v3")
```
### Custom requests
If you:
- would like to send a request to an undocumented API (for example you are in a private beta)
- prefer to bypass the method definitions in the library and specify your request details directly,
- used the method `Stripe::APIResource.request(...)` to specify your own requests, which will soon be broken
you can now use the `raw_request` method on `StripeClient`.
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
[Contribution guidelines for this project](CONTRIBUTING.md)
The test suite depends on [stripe-mock], so make sure to fetch and run it from a background terminal ([stripe-mock's README][stripe-mock] also contains instructions for installing via Homebrew and other methods):
```sh
go install github.com/stripe/stripe-mock@latest
stripe-mock
```
We use [just](https://github.com/casey/just) for common development tasks. You can install it or run the underlying commands directly (by copying them from the `justfile`). Common tasks include:
raiseAuthenticationError.new('No API key provided. (HINT: set your API key using "Stripe.api_key = <API-KEY>". You can generate API keys from the Stripe web interface. See https://stripe.com/api for details, or email support@stripe.com if you have any questions.)')unlessapi_key
if!verify_ssl_certs
unless@no_verify
$stderr.puts"WARNING: Running without SSL cert verification. Execute 'Stripe.verify_ssl_certs = true' to enable verification."
@no_verify=true
end
ssl_opts={:verify_ssl=>false}
elsif!Util.file_readable(@@ssl_bundle_path)
unless@no_bundle
$stderr.puts"WARNING: Running without SSL cert verification because #{@@ssl_bundle_path} isn't readable"
@no_bundle=true
end
ssl_opts={:verify_ssl=>false}
else
ssl_opts={
:verify_ssl=>OpenSSL::SSL::VERIFY_PEER,
:ssl_ca_file=>@@ssl_bundle_path
}
end
uname=(@@uname||=RUBY_PLATFORM=~/linux|darwin/i?`uname -a 2>/dev/null`.strip:nil)
message="Could not connect to Stripe (#{@@api_base}). Please check your internet connection and try again. If this problem persists, you should check Stripe's service status at https://twitter.com/stripestatus, or let us know at support@stripe.com."
whenRestClient::SSLCertificateNotVerified
message="Could not verify Stripe's SSL certificate. Please make sure that your network is not intercepting certificates. (Try going to https://api.stripe.com/v1 in your browser.) If this problem persists, let us know at support@stripe.com."
whenSocketError
message="Unexpected error communicating when trying to connect to Stripe. HINT: You may be seeing this message because your DNS is not working. To check, try running 'host stripe.com' from the command line."
else
message="Unexpected error communicating with Stripe. If this problem persists, let us know at support@stripe.com."
# Account Links are the means by which a Connect platform grants a connected account permission to access
# Stripe-hosted applications, such as Connect Onboarding.
#
# Related guide: [Connect Onboarding](https://stripe.com/docs/connect/custom/hosted-onboarding)
classAccountLink<APIResource
extendStripe::APIOperations::Create
OBJECT_NAME="account_link"
defself.object_name
"account_link"
end
classCreateParams<Stripe::RequestParams
classCollectionOptions<Stripe::RequestParams
# Specifies whether the platform collects only currently_due requirements (`currently_due`) or both currently_due and eventually_due requirements (`eventually_due`). If you don't specify `collection_options`, the default value is `currently_due`.
attr_accessor:fields
# Specifies whether the platform collects future_requirements in addition to requirements in Connect Onboarding. The default value is `omit`.
attr_accessor:future_requirements
definitialize(fields:nil,future_requirements:nil)
@fields=fields
@future_requirements=future_requirements
end
end
# The identifier of the account to create an account link for.
attr_accessor:account
# The collect parameter is deprecated. Use `collection_options` instead.
attr_accessor:collect
# Specifies the requirements that Stripe collects from connected accounts in the Connect Onboarding flow.
attr_accessor:collection_options
# Specifies which fields in the response should be expanded.
attr_accessor:expand
# The URL the user will be redirected to if the account link is expired, has been previously-visited, or is otherwise invalid. The URL you specify should attempt to generate a new account link with the same parameters used to create the original account link, then redirect the user to the new account link's URL so they can continue with Connect Onboarding. If a new account link cannot be generated or the redirect fails you should display a useful error to the user.
attr_accessor:refresh_url
# The URL that the user will be redirected to upon leaving or completing the linked flow.
attr_accessor:return_url
# The type of account link the user is requesting. Possible values are `account_onboarding` or `account_update`.
attr_accessor:type
definitialize(
account:nil,
collect:nil,
collection_options:nil,
expand:nil,
refresh_url:nil,
return_url:nil,
type:nil
)
@account=account
@collect=collect
@collection_options=collection_options
@expand=expand
@refresh_url=refresh_url
@return_url=return_url
@type=type
end
end
# Time at which the object was created. Measured in seconds since the Unix epoch.
attr_reader:created
# The timestamp at which this account link will expire.
attr_reader:expires_at
# String representing the object's type. Objects of the same type share the same value.
attr_reader:object
# The URL for the account link.
attr_reader:url
# Creates an AccountLink object that includes a single-use Stripe URL that the platform can redirect their user to in order to take them through the Connect Onboarding flow.
# An AccountSession allows a Connect platform to grant access to a connected account in Connect embedded components.
#
# We recommend that you create an AccountSession each time you need to display an embedded component
# to your user. Do not save AccountSessions to your database as they expire relatively
# quickly, and cannot be used more than once.
#
# Related guide: [Connect embedded components](https://stripe.com/docs/connect/get-started-connect-embedded-components)
classAccountSession<APIResource
extendStripe::APIOperations::Create
OBJECT_NAME="account_session"
defself.object_name
"account_session"
end
classComponents<Stripe::StripeObject
classAccountManagement<Stripe::StripeObject
classFeatures<Stripe::StripeObject
# Disables Stripe user authentication for this embedded component. This value can only be true for accounts where `controller.requirement_collection` is `application`. The default value is the opposite of the `external_account_collection` value. For example, if you don’t set `external_account_collection`, it defaults to true and `disable_stripe_user_authentication` defaults to false.
attr_reader:disable_stripe_user_authentication
# Whether to allow platforms to control bank account collection for their connected accounts. This feature can only be false for accounts where you’re responsible for collecting updated information when requirements are due or change, like custom accounts. Otherwise, bank account collection is determined by compliance requirements. The default value for this feature is `true`.
attr_reader:external_account_collection
end
# Whether the embedded component is enabled.
attr_reader:enabled
# Attribute for field features
attr_reader:features
end
classAccountOnboarding<Stripe::StripeObject
classFeatures<Stripe::StripeObject
# Disables Stripe user authentication for this embedded component. This value can only be true for accounts where `controller.requirement_collection` is `application`. The default value is the opposite of the `external_account_collection` value. For example, if you don’t set `external_account_collection`, it defaults to true and `disable_stripe_user_authentication` defaults to false.
attr_reader:disable_stripe_user_authentication
# Whether to allow platforms to control bank account collection for their connected accounts. This feature can only be false for accounts where you’re responsible for collecting updated information when requirements are due or change, like custom accounts. Otherwise, bank account collection is determined by compliance requirements. The default value for this feature is `true`.
attr_reader:external_account_collection
end
# Whether the embedded component is enabled.
attr_reader:enabled
# Attribute for field features
attr_reader:features
end
classBalances<Stripe::StripeObject
classFeatures<Stripe::StripeObject
# Disables Stripe user authentication for this embedded component. This value can only be true for accounts where `controller.requirement_collection` is `application`. The default value is the opposite of the `external_account_collection` value. For example, if you don’t set `external_account_collection`, it defaults to true and `disable_stripe_user_authentication` defaults to false.
attr_reader:disable_stripe_user_authentication
# Whether to allow payout schedule to be changed. Default `true` when Stripe owns Loss Liability, default `false` otherwise.
attr_reader:edit_payout_schedule
# Whether to allow platforms to control bank account collection for their connected accounts. This feature can only be false for accounts where you’re responsible for collecting updated information when requirements are due or change, like custom accounts. Otherwise, bank account collection is determined by compliance requirements. The default value for this feature is `true`.
attr_reader:external_account_collection
# Whether to allow creation of instant payouts. Default `true` when Stripe owns Loss Liability, default `false` otherwise.
attr_reader:instant_payouts
# Whether to allow creation of standard payouts. Default `true` when Stripe owns Loss Liability, default `false` otherwise.
attr_reader:standard_payouts
end
# Whether the embedded component is enabled.
attr_reader:enabled
# Attribute for field features
attr_reader:features
end
classDisputesList<Stripe::StripeObject
classFeatures<Stripe::StripeObject
# Whether to allow capturing and cancelling payment intents. This is `true` by default.
attr_reader:capture_payments
# Whether to allow connected accounts to manage destination charges that are created on behalf of them. This is `false` by default.
# Whether to allow responding to disputes, including submitting evidence and accepting disputes. This is `true` by default.
attr_reader:dispute_management
# Whether to allow sending refunds. This is `true` by default.
attr_reader:refund_management
end
# Whether the embedded component is enabled.
attr_reader:enabled
# Attribute for field features
attr_reader:features
end
classDocuments<Stripe::StripeObject
classFeatures<Stripe::StripeObject;end
# Whether the embedded component is enabled.
attr_reader:enabled
# Attribute for field features
attr_reader:features
end
classFinancialAccount<Stripe::StripeObject
classFeatures<Stripe::StripeObject
# Disables Stripe user authentication for this embedded component. This value can only be true for accounts where `controller.requirement_collection` is `application`. The default value is the opposite of the `external_account_collection` value. For example, if you don’t set `external_account_collection`, it defaults to true and `disable_stripe_user_authentication` defaults to false.
attr_reader:disable_stripe_user_authentication
# Whether to allow external accounts to be linked for money transfer.
# Whether to allow card spend dispute management features.
attr_reader:card_spend_dispute_management
end
# Whether the embedded component is enabled.
attr_reader:enabled
# Attribute for field features
attr_reader:features
end
classIssuingCard<Stripe::StripeObject
classFeatures<Stripe::StripeObject
# Whether to allow card management features.
attr_reader:card_management
# Whether to allow card spend dispute management features.
attr_reader:card_spend_dispute_management
# Whether to allow cardholder management features.
attr_reader:cardholder_management
# Whether to allow spend control management features.
attr_reader:spend_control_management
end
# Whether the embedded component is enabled.
attr_reader:enabled
# Attribute for field features
attr_reader:features
end
classIssuingCardsList<Stripe::StripeObject
classFeatures<Stripe::StripeObject
# Whether to allow card management features.
attr_reader:card_management
# Whether to allow card spend dispute management features.
attr_reader:card_spend_dispute_management
# Whether to allow cardholder management features.
attr_reader:cardholder_management
# Disables Stripe user authentication for this embedded component. This feature can only be false for accounts where you’re responsible for collecting updated information when requirements are due or change, like custom accounts.
attr_reader:disable_stripe_user_authentication
# Whether to allow spend control management features.
attr_reader:spend_control_management
end
# Whether the embedded component is enabled.
attr_reader:enabled
# Attribute for field features
attr_reader:features
end
classNotificationBanner<Stripe::StripeObject
classFeatures<Stripe::StripeObject
# Disables Stripe user authentication for this embedded component. This value can only be true for accounts where `controller.requirement_collection` is `application`. The default value is the opposite of the `external_account_collection` value. For example, if you don’t set `external_account_collection`, it defaults to true and `disable_stripe_user_authentication` defaults to false.
attr_reader:disable_stripe_user_authentication
# Whether to allow platforms to control bank account collection for their connected accounts. This feature can only be false for accounts where you’re responsible for collecting updated information when requirements are due or change, like custom accounts. Otherwise, bank account collection is determined by compliance requirements. The default value for this feature is `true`.
attr_reader:external_account_collection
end
# Whether the embedded component is enabled.
attr_reader:enabled
# Attribute for field features
attr_reader:features
end
classPaymentDetails<Stripe::StripeObject
classFeatures<Stripe::StripeObject
# Whether to allow capturing and cancelling payment intents. This is `true` by default.
attr_reader:capture_payments
# Whether to allow connected accounts to manage destination charges that are created on behalf of them. This is `false` by default.
# Whether to allow responding to disputes, including submitting evidence and accepting disputes. This is `true` by default.
attr_reader:dispute_management
# Whether to allow sending refunds. This is `true` by default.
attr_reader:refund_management
end
# Whether the embedded component is enabled.
attr_reader:enabled
# Attribute for field features
attr_reader:features
end
classPayouts<Stripe::StripeObject
classFeatures<Stripe::StripeObject
# Disables Stripe user authentication for this embedded component. This value can only be true for accounts where `controller.requirement_collection` is `application`. The default value is the opposite of the `external_account_collection` value. For example, if you don’t set `external_account_collection`, it defaults to true and `disable_stripe_user_authentication` defaults to false.
attr_reader:disable_stripe_user_authentication
# Whether to allow payout schedule to be changed. Default `true` when Stripe owns Loss Liability, default `false` otherwise.
attr_reader:edit_payout_schedule
# Whether to allow platforms to control bank account collection for their connected accounts. This feature can only be false for accounts where you’re responsible for collecting updated information when requirements are due or change, like custom accounts. Otherwise, bank account collection is determined by compliance requirements. The default value for this feature is `true`.
attr_reader:external_account_collection
# Whether to allow creation of instant payouts. Default `true` when Stripe owns Loss Liability, default `false` otherwise.
attr_reader:instant_payouts
# Whether to allow creation of standard payouts. Default `true` when Stripe owns Loss Liability, default `false` otherwise.
attr_reader:standard_payouts
end
# Whether the embedded component is enabled.
attr_reader:enabled
# Attribute for field features
attr_reader:features
end
classPayoutsList<Stripe::StripeObject
classFeatures<Stripe::StripeObject;end
# Whether the embedded component is enabled.
attr_reader:enabled
# Attribute for field features
attr_reader:features
end
classTaxRegistrations<Stripe::StripeObject
classFeatures<Stripe::StripeObject;end
# Whether the embedded component is enabled.
attr_reader:enabled
# Attribute for field features
attr_reader:features
end
classTaxSettings<Stripe::StripeObject
classFeatures<Stripe::StripeObject;end
# Whether the embedded component is enabled.
attr_reader:enabled
# Attribute for field features
attr_reader:features
end
# Attribute for field account_management
attr_reader:account_management
# Attribute for field account_onboarding
attr_reader:account_onboarding
# Attribute for field balances
attr_reader:balances
# Attribute for field disputes_list
attr_reader:disputes_list
# Attribute for field documents
attr_reader:documents
# Attribute for field financial_account
attr_reader:financial_account
# Attribute for field financial_account_transactions
attr_reader:financial_account_transactions
# Attribute for field issuing_card
attr_reader:issuing_card
# Attribute for field issuing_cards_list
attr_reader:issuing_cards_list
# Attribute for field notification_banner
attr_reader:notification_banner
# Attribute for field payment_details
attr_reader:payment_details
# Attribute for field payment_disputes
attr_reader:payment_disputes
# Attribute for field payments
attr_reader:payments
# Attribute for field payouts
attr_reader:payouts
# Attribute for field payouts_list
attr_reader:payouts_list
# Attribute for field tax_registrations
attr_reader:tax_registrations
# Attribute for field tax_settings
attr_reader:tax_settings
end
classCreateParams<Stripe::RequestParams
classComponents<Stripe::RequestParams
classAccountManagement<Stripe::RequestParams
classFeatures<Stripe::RequestParams
# Disables Stripe user authentication for this embedded component. This value can only be true for accounts where `controller.requirement_collection` is `application`. The default value is the opposite of the `external_account_collection` value. For example, if you don’t set `external_account_collection`, it defaults to true and `disable_stripe_user_authentication` defaults to false.
attr_accessor:disable_stripe_user_authentication
# Whether to allow platforms to control bank account collection for their connected accounts. This feature can only be false for accounts where you’re responsible for collecting updated information when requirements are due or change, like custom accounts. Otherwise, bank account collection is determined by compliance requirements. The default value for this feature is `true`.
# The list of features enabled in the embedded component.
attr_accessor:features
definitialize(enabled:nil,features:nil)
@enabled=enabled
@features=features
end
end
classAccountOnboarding<Stripe::RequestParams
classFeatures<Stripe::RequestParams
# Disables Stripe user authentication for this embedded component. This value can only be true for accounts where `controller.requirement_collection` is `application`. The default value is the opposite of the `external_account_collection` value. For example, if you don’t set `external_account_collection`, it defaults to true and `disable_stripe_user_authentication` defaults to false.
attr_accessor:disable_stripe_user_authentication
# Whether to allow platforms to control bank account collection for their connected accounts. This feature can only be false for accounts where you’re responsible for collecting updated information when requirements are due or change, like custom accounts. Otherwise, bank account collection is determined by compliance requirements. The default value for this feature is `true`.
# The list of features enabled in the embedded component.
attr_accessor:features
definitialize(enabled:nil,features:nil)
@enabled=enabled
@features=features
end
end
classBalances<Stripe::RequestParams
classFeatures<Stripe::RequestParams
# Disables Stripe user authentication for this embedded component. This value can only be true for accounts where `controller.requirement_collection` is `application`. The default value is the opposite of the `external_account_collection` value. For example, if you don’t set `external_account_collection`, it defaults to true and `disable_stripe_user_authentication` defaults to false.
attr_accessor:disable_stripe_user_authentication
# Whether to allow payout schedule to be changed. Default `true` when Stripe owns Loss Liability, default `false` otherwise.
attr_accessor:edit_payout_schedule
# Whether to allow platforms to control bank account collection for their connected accounts. This feature can only be false for accounts where you’re responsible for collecting updated information when requirements are due or change, like custom accounts. Otherwise, bank account collection is determined by compliance requirements. The default value for this feature is `true`.
attr_accessor:external_account_collection
# Whether to allow creation of instant payouts. Default `true` when Stripe owns Loss Liability, default `false` otherwise.
attr_accessor:instant_payouts
# Whether to allow creation of standard payouts. Default `true` when Stripe owns Loss Liability, default `false` otherwise.
# The list of features enabled in the embedded component.
attr_accessor:features
definitialize(enabled:nil,features:nil)
@enabled=enabled
@features=features
end
end
classDocuments<Stripe::RequestParams
classFeatures<Stripe::RequestParams;end
# Whether the embedded component is enabled.
attr_accessor:enabled
# The list of features enabled in the embedded component.
attr_accessor:features
definitialize(enabled:nil,features:nil)
@enabled=enabled
@features=features
end
end
classFinancialAccount<Stripe::RequestParams
classFeatures<Stripe::RequestParams
# Disables Stripe user authentication for this embedded component. This value can only be true for accounts where `controller.requirement_collection` is `application`. The default value is the opposite of the `external_account_collection` value. For example, if you don’t set `external_account_collection`, it defaults to true and `disable_stripe_user_authentication` defaults to false.
attr_accessor:disable_stripe_user_authentication
# Whether to allow external accounts to be linked for money transfer.
# The list of features enabled in the embedded component.
attr_accessor:features
definitialize(enabled:nil,features:nil)
@enabled=enabled
@features=features
end
end
classIssuingCardsList<Stripe::RequestParams
classFeatures<Stripe::RequestParams
# Whether to allow card management features.
attr_accessor:card_management
# Whether to allow card spend dispute management features.
attr_accessor:card_spend_dispute_management
# Whether to allow cardholder management features.
attr_accessor:cardholder_management
# Disables Stripe user authentication for this embedded component. This feature can only be false for accounts where you’re responsible for collecting updated information when requirements are due or change, like custom accounts.
attr_accessor:disable_stripe_user_authentication
# Whether to allow spend control management features.
# The list of features enabled in the embedded component.
attr_accessor:features
definitialize(enabled:nil,features:nil)
@enabled=enabled
@features=features
end
end
classNotificationBanner<Stripe::RequestParams
classFeatures<Stripe::RequestParams
# Disables Stripe user authentication for this embedded component. This value can only be true for accounts where `controller.requirement_collection` is `application`. The default value is the opposite of the `external_account_collection` value. For example, if you don’t set `external_account_collection`, it defaults to true and `disable_stripe_user_authentication` defaults to false.
attr_accessor:disable_stripe_user_authentication
# Whether to allow platforms to control bank account collection for their connected accounts. This feature can only be false for accounts where you’re responsible for collecting updated information when requirements are due or change, like custom accounts. Otherwise, bank account collection is determined by compliance requirements. The default value for this feature is `true`.
# The list of features enabled in the embedded component.
attr_accessor:features
definitialize(enabled:nil,features:nil)
@enabled=enabled
@features=features
end
end
classPayouts<Stripe::RequestParams
classFeatures<Stripe::RequestParams
# Disables Stripe user authentication for this embedded component. This value can only be true for accounts where `controller.requirement_collection` is `application`. The default value is the opposite of the `external_account_collection` value. For example, if you don’t set `external_account_collection`, it defaults to true and `disable_stripe_user_authentication` defaults to false.
attr_accessor:disable_stripe_user_authentication
# Whether to allow payout schedule to be changed. Default `true` when Stripe owns Loss Liability, default `false` otherwise.
attr_accessor:edit_payout_schedule
# Whether to allow platforms to control bank account collection for their connected accounts. This feature can only be false for accounts where you’re responsible for collecting updated information when requirements are due or change, like custom accounts. Otherwise, bank account collection is determined by compliance requirements. The default value for this feature is `true`.
attr_accessor:external_account_collection
# Whether to allow creation of instant payouts. Default `true` when Stripe owns Loss Liability, default `false` otherwise.
attr_accessor:instant_payouts
# Whether to allow creation of standard payouts. Default `true` when Stripe owns Loss Liability, default `false` otherwise.
# The identifier of the account to create an Account Session for.
attr_accessor:account
# Each key of the dictionary represents an embedded component, and each embedded component maps to its configuration (e.g. whether it has been enabled or not).
attr_accessor:components
# Specifies which fields in the response should be expanded.
# The ID of the account the AccountSession was created for
attr_reader:account
# The client secret of this AccountSession. Used on the client to set up secure access to the given `account`.
#
# The client secret can be used to provide access to `account` from your frontend. It should not be stored, logged, or exposed to anyone other than the connected account. Make sure that you have TLS enabled on any page that includes the client secret.
#
# Refer to our docs to [setup Connect embedded components](https://stripe.com/docs/connect/get-started-connect-embedded-components) and learn about how `client_secret` should be handled.
attr_reader:client_secret
# Attribute for field components
attr_reader:components
# The timestamp at which this AccountSession will expire.
attr_reader:expires_at
# Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode.
attr_reader:livemode
# String representing the object's type. Objects of the same type share the same value.
attr_reader:object
# Creates a AccountSession object that includes a single-use token that the platform can use on their front-end to grant client-side API access.
# A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list.
attr_accessor:ending_before
# Specifies which fields in the response should be expanded.
attr_accessor:expand
# A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.
attr_accessor:limit
# A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list.
attr_accessor:starting_after
definitialize(
domain_name:nil,
ending_before:nil,
expand:nil,
limit:nil,
starting_after:nil
)
@domain_name=domain_name
@ending_before=ending_before
@expand=expand
@limit=limit
@starting_after=starting_after
end
end
classCreateParams<Stripe::RequestParams
# Attribute for param field domain_name
attr_accessor:domain_name
# Specifies which fields in the response should be expanded.
attr_accessor:expand
definitialize(domain_name:nil,expand:nil)
@domain_name=domain_name
@expand=expand
end
end
# Time at which the object was created. Measured in seconds since the Unix epoch.
attr_reader:created
# Attribute for field domain_name
attr_reader:domain_name
# Unique identifier for the object.
attr_reader:id
# Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode.
attr_reader:livemode
# String representing the object's type. Objects of the same type share the same value.
# Type of object that created the application fee.
attr_reader:type
end
classListParams<Stripe::RequestParams
classCreated<Stripe::RequestParams
# Minimum value to filter by (exclusive)
attr_accessor:gt
# Minimum value to filter by (inclusive)
attr_accessor:gte
# Maximum value to filter by (exclusive)
attr_accessor:lt
# Maximum value to filter by (inclusive)
attr_accessor:lte
definitialize(gt:nil,gte:nil,lt:nil,lte:nil)
@gt=gt
@gte=gte
@lt=lt
@lte=lte
end
end
# Only return application fees for the charge specified by this charge ID.
attr_accessor:charge
# Only return applications fees that were created during the given date interval.
attr_accessor:created
# A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list.
attr_accessor:ending_before
# Specifies which fields in the response should be expanded.
attr_accessor:expand
# A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.
attr_accessor:limit
# A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list.
attr_accessor:starting_after
definitialize(
charge:nil,
created:nil,
ending_before:nil,
expand:nil,
limit:nil,
starting_after:nil
)
@charge=charge
@created=created
@ending_before=ending_before
@expand=expand
@limit=limit
@starting_after=starting_after
end
end
# ID of the Stripe account this fee was taken from.
attr_reader:account
# Amount earned, in cents (or local equivalent).
attr_reader:amount
# Amount in cents (or local equivalent) refunded (can be less than the amount attribute on the fee if a partial refund was issued)
attr_reader:amount_refunded
# ID of the Connect application that earned the fee.
attr_reader:application
# Balance transaction that describes the impact of this collected application fee on your account balance (not including refunds).
attr_reader:balance_transaction
# ID of the charge that the application fee was taken from.
attr_reader:charge
# Time at which the object was created. Measured in seconds since the Unix epoch.
attr_reader:created
# Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies).
attr_reader:currency
# Polymorphic source of the application fee. Includes the ID of the object the application fee was created from.
attr_reader:fee_source
# Unique identifier for the object.
attr_reader:id
# Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode.
attr_reader:livemode
# String representing the object's type. Objects of the same type share the same value.
attr_reader:object
# ID of the corresponding charge on the platform account, if this fee was the result of a charge using the `destination` parameter.
attr_reader:originating_transaction
# Whether the fee has been fully refunded. If the fee is only partially refunded, this attribute will still be false.
attr_reader:refunded
# A list of refunds that have been applied to the fee.
attr_reader:refunds
# Returns a list of application fees you've previously collected. The application fees are returned in sorted order, with the most recent fees appearing first.
# `Application Fee Refund` objects allow you to refund an application fee that
# has previously been created but not yet refunded. Funds will be refunded to
# the Stripe account from which the fee was originally collected.
#
# Related guide: [Refunding application fees](https://stripe.com/docs/connect/destination-charges#refunding-app-fee)
classApplicationFeeRefund<APIResource
includeStripe::APIOperations::Save
OBJECT_NAME="fee_refund"
defself.object_name
"fee_refund"
end
# Amount, in cents (or local equivalent).
attr_reader:amount
# Balance transaction that describes the impact on your account balance.
attr_reader:balance_transaction
# Time at which the object was created. Measured in seconds since the Unix epoch.
attr_reader:created
# Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies).
attr_reader:currency
# ID of the application fee that was refunded.
attr_reader:fee
# Unique identifier for the object.
attr_reader:id
# Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
attr_reader:metadata
# String representing the object's type. Objects of the same type share the same value.
# Secret Store is an API that allows Stripe Apps developers to securely persist secrets for use by UI Extensions and app backends.
#
# The primary resource in Secret Store is a `secret`. Other apps can't view secrets created by an app. Additionally, secrets are scoped to provide further permission control.
#
# All Dashboard users and the app backend share `account` scoped secrets. Use the `account` scope for secrets that don't change per-user, like a third-party API key.
#
# A `user` scoped secret is accessible by the app backend and one specific Dashboard user. Use the `user` scope for per-user secrets like per-user OAuth tokens, where different users might have different permissions.
#
# Related guide: [Store data between page reloads](https://stripe.com/docs/stripe-apps/store-auth-data-custom-objects)
classSecret<APIResource
extendStripe::APIOperations::Create
extendStripe::APIOperations::List
OBJECT_NAME="apps.secret"
defself.object_name
"apps.secret"
end
classScope<Stripe::StripeObject
# The secret scope type.
attr_reader:type
# The user ID, if type is set to "user"
attr_reader:user
end
classListParams<Stripe::RequestParams
classScope<Stripe::RequestParams
# The secret scope type.
attr_accessor:type
# The user ID. This field is required if `type` is set to `user`, and should not be provided if `type` is set to `account`.
attr_accessor:user
definitialize(type:nil,user:nil)
@type=type
@user=user
end
end
# A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list.
attr_accessor:ending_before
# Specifies which fields in the response should be expanded.
attr_accessor:expand
# A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.
attr_accessor:limit
# Specifies the scoping of the secret. Requests originating from UI extensions can only access account-scoped secrets or secrets scoped to their own user.
attr_accessor:scope
# A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list.
# The user ID. This field is required if `type` is set to `user`, and should not be provided if `type` is set to `account`.
attr_accessor:user
definitialize(type:nil,user:nil)
@type=type
@user=user
end
end
# Specifies which fields in the response should be expanded.
attr_accessor:expand
# The Unix timestamp for the expiry time of the secret, after which the secret deletes.
attr_accessor:expires_at
# A name for the secret that's unique within the scope.
attr_accessor:name
# The plaintext secret value to be stored.
attr_accessor:payload
# Specifies the scoping of the secret. Requests originating from UI extensions can only access account-scoped secrets or secrets scoped to their own user.
# The user ID. This field is required if `type` is set to `user`, and should not be provided if `type` is set to `account`.
attr_accessor:user
definitialize(type:nil,user:nil)
@type=type
@user=user
end
end
# Specifies which fields in the response should be expanded.
attr_accessor:expand
# A name for the secret that's unique within the scope.
attr_accessor:name
# Specifies the scoping of the secret. Requests originating from UI extensions can only access account-scoped secrets or secrets scoped to their own user.
attr_accessor:scope
definitialize(expand:nil,name:nil,scope:nil)
@expand=expand
@name=name
@scope=scope
end
end
classDeleteWhereParams<Stripe::RequestParams
classScope<Stripe::RequestParams
# The secret scope type.
attr_accessor:type
# The user ID. This field is required if `type` is set to `user`, and should not be provided if `type` is set to `account`.
attr_accessor:user
definitialize(type:nil,user:nil)
@type=type
@user=user
end
end
# Specifies which fields in the response should be expanded.
attr_accessor:expand
# A name for the secret that's unique within the scope.
attr_accessor:name
# Specifies the scoping of the secret. Requests originating from UI extensions can only access account-scoped secrets or secrets scoped to their own user.
attr_accessor:scope
definitialize(expand:nil,name:nil,scope:nil)
@expand=expand
@name=name
@scope=scope
end
end
# Time at which the object was created. Measured in seconds since the Unix epoch.
attr_reader:created
# If true, indicates that this secret has been deleted
attr_reader:deleted
# The Unix timestamp for the expiry time of the secret, after which the secret deletes.
attr_reader:expires_at
# Unique identifier for the object.
attr_reader:id
# Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode.
attr_reader:livemode
# A name for the secret that's unique within the scope.
attr_reader:name
# String representing the object's type. Objects of the same type share the same value.
# This is an object representing your Stripe balance. You can retrieve it to see
# the balance currently on your Stripe account.
#
# You can also retrieve the balance history, which contains a list of
# [transactions](https://stripe.com/docs/reporting/balance-transaction-types) that contributed to the balance
# (charges, payouts, and so forth).
#
# The available and pending amounts for each currency are broken down further by
# payment source types.
#
# Related guide: [Understanding Connect account balances](https://stripe.com/docs/connect/account-balances)
classBalance<SingletonAPIResource
OBJECT_NAME="balance"
defself.object_name
"balance"
end
classAvailable<Stripe::StripeObject
classSourceTypes<Stripe::StripeObject
# Amount coming from [legacy US ACH payments](https://docs.stripe.com/ach-deprecated).
attr_reader:bank_account
# Amount coming from most payment methods, including cards as well as [non-legacy bank debits](https://docs.stripe.com/payments/bank-debits).
attr_reader:card
# Amount coming from [FPX](https://docs.stripe.com/payments/fpx), a Malaysian payment method.
attr_reader:fpx
end
# Balance amount.
attr_reader:amount
# Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies).
attr_reader:currency
# Attribute for field source_types
attr_reader:source_types
end
classConnectReserved<Stripe::StripeObject
classSourceTypes<Stripe::StripeObject
# Amount coming from [legacy US ACH payments](https://docs.stripe.com/ach-deprecated).
attr_reader:bank_account
# Amount coming from most payment methods, including cards as well as [non-legacy bank debits](https://docs.stripe.com/payments/bank-debits).
attr_reader:card
# Amount coming from [FPX](https://docs.stripe.com/payments/fpx), a Malaysian payment method.
attr_reader:fpx
end
# Balance amount.
attr_reader:amount
# Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies).
attr_reader:currency
# Attribute for field source_types
attr_reader:source_types
end
classInstantAvailable<Stripe::StripeObject
classNetAvailable<Stripe::StripeObject
classSourceTypes<Stripe::StripeObject
# Amount coming from [legacy US ACH payments](https://docs.stripe.com/ach-deprecated).
attr_reader:bank_account
# Amount coming from most payment methods, including cards as well as [non-legacy bank debits](https://docs.stripe.com/payments/bank-debits).
attr_reader:card
# Amount coming from [FPX](https://docs.stripe.com/payments/fpx), a Malaysian payment method.
attr_reader:fpx
end
# Net balance amount, subtracting fees from platform-set pricing.
attr_reader:amount
# ID of the external account for this net balance (not expandable).
attr_reader:destination
# Attribute for field source_types
attr_reader:source_types
end
classSourceTypes<Stripe::StripeObject
# Amount coming from [legacy US ACH payments](https://docs.stripe.com/ach-deprecated).
attr_reader:bank_account
# Amount coming from most payment methods, including cards as well as [non-legacy bank debits](https://docs.stripe.com/payments/bank-debits).
attr_reader:card
# Amount coming from [FPX](https://docs.stripe.com/payments/fpx), a Malaysian payment method.
attr_reader:fpx
end
# Balance amount.
attr_reader:amount
# Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies).
attr_reader:currency
# Breakdown of balance by destination.
attr_reader:net_available
# Attribute for field source_types
attr_reader:source_types
end
classIssuing<Stripe::StripeObject
classAvailable<Stripe::StripeObject
classSourceTypes<Stripe::StripeObject
# Amount coming from [legacy US ACH payments](https://docs.stripe.com/ach-deprecated).
attr_reader:bank_account
# Amount coming from most payment methods, including cards as well as [non-legacy bank debits](https://docs.stripe.com/payments/bank-debits).
attr_reader:card
# Amount coming from [FPX](https://docs.stripe.com/payments/fpx), a Malaysian payment method.
attr_reader:fpx
end
# Balance amount.
attr_reader:amount
# Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies).
attr_reader:currency
# Attribute for field source_types
attr_reader:source_types
end
# Funds that are available for use.
attr_reader:available
end
classPending<Stripe::StripeObject
classSourceTypes<Stripe::StripeObject
# Amount coming from [legacy US ACH payments](https://docs.stripe.com/ach-deprecated).
attr_reader:bank_account
# Amount coming from most payment methods, including cards as well as [non-legacy bank debits](https://docs.stripe.com/payments/bank-debits).
attr_reader:card
# Amount coming from [FPX](https://docs.stripe.com/payments/fpx), a Malaysian payment method.
attr_reader:fpx
end
# Balance amount.
attr_reader:amount
# Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies).
# Amount coming from [legacy US ACH payments](https://docs.stripe.com/ach-deprecated).
attr_reader:bank_account
# Amount coming from most payment methods, including cards as well as [non-legacy bank debits](https://docs.stripe.com/payments/bank-debits).
attr_reader:card
# Amount coming from [FPX](https://docs.stripe.com/payments/fpx), a Malaysian payment method.
attr_reader:fpx
end
# Balance amount.
attr_reader:amount
# Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies).
attr_reader:currency
# Attribute for field source_types
attr_reader:source_types
end
classPending<Stripe::StripeObject
classSourceTypes<Stripe::StripeObject
# Amount coming from [legacy US ACH payments](https://docs.stripe.com/ach-deprecated).
attr_reader:bank_account
# Amount coming from most payment methods, including cards as well as [non-legacy bank debits](https://docs.stripe.com/payments/bank-debits).
attr_reader:card
# Amount coming from [FPX](https://docs.stripe.com/payments/fpx), a Malaysian payment method.
attr_reader:fpx
end
# Balance amount.
attr_reader:amount
# Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies).
attr_reader:currency
# Attribute for field source_types
attr_reader:source_types
end
# Funds that are available for use.
attr_reader:available
# Funds that are pending
attr_reader:pending
end
# Available funds that you can transfer or pay out automatically by Stripe or explicitly through the [Transfers API](https://stripe.com/docs/api#transfers) or [Payouts API](https://stripe.com/docs/api#payouts). You can find the available balance for each currency and payment type in the `source_types` property.
attr_reader:available
# Funds held due to negative balances on connected accounts where [account.controller.requirement_collection](/api/accounts/object#account_object-controller-requirement_collection) is `application`, which includes Custom accounts. You can find the connect reserve balance for each currency and payment type in the `source_types` property.
attr_reader:connect_reserved
# Funds that you can pay out using Instant Payouts.
attr_reader:instant_available
# Attribute for field issuing
attr_reader:issuing
# Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode.
attr_reader:livemode
# String representing the object's type. Objects of the same type share the same value.
attr_reader:object
# Funds that aren't available in the balance yet. You can find the pending balance for each currency and each payment type in the `source_types` property.
attr_reader:pending
# Attribute for field refund_and_dispute_prefunding
# Balance transactions represent funds moving through your Stripe account.
# Stripe creates them for every type of transaction that enters or leaves your Stripe account balance.
#
# Related guide: [Balance transaction types](https://stripe.com/docs/reports/balance-transaction-types)
classBalanceTransaction<APIResource
extendStripe::APIOperations::List
OBJECT_NAME="balance_transaction"
defself.object_name
"balance_transaction"
end
classFeeDetail<Stripe::StripeObject
# Amount of the fee, in cents.
attr_reader:amount
# ID of the Connect application that earned the fee.
attr_reader:application
# Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies).
attr_reader:currency
# An arbitrary string attached to the object. Often useful for displaying to users.
attr_reader:description
# Type of the fee, one of: `application_fee`, `payment_method_passthrough_fee`, `stripe_fee` or `tax`.
attr_reader:type
end
classListParams<Stripe::RequestParams
classCreated<Stripe::RequestParams
# Minimum value to filter by (exclusive)
attr_accessor:gt
# Minimum value to filter by (inclusive)
attr_accessor:gte
# Maximum value to filter by (exclusive)
attr_accessor:lt
# Maximum value to filter by (inclusive)
attr_accessor:lte
definitialize(gt:nil,gte:nil,lt:nil,lte:nil)
@gt=gt
@gte=gte
@lt=lt
@lte=lte
end
end
# Only return transactions that were created during the given date interval.
attr_accessor:created
# Only return transactions in a certain currency. Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies).
attr_accessor:currency
# A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list.
attr_accessor:ending_before
# Specifies which fields in the response should be expanded.
attr_accessor:expand
# A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.
attr_accessor:limit
# For automatic Stripe payouts only, only returns transactions that were paid out on the specified payout ID.
attr_accessor:payout
# Only returns the original transaction.
attr_accessor:source
# A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list.
attr_accessor:starting_after
# Only returns transactions of the given type. One of: `adjustment`, `advance`, `advance_funding`, `anticipation_repayment`, `application_fee`, `application_fee_refund`, `charge`, `climate_order_purchase`, `climate_order_refund`, `connect_collection_transfer`, `contribution`, `issuing_authorization_hold`, `issuing_authorization_release`, `issuing_dispute`, `issuing_transaction`, `obligation_outbound`, `obligation_reversal_inbound`, `payment`, `payment_failure_refund`, `payment_network_reserve_hold`, `payment_network_reserve_release`, `payment_refund`, `payment_reversal`, `payment_unreconciled`, `payout`, `payout_cancel`, `payout_failure`, `payout_minimum_balance_hold`, `payout_minimum_balance_release`, `refund`, `refund_failure`, `reserve_transaction`, `reserved_funds`, `stripe_fee`, `stripe_fx_fee`, `stripe_balance_payment_debit`, `stripe_balance_payment_debit_reversal`, `tax_fee`, `topup`, `topup_reversal`, `transfer`, `transfer_cancel`, `transfer_failure`, or `transfer_refund`.
attr_accessor:type
definitialize(
created:nil,
currency:nil,
ending_before:nil,
expand:nil,
limit:nil,
payout:nil,
source:nil,
starting_after:nil,
type:nil
)
@created=created
@currency=currency
@ending_before=ending_before
@expand=expand
@limit=limit
@payout=payout
@source=source
@starting_after=starting_after
@type=type
end
end
# Gross amount of this transaction (in cents (or local equivalent)). A positive value represents funds charged to another party, and a negative value represents funds sent to another party.
attr_reader:amount
# The date that the transaction's net funds become available in the Stripe balance.
attr_reader:available_on
# The balance that this transaction impacts.
attr_reader:balance_type
# Time at which the object was created. Measured in seconds since the Unix epoch.
attr_reader:created
# Three-letter [ISO currency code](https://www.iso.org/iso-4217-currency-codes.html), in lowercase. Must be a [supported currency](https://stripe.com/docs/currencies).
attr_reader:currency
# An arbitrary string attached to the object. Often useful for displaying to users.
attr_reader:description
# If applicable, this transaction uses an exchange rate. If money converts from currency A to currency B, then the `amount` in currency A, multipled by the `exchange_rate`, equals the `amount` in currency B. For example, if you charge a customer 10.00 EUR, the PaymentIntent's `amount` is `1000` and `currency` is `eur`. If this converts to 12.34 USD in your Stripe account, the BalanceTransaction's `amount` is `1234`, its `currency` is `usd`, and the `exchange_rate` is `1.234`.
attr_reader:exchange_rate
# Fees (in cents (or local equivalent)) paid for this transaction. Represented as a positive integer when assessed.
attr_reader:fee
# Detailed breakdown of fees (in cents (or local equivalent)) paid for this transaction.
attr_reader:fee_details
# Unique identifier for the object.
attr_reader:id
# Net impact to a Stripe balance (in cents (or local equivalent)). A positive value represents incrementing a Stripe balance, and a negative value decrementing a Stripe balance. You can calculate the net impact of a transaction on a balance by `amount` - `fee`
attr_reader:net
# String representing the object's type. Objects of the same type share the same value.
attr_reader:object
# Learn more about how [reporting categories](https://stripe.com/docs/reports/reporting-categories) can help you understand balance transactions from an accounting perspective.
attr_reader:reporting_category
# This transaction relates to the Stripe object.
attr_reader:source
# The transaction's net funds status in the Stripe balance, which are either `available` or `pending`.
attr_reader:status
# Transaction type: `adjustment`, `advance`, `advance_funding`, `anticipation_repayment`, `application_fee`, `application_fee_refund`, `charge`, `climate_order_purchase`, `climate_order_refund`, `connect_collection_transfer`, `contribution`, `issuing_authorization_hold`, `issuing_authorization_release`, `issuing_dispute`, `issuing_transaction`, `obligation_outbound`, `obligation_reversal_inbound`, `payment`, `payment_failure_refund`, `payment_network_reserve_hold`, `payment_network_reserve_release`, `payment_refund`, `payment_reversal`, `payment_unreconciled`, `payout`, `payout_cancel`, `payout_failure`, `payout_minimum_balance_hold`, `payout_minimum_balance_release`, `refund`, `refund_failure`, `reserve_transaction`, `reserved_funds`, `stripe_fee`, `stripe_fx_fee`, `stripe_balance_payment_debit`, `stripe_balance_payment_debit_reversal`, `tax_fee`, `topup`, `topup_reversal`, `transfer`, `transfer_cancel`, `transfer_failure`, or `transfer_refund`. Learn more about [balance transaction types and what they represent](https://stripe.com/docs/reports/balance-transaction-types). To classify transactions for accounting purposes, consider `reporting_category` instead.
attr_reader:type
# Returns a list of transactions that have contributed to the Stripe account balance (e.g., charges, transfers, and so forth). The transactions are returned in sorted order, with the most recent transactions appearing first.
#
# Note that this endpoint was previously called “Balance history” and used the path /v1/balance/history.
# These bank accounts are payment methods on `Customer` objects.
#
# On the other hand [External Accounts](https://docs.stripe.com/api#external_accounts) are transfer
# destinations on `Account` objects for connected accounts.
# They can be bank accounts or debit cards as well, and are documented in the links above.
#
# Related guide: [Bank debits and transfers](https://docs.stripe.com/payments/bank-debits-transfers)
classBankAccount<APIResource
includeStripe::APIOperations::Delete
extendStripe::APIOperations::List
includeStripe::APIOperations::Save
OBJECT_NAME="bank_account"
defself.object_name
"bank_account"
end
classFutureRequirements<Stripe::StripeObject
classError<Stripe::StripeObject
# The code for the type of error.
attr_reader:code
# An informative message that indicates the error type and provides additional details about the error.
attr_reader:reason
# The specific user onboarding requirement field (in the requirements hash) that needs to be resolved.
attr_reader:requirement
end
# Fields that need to be collected to keep the external account enabled. If not collected by `current_deadline`, these fields appear in `past_due` as well, and the account is disabled.
attr_reader:currently_due
# Fields that are `currently_due` and need to be collected again because validation or verification failed.
attr_reader:errors
# Fields that weren't collected by `current_deadline`. These fields need to be collected to enable the external account.
attr_reader:past_due
# Fields that might become required depending on the results of verification or review. It's an empty array unless an asynchronous verification is pending. If verification fails, these fields move to `eventually_due`, `currently_due`, or `past_due`. Fields might appear in `eventually_due`, `currently_due`, or `past_due` and in `pending_verification` if verification fails but another verification is still pending.
attr_reader:pending_verification
end
classRequirements<Stripe::StripeObject
classError<Stripe::StripeObject
# The code for the type of error.
attr_reader:code
# An informative message that indicates the error type and provides additional details about the error.
attr_reader:reason
# The specific user onboarding requirement field (in the requirements hash) that needs to be resolved.
attr_reader:requirement
end
# Fields that need to be collected to keep the external account enabled. If not collected by `current_deadline`, these fields appear in `past_due` as well, and the account is disabled.
attr_reader:currently_due
# Fields that are `currently_due` and need to be collected again because validation or verification failed.
attr_reader:errors
# Fields that weren't collected by `current_deadline`. These fields need to be collected to enable the external account.
attr_reader:past_due
# Fields that might become required depending on the results of verification or review. It's an empty array unless an asynchronous verification is pending. If verification fails, these fields move to `eventually_due`, `currently_due`, or `past_due`. Fields might appear in `eventually_due`, `currently_due`, or `past_due` and in `pending_verification` if verification fails but another verification is still pending.
attr_reader:pending_verification
end
# The account this bank account belongs to. Only applicable on Accounts (not customers or recipients) This property is only available when returned as an [External Account](/api/external_account_bank_accounts/object) where [controller.is_controller](/api/accounts/object#account_object-controller-is_controller) is `true`.
attr_reader:account
# The name of the person or business that owns the bank account.
attr_reader:account_holder_name
# The type of entity that holds the account. This can be either `individual` or `company`.
attr_reader:account_holder_type
# The bank account type. This can only be `checking` or `savings` in most countries. In Japan, this can only be `futsu` or `toza`.
attr_reader:account_type
# A set of available payout methods for this bank account. Only values from this set should be passed as the `method` when creating a payout.
attr_reader:available_payout_methods
# Name of the bank associated with the routing number (e.g., `WELLS FARGO`).
attr_reader:bank_name
# Two-letter ISO code representing the country the bank account is located in.
attr_reader:country
# Three-letter [ISO code for the currency](https://stripe.com/docs/payouts) paid out to the bank account.
attr_reader:currency
# The ID of the customer that the bank account is associated with.
attr_reader:customer
# Whether this bank account is the default external account for its currency.
attr_reader:default_for_currency
# Uniquely identifies this particular bank account. You can use this attribute to check whether two bank accounts are the same.
attr_reader:fingerprint
# Information about the [upcoming new requirements for the bank account](https://stripe.com/docs/connect/custom-accounts/future-requirements), including what information needs to be collected, and by when.
attr_reader:future_requirements
# Unique identifier for the object.
attr_reader:id
# The last four digits of the bank account number.
attr_reader:last4
# Set of [key-value pairs](https://stripe.com/docs/api/metadata) that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
attr_reader:metadata
# String representing the object's type. Objects of the same type share the same value.
attr_reader:object
# Information about the requirements for the bank account, including what information needs to be collected.
attr_reader:requirements
# The routing transit number for the bank account.
attr_reader:routing_number
# For bank accounts, possible values are `new`, `validated`, `verified`, `verification_failed`, or `errored`. A bank account that hasn't had any activity or validation performed is `new`. If Stripe can determine that the bank account exists, its status will be `validated`. Note that there often isn’t enough information to know (e.g., for smaller credit unions), and the validation is not always run. If customer bank account verification has succeeded, the bank account status will be `verified`. If the verification failed for any reason, such as microdeposit failure, the status will be `verification_failed`. If a payout sent to this bank account fails, we'll set the status to `errored` and will not continue to send [scheduled payouts](https://stripe.com/docs/payouts#payout-schedule) until the bank details are updated.
#
# For external accounts, possible values are `new`, `errored` and `verification_failed`. If a payout fails, the status is set to `errored` and scheduled payouts are stopped until account details are updated. In the US and India, if we can't [verify the owner of the bank account](https://support.stripe.com/questions/bank-account-ownership-verification), we'll set the status to `verification_failed`. Other validations aren't run against external accounts because they're only used for payouts. This means the other statuses don't apply.
# A billing alert is a resource that notifies you when a certain usage threshold on a meter is crossed. For example, you might create a billing alert to notify you when a certain user made 100 API requests.
classAlert<APIResource
extendStripe::APIOperations::Create
extendStripe::APIOperations::List
OBJECT_NAME="billing.alert"
defself.object_name
"billing.alert"
end
classUsageThreshold<Stripe::StripeObject
classFilter<Stripe::StripeObject
# Limit the scope of the alert to this customer ID
attr_reader:customer
# Attribute for field type
attr_reader:type
end
# The filters allow limiting the scope of this usage alert. You can only specify up to one filter at this time.
attr_reader:filters
# The value at which this alert will trigger.
attr_reader:gte
# The [Billing Meter](/api/billing/meter) ID whose usage is monitored.
attr_reader:meter
# Defines how the alert will behave.
attr_reader:recurrence
end
classListParams<Stripe::RequestParams
# Filter results to only include this type of alert.
attr_accessor:alert_type
# A cursor for use in pagination. `ending_before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with `obj_bar`, your subsequent call can include `ending_before=obj_bar` in order to fetch the previous page of the list.
attr_accessor:ending_before
# Specifies which fields in the response should be expanded.
attr_accessor:expand
# A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 10.
attr_accessor:limit
# Filter results to only include alerts with the given meter.
attr_accessor:meter
# A cursor for use in pagination. `starting_after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with `obj_foo`, your subsequent call can include `starting_after=obj_foo` in order to fetch the next page of the list.
attr_accessor:starting_after
definitialize(
alert_type:nil,
ending_before:nil,
expand:nil,
limit:nil,
meter:nil,
starting_after:nil
)
@alert_type=alert_type
@ending_before=ending_before
@expand=expand
@limit=limit
@meter=meter
@starting_after=starting_after
end
end
classCreateParams<Stripe::RequestParams
classUsageThreshold<Stripe::RequestParams
classFilter<Stripe::RequestParams
# Limit the scope to this usage alert only to this customer.
attr_accessor:customer
# What type of filter is being applied to this usage alert.
attr_accessor:type
definitialize(customer:nil,type:nil)
@customer=customer
@type=type
end
end
# The filters allows limiting the scope of this usage alert. You can only specify up to one filter at this time.
attr_accessor:filters
# Defines at which value the alert will fire.
attr_accessor:gte
# The [Billing Meter](/api/billing/meter) ID whose usage is monitored.
attr_accessor:meter
# Whether the alert should only fire only once, or once per billing cycle.
# A billing alert is a resource that notifies you when a certain usage threshold on a meter is crossed. For example, you might create a billing alert to notify you when a certain user made 100 API requests.
attr_reader:alert
# Time at which the object was created. Measured in seconds since the Unix epoch.
attr_reader:created
# ID of customer for which the alert triggered
attr_reader:customer
# Has the value `true` if the object exists in live mode or the value `false` if the object exists in test mode.
attr_reader:livemode
# String representing the object's type. Objects of the same type share the same value.
attr_reader:object
# The value triggering the alert
attr_reader:value
end
end
end
Some files were not shown because too many files have changed in this diff
Show More
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.