Compare commits

..

No commits in common. "master" and "v1.17.1" have entirely different histories.

907 changed files with 7805 additions and 524575 deletions

View File

@ -1,10 +0,0 @@
# see http://editorconfig.org/
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
insert_final_newline = true

4
.gitattributes vendored
View File

@ -1,4 +0,0 @@
# may be useful in hiding large schema changes in pull request diffs (but not
# using it for now)
spec/*.json binary
spec/*.yaml binary

2
.github/CODEOWNERS vendored
View File

@ -1,2 +0,0 @@
# All files should be reviewed by a member of the SDKs team
* @stripe/api-library-reviewers

View File

@ -1,78 +0,0 @@
name: Bug report
description: Create a report to help us improve
labels: ["bug"]
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to fill out this bug report!
- type: textarea
id: what-happened
attributes:
label: Describe the bug
description: A clear and concise description of what the bug is.
placeholder: Tell us what you see!
validations:
required: true
- type: textarea
id: repro-steps
attributes:
label: To Reproduce
description: Steps to reproduce the behavior
placeholder: |
1. Fetch a '...'
2. Update the '....'
3. See error
validations:
required: true
- type: textarea
id: expected-behavior
attributes:
label: Expected behavior
description: A clear and concise description of what you expected to happen.
validations:
required: true
- type: textarea
id: code-snippets
attributes:
label: Code snippets
description: If applicable, add code snippets to help explain your problem.
render: Ruby
validations:
required: false
- type: input
id: os
attributes:
label: OS
placeholder: macOS
validations:
required: true
- type: input
id: language-version
attributes:
label: Language version
placeholder: Ruby 3.1.2
validations:
required: true
- type: input
id: lib-version
attributes:
label: Library version
placeholder: stripe-ruby v5.52.0
validations:
required: true
- type: input
id: api-version
attributes:
label: API version
description: See [Versioning](https://stripe.com/docs/api/versioning) in the API Reference to find which version you're using
placeholder: "2020-08-27"
validations:
required: true
- type: textarea
id: additional-context
attributes:
label: Additional context
description: Add any other context about the problem here.
validations:
required: false

View File

@ -1,8 +0,0 @@
blank_issues_enabled: false
contact_links:
- name: Stripe support
url: https://support.stripe.com/
about: |
Please only file issues here that you believe represent actual bugs or feature requests for the Stripe Ruby library.
If you're having general trouble with your Stripe integration, please reach out to support.

View File

@ -1,28 +0,0 @@
name: Feature request
description: Suggest an idea for this library
labels: ["feature-request"]
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to fill out this feature request!
- type: textarea
id: problem
attributes:
label: Is your feature request related to a problem? Please describe.
description: A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
- type: textarea
id: solution
attributes:
label: Describe the solution you'd like
description: A clear and concise description of what you want to happen.
- type: textarea
id: alternatives
attributes:
label: Describe alternatives you've considered
description: A clear and concise description of any alternative solutions or features you've considered.
- type: textarea
id: context
attributes:
label: Additional context
description: Add any other context about the feature request here.

View File

@ -1,11 +0,0 @@
### Why?
<!-- 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. -->

View File

@ -1,87 +0,0 @@
name: CI
on:
workflow_dispatch: {}
push:
branches:
- master
- beta
- sdk-release/**
- feature/**
tags:
- v[0-9]+.[0-9]+.[0-9]+*
pull_request:
branches:
- master
- beta
- sdk-release/**
- feature/**
jobs:
build:
name: Build
runs-on: ubuntu-22.04
steps:
- uses: extractions/setup-just@v2
- uses: actions/checkout@v3
- name: Set up Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: 3.1
- name: Lint
run: just lint
- name: Build
run: gem build stripe.gemspec
- name: 'Upload Artifact'
uses: actions/upload-artifact@v4
with:
name: gems
path: '*.gem'
test:
name: Test (${{ matrix.ruby-version }})
# this version of jruby isn't available in the new latest (24.04) so we have to pin (or update jruby)
runs-on: ubuntu-22.04
strategy:
matrix:
ruby-version: [2.3, 2.4, 2.5, 2.6, 2.7, '3.0', 3.1, 3.2, 3.3, 3.4, jruby-9.4.0.0, truffleruby-head]
steps:
- uses: extractions/setup-just@v2
- uses: actions/checkout@v3
- name: Set up Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: ${{ matrix.ruby-version }}
- uses: stripe/openapi/actions/stripe-mock@master
- name: test
run: just test typecheck
env:
GITHUB_TOKEN: ${{ secrets.github_token }}
publish:
name: Publish
if: >-
((github.event_name == 'workflow_dispatch') || (github.event_name == 'push')) &&
startsWith(github.ref, 'refs/tags/v') &&
endsWith(github.actor, '-stripe')
needs: [build, test]
runs-on: ubuntu-22.04
steps:
- name: Download all workflow run artifacts
uses: actions/download-artifact@v4
with:
name: gems
path: gems
- name: Set up Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: 3.1
- name: Publish gems to Rubygems
run: gem push gems/*.gem
env:
GEM_HOST_API_KEY: ${{secrets.GEM_HOST_API_KEY}}
- uses: stripe/openapi/actions/notify-release@master
if: always()
with:
bot_token: ${{ secrets.SLACK_BOT_TOKEN }}

View File

@ -1,21 +0,0 @@
name: rules
on:
workflow_dispatch: {}
pull_request:
types:
- auto_merge_enabled
jobs:
require_merge_commit_on_merge_script_pr:
name: Merge script PRs must create merge commits
if: ${{ contains(github.head_ref, '/merge-') }}
runs-on: ubuntu-latest
steps:
- run: |
if ${{ github.event.pull_request.auto_merge.merge_method != 'merge' }}; then
echo "Auto-merge method must be 'merge' instead of '${{github.event.pull_request.auto_merge.merge_method}}'"
exit 1
fi

5
.gitignore vendored
View File

@ -2,8 +2,3 @@
/Gemfile.lock /Gemfile.lock
.rvmrc .rvmrc
Gemfile.lock Gemfile.lock
tags
/.bundle/
coverage/
.idea/
.ruby-version

View File

@ -1,398 +0,0 @@
inherit_from: .rubocop_todo.yml
AllCops:
DisplayCopNames: true
TargetRubyVersion: 2.3
Layout/CaseIndentation:
EnforcedStyle: end
Layout/FirstArrayElementIndentation:
EnforcedStyle: consistent
Layout/FirstHashElementIndentation:
EnforcedStyle: consistent
Layout/LineLength:
Exclude:
- "lib/stripe/object_types.rb"
- "lib/stripe/stripe_client.rb"
- "lib/stripe/resources/**/*.rb"
- "lib/stripe/services/**/*.rb"
- "test/**/*.rb"
Lint/MissingSuper:
Exclude:
- "lib/stripe/resources/**/*.rb"
- "lib/stripe/services/**/*.rb"
- "test/stripe/request_params_test.rb"
Metrics/AbcSize:
Enabled: false
Metrics/BlockLength:
Max: 40
Exclude:
# `context` in tests are blocks and get quite large, so exclude the test
# directory from having to adhere to this rule.
- "test/**/*.rb"
Metrics/ClassLength:
Enabled: false
# There are several methods with many branches in api_requestor due to
# request logic.
Metrics/CyclomaticComplexity:
Exclude:
- "lib/stripe/api_requestor.rb"
- "lib/stripe/util.rb"
Metrics/PerceivedComplexity:
Exclude:
- "lib/stripe/api_requestor.rb"
- "lib/stripe/stripe_object.rb"
- "lib/stripe/util.rb"
Metrics/MethodLength:
# There's ~2 long methods in `APIRequestor` and one in `NestedResource`. If
# we want to truncate those a little, we could move this to be closer to ~30
# (but the default of 10 is probably too short).
Max: 55
Exclude:
- "lib/stripe/services/v1_services.rb"
- "lib/stripe/event_types.rb"
AllowedMethods:
- initialize
# TODO(xavdid): remove this once the first `basil` release is out
Naming/MethodName:
# these endpoints are removed soon so we pulled their overrides, meaning their names are wrong
# that won't make it out to users, but it's breaking linting/formatting in the meantime
Exclude:
- "lib/stripe/services/invoice_service.rb"
- "lib/stripe/resources/invoice.rb"
Metrics/ModuleLength:
Enabled: false
Metrics/ParameterLists:
# There's 2 methods in `StripeClient` that have long parameter lists.
Max: 8
# Optional parameters should be consistent across libraries, we need not be
# concerned about this. Was introduced with adding `base_address`
Exclude:
- "lib/stripe/api_operations/request.rb"
- "lib/stripe/stripe_object.rb"
- "lib/stripe/stripe_client.rb"
- "lib/stripe/resources/**/*.rb"
- "lib/stripe/services/**/*.rb"
Naming/MethodParameterName:
# We have many parameters that are less than 3 characters for tax codes
Exclude:
- "lib/stripe/resources/**/*.rb"
- "lib/stripe/services/**/*.rb"
Naming/VariableNumber:
# We use a variety of variable number syntaxes
Exclude:
- "lib/stripe/resources/**/*.rb"
- "lib/stripe/services/**/*.rb"
Style/AccessModifierDeclarations:
EnforcedStyle: inline
Style/AsciiComments:
Enabled: false
Style/FrozenStringLiteralComment:
EnforcedStyle: always
Style/HashEachMethods:
Enabled: true
Style/HashTransformKeys:
Enabled: true
Style/HashTransformValues:
Enabled: true
Style/NumericPredicate:
Enabled: false
Style/StringLiterals:
EnforcedStyle: double_quotes
Style/TrailingCommaInArrayLiteral:
EnforcedStyleForMultiline: consistent_comma
Style/TrailingCommaInHashLiteral:
EnforcedStyleForMultiline: consistent_comma
Gemspec/DeprecatedAttributeAssignment: # new in 1.30
Enabled: true
Gemspec/DevelopmentDependencies: # new in 1.44
Enabled: true
Gemspec/RequireMFA: # new in 1.23
Enabled: false
Layout/LineContinuationLeadingSpace: # new in 1.31
Enabled: true
Layout/LineContinuationSpacing: # new in 1.31
Enabled: true
Layout/LineEndStringConcatenationIndentation: # new in 1.18
Enabled: true
Layout/SpaceBeforeBrackets: # new in 1.7
Enabled: true
Lint/AmbiguousAssignment: # new in 1.7
Enabled: true
Lint/AmbiguousOperatorPrecedence: # new in 1.21
Enabled: true
Lint/AmbiguousRange: # new in 1.19
Enabled: true
Lint/ConstantOverwrittenInRescue: # new in 1.31
Enabled: true
Lint/DeprecatedConstants: # new in 1.8
Enabled: true
Lint/DuplicateBranch: # new in 1.3
Enabled: true
Lint/DuplicateMagicComment: # new in 1.37
Enabled: true
Lint/DuplicateMatchPattern: # new in 1.50
Enabled: true
Lint/DuplicateRegexpCharacterClassElement: # new in 1.1
Enabled: true
Lint/EmptyBlock: # new in 1.1
Enabled: true
Lint/EmptyClass: # new in 1.3
Enabled: true
Lint/EmptyInPattern: # new in 1.16
Enabled: true
Lint/IncompatibleIoSelectWithFiberScheduler: # new in 1.21
Enabled: true
Lint/LambdaWithoutLiteralBlock: # new in 1.8
Enabled: true
Lint/MixedCaseRange: # new in 1.53
Enabled: true
Lint/NoReturnInBeginEndBlocks: # new in 1.2
Enabled: true
Lint/NonAtomicFileOperation: # new in 1.31
Enabled: true
Lint/NumberedParameterAssignment: # new in 1.9
Enabled: true
Lint/OrAssignmentToConstant: # new in 1.9
Enabled: true
Lint/RedundantDirGlobSort: # new in 1.8
Enabled: true
Lint/RedundantRegexpQuantifiers: # new in 1.53
Enabled: true
Lint/RefinementImportMethods: # new in 1.27
Enabled: true
Lint/RequireRangeParentheses: # new in 1.32
Enabled: true
Lint/RequireRelativeSelfPath: # new in 1.22
Enabled: true
Lint/SymbolConversion: # new in 1.9
Enabled: true
Lint/ToEnumArguments: # new in 1.1
Enabled: true
Lint/TripleQuotes: # new in 1.9
Enabled: true
Lint/UnexpectedBlockArity: # new in 1.5
Enabled: true
Lint/UnmodifiedReduceAccumulator: # new in 1.1
Enabled: true
Lint/UselessAssignment:
Exclude:
- "test/stripe/generated_examples_test.rb"
Lint/UselessRescue: # new in 1.43
Enabled: true
Lint/UselessRuby2Keywords: # new in 1.23
Enabled: true
Metrics/CollectionLiteralLength: # new in 1.47
Enabled: true
Naming/BlockForwarding: # new in 1.24
Enabled: true
Security/CompoundHash: # new in 1.28
Enabled: true
Security/IoMethods: # new in 1.22
Enabled: true
Style/ArgumentsForwarding: # new in 1.1
Enabled: true
Style/ArrayIntersect: # new in 1.40
Enabled: true
Style/CollectionCompact: # new in 1.2
Enabled: true
Style/ComparableClamp: # new in 1.44
Enabled: true
Style/ConcatArrayLiterals: # new in 1.41
Enabled: true
Style/DataInheritance: # new in 1.49
Enabled: true
Style/DirEmpty: # new in 1.48
Enabled: true
Style/DocumentDynamicEvalDefinition: # new in 1.1
Enabled: true
Style/EmptyHeredoc: # new in 1.32
Enabled: true
Style/EndlessMethod: # new in 1.8
Enabled: true
Style/EnvHome: # new in 1.29
Enabled: true
Style/ExactRegexpMatch: # new in 1.51
Enabled: true
Style/FetchEnvVar: # new in 1.28
Enabled: true
Style/FileEmpty: # new in 1.48
Enabled: true
Style/FileRead: # new in 1.24
Enabled: true
Style/FileWrite: # new in 1.24
Enabled: true
Style/HashConversion: # new in 1.10
Enabled: true
Style/HashExcept: # new in 1.7
Enabled: true
Style/IfWithBooleanLiteralBranches: # new in 1.9
Enabled: true
Style/InPatternThen: # new in 1.16
Enabled: true
Style/MagicCommentFormat: # new in 1.35
Enabled: true
Style/MapCompactWithConditionalBlock: # new in 1.30
Enabled: true
Style/MapToHash: # new in 1.24
Enabled: true
Style/MapToSet: # new in 1.42
Enabled: true
Style/MinMaxComparison: # new in 1.42
Enabled: true
Style/MultilineInPatternThen: # new in 1.16
Enabled: true
Style/NegatedIfElseCondition: # new in 1.2
Enabled: true
Style/NestedFileDirname: # new in 1.26
Enabled: true
Style/NilLambda: # new in 1.3
Enabled: true
Style/NumberedParameters: # new in 1.22
Enabled: true
Style/NumberedParametersLimit: # new in 1.22
Enabled: true
Style/ObjectThen: # new in 1.28
Enabled: true
Style/OpenStructUse: # new in 1.23
Enabled: true
Style/OperatorMethodCall: # new in 1.37
Enabled: true
Style/QuotedSymbols: # new in 1.16
Enabled: true
Style/RedundantArgument: # new in 1.4
Enabled: true
Style/RedundantArrayConstructor: # new in 1.52
Enabled: true
Style/RedundantConstantBase: # new in 1.40
Enabled: true
Style/RedundantCurrentDirectoryInPath: # new in 1.53
Enabled: true
Style/RedundantDoubleSplatHashBraces: # new in 1.41
Enabled: true
Style/RedundantEach: # new in 1.38
Enabled: true
Style/RedundantFilterChain: # new in 1.52
Enabled: true
Style/RedundantHeredocDelimiterQuotes: # new in 1.45
Enabled: true
Style/RedundantInitialize: # new in 1.27
Enabled: true
Style/RedundantLineContinuation: # new in 1.49
Enabled: true
Style/RedundantRegexpArgument: # new in 1.53
Enabled: true
Style/RedundantRegexpConstructor: # new in 1.52
Enabled: true
Style/RedundantSelfAssignmentBranch: # new in 1.19
Enabled: true
Style/RedundantStringEscape: # new in 1.37
Enabled: true
Style/ReturnNilInPredicateMethodDefinition: # new in 1.53
Enabled: true
Style/SelectByRegexp: # new in 1.22
Enabled: true
Style/SingleLineDoEndBlock: # new in 1.57
Enabled: true
Style/StringChars: # new in 1.12
Enabled: true
Style/SwapValues: # new in 1.1
Enabled: true
Style/YAMLFileRead: # new in 1.53
Enabled: true
Gemspec/AddRuntimeDependency: # new in 1.65
Enabled: true
Lint/ArrayLiteralInRegexp: # new in 1.71
Enabled: true
Lint/ConstantReassignment: # new in 1.70
Enabled: true
Lint/CopDirectiveSyntax: # new in 1.72
Enabled: true
Lint/DuplicateSetElement: # new in 1.67
Enabled: true
Lint/HashNewWithKeywordArgumentsAsDefault: # new in 1.69
Enabled: true
Lint/ItWithoutArgumentsInBlock: # new in 1.59
Enabled: true
Lint/LiteralAssignmentInCondition: # new in 1.58
Enabled: true
Lint/NumericOperationWithConstantResult: # new in 1.69
Enabled: true
Lint/RedundantTypeConversion: # new in 1.72
Enabled: true
Lint/SharedMutableDefault: # new in 1.70
Enabled: true
Lint/SuppressedExceptionInNumberConversion: # new in 1.72
Enabled: true
Lint/UnescapedBracketInRegexp: # new in 1.68
Enabled: true
Lint/UselessConstantScoping: # new in 1.72
Enabled: true
Lint/UselessDefined: # new in 1.69
Enabled: true
Lint/UselessNumericOperation: # new in 1.66
Enabled: true
Style/AmbiguousEndlessMethodDefinition: # new in 1.68
Enabled: true
Style/BitwisePredicate: # new in 1.68
Enabled: true
Style/CombinableDefined: # new in 1.68
Enabled: true
Style/ComparableBetween: # new in 1.74
Enabled: true
Style/DigChain: # new in 1.69
Enabled: true
Style/FileNull: # new in 1.69
Enabled: true
Style/FileTouch: # new in 1.69
Enabled: true
Style/HashFetchChain: # new in 1.75
Enabled: true
Style/HashSlice: # new in 1.71
Enabled: true
Style/ItAssignment: # new in 1.70
Enabled: true
Style/ItBlockParameter: # new in 1.75
Enabled: true
Style/KeywordArgumentsMerging: # new in 1.68
Enabled: true
Style/MapIntoArray: # new in 1.63
Enabled: true
Style/RedundantFormat: # new in 1.72
Enabled: true
Style/RedundantInterpolationUnfreeze: # new in 1.66
Enabled: true
Style/SafeNavigationChainLength: # new in 1.68
Enabled: true
Style/SendWithLiteralMethodName: # new in 1.64
Enabled: true
Style/SuperArguments: # new in 1.64
Enabled: true
Style/SuperWithArgsParentheses: # new in 1.58
Enabled: true

View File

@ -1,87 +0,0 @@
# This configuration was generated by
# `rubocop --auto-gen-config`
# on 2023-11-28 01:02:03 UTC using RuboCop version 1.57.2.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
# versions of RuboCop, may require this file to be generated again.
# Offense count: 2
Lint/HashCompareByIdentity:
Exclude:
- 'lib/stripe/api_requestor.rb'
# Offense count: 26
# Configuration parameters: AllowedMethods, AllowedPatterns, CountRepeatedAttributes.
Metrics/AbcSize:
Max: 50
# Offense count: 9
# Configuration parameters: CountComments, CountAsOne.
Metrics/ClassLength:
Max: 592
# Offense count: 12
# Configuration parameters: AllowedMethods, AllowedPatterns.
Metrics/CyclomaticComplexity:
Max: 12
# Offense count: 9
# Configuration parameters: CountKeywordArgs, MaxOptionalParameters.
Metrics/ParameterLists:
Max: 7
# Offense count: 8
# Configuration parameters: AllowedMethods, AllowedPatterns.
Metrics/PerceivedComplexity:
Max: 12
# Offense count: 1
# This cop supports unsafe autocorrection (--autocorrect-all).
# Configuration parameters: MinBranchesCount.
Style/CaseLikeIf:
Exclude:
- 'lib/stripe/stripe_configuration.rb'
# Offense count: 1
# This cop supports unsafe autocorrection (--autocorrect-all).
Style/CombinableLoops:
Exclude:
- 'lib/stripe/api_requestor.rb'
# Offense count: 39
# Configuration parameters: AllowedConstants.
Style/Documentation:
Enabled: false
# Offense count: 1
# This cop supports unsafe autocorrection (--autocorrect-all).
# Configuration parameters: AllowSplatArgument.
Style/HashConversion:
Exclude:
- 'lib/stripe/api_requestor.rb'
# Offense count: 3
# This cop supports unsafe autocorrection (--autocorrect-all).
# Configuration parameters: ConvertCodeThatCanStartToReturnNil, AllowedMethods, MaxChainLength.
# AllowedMethods: present?, blank?, presence, try, try!
Style/SafeNavigation:
Exclude:
- 'lib/stripe/instrumentation.rb'
- 'lib/stripe/stripe_response.rb'
# Offense count: 15
# This cop supports unsafe autocorrection (--autocorrect-all).
# Configuration parameters: Mode.
Style/StringConcatenation:
Exclude:
- 'lib/stripe.rb'
- 'lib/stripe/connection_manager.rb'
- 'lib/stripe/multipart_encoder.rb'
- 'lib/stripe/oauth.rb'
- 'lib/stripe/resources/bank_account.rb'
- 'lib/stripe/resources/source.rb'
- 'lib/stripe/api_requestor.rb'
- 'test/stripe/api_resource_test.rb'
- 'test/stripe/stripe_client_test.rb'
- 'test/stripe/webhook_test.rb'

15
.travis.yml Normal file
View File

@ -0,0 +1,15 @@
language: ruby
rvm:
- 1.8.7
- 1.9.2
- 1.9.3
- 2.0.0
- 2.1
gemfile:
- gemfiles/default-with-activesupport.gemfile
- gemfiles/json.gemfile
- gemfiles/yajl.gemfile
sudo: false

View File

@ -1,9 +0,0 @@
{
"recommendations": [
"EditorConfig.editorconfig", // default
"castwide.solargraph", // intellisense
"sorbet.sorbet-vscode-extension", // typechecking, where applicable
"LoranKloeze.ruby-rubocop-revived", // linting
"SarahRidge.vscode-ruby-syntax" // Semantic syntax highlighting
]
}

11
.vscode/settings.json vendored
View File

@ -1,11 +0,0 @@
{
// Show the repo name in the top window bar.
"window.title": "${rootName}${separator}${activeEditorMedium}",
"editor.formatOnSave": true,
"files.trimTrailingWhitespace": true,
// Rubocop settings
"ruby.rubocop.configFilePath": ".rubocop.yml",
"ruby.rubocop.onSave": true
}

File diff suppressed because it is too large Load Diff

View File

@ -1,77 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to make participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies within all project spaces, and it also applies when
an individual is representing the project or its community in public spaces.
Examples of representing a project or community include using an official
project e-mail address, posting via an official social media account, or acting
as an appointed representative at an online or offline event. Representation of
a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at conduct@stripe.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq

View File

@ -1,25 +0,0 @@
# Contributing
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.

41
Gemfile
View File

@ -1,41 +1,8 @@
# frozen_string_literal: true
source "https://rubygems.org" source "https://rubygems.org"
gemspec gemspec
group :development do if Gem::Version.new(RUBY_VERSION.dup) < Gem::Version.new('1.9.3')
gem "mocha", "~> 1.16.0" gem 'i18n', '< 0.7'
gem "rack", ">= 2.0.6" gem 'rest-client', '~> 1.6.8'
gem "rake" gem 'activesupport', '~> 3.2'
gem "shoulda-context", "2.0.0"
gem "test-unit"
# Version doesn't matter that much, but this one contains some fixes for Ruby
# 2.7 warnings that add noise to the test suite.
gem "webmock", ">= 3.8.0"
# Rubocop changes pretty quickly: new cops get added and old cops change
# names or go into new namespaces. This is a library and we don't have
# `Gemfile.lock` checked in, so to prevent good builds from suddenly going
# bad, pin to a specific version number here. Try to keep this relatively
# up-to-date, but it's not the end of the world if it's not.
#
# The latest version of rubocop is only compatible with Ruby 2.7+
gem "rubocop", "1.75.2" if RUBY_VERSION >= "2.7"
gem "sorbet"
gem "tapioca"
platforms :mri do
gem "byebug"
gem "pry"
gem "pry-byebug"
end
platforms :jruby do
gem "rbi", "0.2.4" # jruby does not support rbs, a new dependency in 0.3.0
end
end end

View File

@ -1 +1,275 @@
History.txt has been converted to a formal changelog. Please see CHANGELOG.md. === 1.17.1 2015-01-07
* 2 minor enhacements:
* Fixed dependencies for Ruby versions less than 1.9.3
* Added deauthorize method to Account object
=== 1.17.0 2014-12-15
* 1 major enhacement:
* File uploads resource was added (for uploading pdf or image documents for
disputes)
=== 1.16.1 2014-12-19
* 2 minor enhancements:
* Ability to send idempotent requests
* Ability to specify stripe account as a header.
=== 1.16.0 2014-10-08
* 1 minor enhacement:
* Coupons now support update operations - useful for manipulating metadata.
=== 1.15.0 2014-07-26
* 1 major enhacement:
* Application Fee refunds now a list instead of array
=== 1.14.0 2014-06-17
* 1 major enhancement:
* Add metadata for refunds and disputes
=== 1.13.0 2014-05-28
* 1 major enhancement:
* Support for canceling transfers
=== 1.12.0 2014-05-21
* 1 major enhancement:
* Support for cards for recipients.
=== 1.11.0 2014-04-09
* 2 minor enhancements:
* Update included ca bundles
* Implement certificate blacklisting
=== 1.10.2 2014-02-18
* 1 minor enhancement:
* Add create_subscription on Customer resources, so you can create
subscriptions without needing to retrieve the customer first (github
issue #120)
=== 1.10.1 2014-02-03
* 1 bugfix:
* Fix marshaling of StripeObjects
=== 1.10.0 2014-01-29
* 2 major enhancements
* Support for multiple subscriptions per customer
* Testing ruby 2.1.0
* 2 minor enhancements
* Replace multi_json with json
* Allow #save to take opts (for :expand)
* 1 bugfix
* Fix #try and #respond_to? on StripeObjects
=== 1.9.9 2013-12-02
* 1 major enhancement
* Add ApplicationFee resource
=== 1.8.9 2013-11-14
* 2 bugfixes:
* Fix gemspec dependencies so the gem doesn't break for Ruby 1.8 users
* Fix api_resource_test to not use returns as a way of testing rescue behavior
=== 1.8.8 2013-10-3
* 1 major enhancement
* Add support for metadata on resources
=== 1.8.7 2013-08-18
* 1 minor enhancement
* Add support for closing disputes.
=== 1.8.6 2013-08-13
* 1 major enhancement
* Add Balance and BalanceTransaction resources
=== 1.8.5 2013-08-12
* 1 major enhancement
* Add support for unsetting attributes by setting to nil. This permits
unsetting email and description on customers and description on charges.
Setting properties to a blank string is now an error.
* Attempting to set an object's id is now an error.
=== 1.8.4 2013-07-11
* 1 major enhancement
* Add support for new cards API (Stripe API version 2013-07-05)
=== 1.8.3 2013-05-06
* 1 bugfix:
* Fix handling of per-call API keys (github issue #67)
=== 1.8.2 2013-05-01
* 3 minor enhancements:
* Use to_sym instead of type checking for minor performance
improvement (github issue #59)
* Handle low-memory situations without throwing an exception (github
issue #61)
* Add an Customer#upcoming_invoice convenience method (github issue
#65)
* 1 bugfix:
* Allow updating resources without first retrieving them (github
issue #60)
=== 1.8.1 2013-04-19
* 1 minor enhancement:
* Add support for specifying an API key when retrieving an upcoming invoice
=== 1.8.0 2013-04-11
* 1 major enhancement:
* Add new Recipient resource
* Allow Transfers to be createable
=== 1.7.11 2013-02-21
* 1 minor enhancement
* Add 'id' to the list of permanent attributes
=== 1.7.10 2013-02-01
* 1 major enhancement
* Add support for passing options when retrieving Stripe objects
e.g., Stripe::Charge.retrieve({id:"foo", expand:["customer"]})
Stripe::Charge("foo") is still supported as well
=== 1.7.9 2013-01-15
* 1 major enhancement
* Add support for setting a Stripe API version override.
=== 1.7.8 2012-11-21
* 1 bugfix
* Relax the version constraint on multi_json (github issue #44)
=== 1.7.7 2012-11-07
* 1 minor enhancement:
* Add support for updating charge disputes
* 1 bugfix
* Fix Account API resource bug
=== 1.7.6 2012-10-30
* 1 major enhancement
* Add support for creating invoices
=== 1.7.5 2012-10-25
* 1 major enhancement
* Add support for new API lists
=== 1.7.4 2012-10-08
* 1 bugfix
* Fix bug introduced in 1.7.3 calling API methods that take no
arguments, like Stripe::Invoice#pay (github issue #42)
=== 1.7.3 2012-09-14
* 2 bugfixes
* Make sure that both keys and values of GET params are
URL-encoded. NOTE: If you were previously URL-encoding values
yourself, you may need to adjust your code.
* URL-encode POST params directly, instead of allowing rest-client to
do it to work around an unfortunate interaction with the hashery gem
(github issue #38)
=== 1.7.2 2012-08-31
* 1 major enhancement
* Add support for new pay and update methods for Invoice objects
=== 1.7.1 2012-08-15
* 1 major enhancement
* Add new Account API resource
=== 1.7.0 2012-05-17
* 3 major enhancements:
* Switch from vendored stripe-json to multi_json for all JSON
parsing and rendering. This should not impact programmatic usage
of the library, but may cause small rendering differences from,
e.g., StripeObject#inspect (github issue #22)
* Add new delete_discount method to Customer objects
* Add new Transfer API resource
* 2 minor enhancements:
* Switch from HTTP Basic auth to Bearer auth (Note: Stripe will
support Basic auth for the indefinite future, but recommends
Bearer auth when possible going forward)
* Numerous test suite improvements
=== 1.6.3 2012-03-22
* 1 bugfix:
* Encode GET query strings ourselves instead of using rest-client to
work around a bug
=== 1.6.2 2012-02-24
* 1 bugfix:
* Correct argument handling in StripeObject#as_json
=== 1.6.1 2012-02-22
* 1 bugfix:
* Fix StripeObject#inspect when ActiveSupport 3.0 is loaded
=== 1.6.0 2012-02-01
* A whole bunch of releases between 1.5.0 and 1.6.0, but few changes, mainly
the addition of:
- plans
- coupons
- events
- tokens
* 1.6.0 also contains a new inspect/to_string implementation
=== 1.5.0 2011-05-09
* 1 major enhancement:
* Update for new RESTful API
=== 1.3.4 2011-01-07
* 1 major enhancement:
* Rename to Stripe
=== 1.2 2010-06-06
* 1 major enhancement:
* Support for the set_customer_subscription and delete_customer API methods
=== 1.1 2010-03-14
* 1 major enhancement:
* Support for recurring billing
=== 1.0 2010-01-05
* 1 major enhancement:
* Initial release

View File

@ -1,22 +0,0 @@
# NOTE: this file is deprecated and slated for deletion; prefer using the equivalent `just` commands.
.PHONY: update-version codegen-format test ci-test
update-version:
@echo "$(VERSION)" > VERSION
@perl -pi -e 's|VERSION = "[.\-\w\d]+"|VERSION = "$(VERSION)"|' lib/stripe/version.rb
codegen-format:
bundle install --quiet
bundle exec rubocop -o /dev/null --autocorrect
ci-test:
bundle install && bundle exec rake test
@version=$$(ruby -e "puts RUBY_VERSION.split('.')[0..1].join.to_i"); \
if [ $$version -ge 27 ]; then \
echo "Ruby version >= 2.7, continue with srb tc"; \
bundle exec srb tc; \
else \
echo "Ruby version < 2.7, skipping srb tc"; \
fi
test: ci-test

View File

@ -1 +0,0 @@
v1773

460
README.md
View File

@ -1,460 +0,0 @@
# Stripe Ruby Library
[![Gem Version](https://badge.fury.io/rb/stripe.svg)](https://badge.fury.io/rb/stripe)
[![Build Status](https://github.com/stripe/stripe-ruby/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/stripe/stripe-ruby/actions?query=branch%3Amaster)
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.
```ruby
customer = Stripe::Customer.retrieve('cus_123456789')
puts customer['id']
puts customer.id
```
NOTE: If the resource property is not defined, the accessors will raise an exception, while the indexer will return `nil`.
```ruby
customer = Stripe::Customer.retrieve('cus_123456789')
puts customer['unknown'] # nil
puts customer.unknown # raises NoMethodError
```
### Accessing a response object
Get access to response objects by using the `last_response` property of the returned resource:
```ruby
customer = Stripe::Customer.retrieve('cus_123456789')
print(customer.last_response.http_status) # to retrieve status code
print(customer.last_response.http_headers) # to retrieve headers
```
If you are accessing a response field with custom hashes provided by you, such as `Customer.metadata`,
please access your fields with the `[]` accessor.
### Configuring a proxy
A proxy can be configured with `Stripe.proxy`:
```ruby
Stripe.proxy = 'https://user:pass@example.com:1234'
```
### Configuring an API Version
By default, the library will use the API version pinned to the account making
a request. This can be overridden with this global option:
```ruby
Stripe.api_version = '2018-02-28'
```
See [versioning in the API reference][versioning] for more information.
### Configuring CA Bundles
By default, the library will use its own internal bundle of known CA
certificates, but it's possible to configure your own:
```ruby
Stripe.ca_bundle_path = 'path/to/ca/bundle'
```
### Configuring Automatic Retries
You can enable automatic retries on requests that fail due to a transient
problem by configuring the maximum number of retries:
```ruby
Stripe.max_network_retries = 2
```
Various errors can trigger a retry, like a connection error or a timeout, and
also certain API responses like HTTP status `409 Conflict`.
[Idempotency keys][idempotency-keys] are added to requests to guarantee that
retries are safe.
### Configuring Timeouts
Open, read and write timeouts are configurable:
```ruby
Stripe.open_timeout = 30 # in seconds
Stripe.read_timeout = 80
Stripe.write_timeout = 30 # only supported on Ruby 2.6+
```
Please take care to set conservative read timeouts. Some API requests can take
some time, and a short timeout increases the likelihood of a problem within our
servers.
### Logging
The library can be configured to emit logging that will give you better insight
into what it's doing. The `info` logging level is usually most appropriate for
production use, but `debug` is also available for more verbosity.
There are a few options for enabling it:
1. Set the environment variable `STRIPE_LOG` to the value `debug` or `info`:
```sh
$ export STRIPE_LOG=info
```
2. Set `Stripe.log_level`:
```ruby
Stripe.log_level = Stripe::LEVEL_INFO
```
### Instrumentation
The library has various hooks that user code can tie into by passing a block to
`Stripe::Instrumentation.subscribe` to be notified about specific events.
#### `request_begin`
Invoked when an HTTP request starts. Receives `RequestBeginEvent` with the
following properties:
- `method`: HTTP method. (`Symbol`)
- `path`: Request path. (`String`)
- `user_data`: A hash on which users can set arbitrary data, and which will be
passed through to `request_end` invocations. This could be used, for example,
to assign unique IDs to each request, and it'd work even if many requests are
running in parallel. All subscribers share the same object for any particular
request, so they must be careful to use unique keys that will not conflict
with other subscribers. (`Hash`)
#### `request_end`
Invoked when an HTTP request finishes, regardless of whether it terminated with
a success or error. Receives `RequestEndEvent` with the following properties:
- `duration`: Request duration in seconds. (`Float`)
- `http_status`: HTTP response code (`Integer`) if available, or `nil` in case
of a lower level network error.
- `method`: HTTP method. (`Symbol`)
- `num_retries`: The number of retries. (`Integer`)
- `path`: Request path. (`String`)
- `user_data`: A hash on which users may have set arbitrary data in
`request_begin`. See above for more information. (`Hash`)
- `request_id`: HTTP request identifier. (`String`)
- `response_header`: The response headers. (`Hash`)
- `response_body` = The response body. (`String`)
- `request_header` = The request headers. (`Hash`)
- `request_body` = The request body. (`String`)
#### Example
For example:
```ruby
Stripe::Instrumentation.subscribe(:request_end) do |request_event|
# Filter out high-cardinality ids from `path`
path_parts = request_event.path.split("/").drop(2)
resource = path_parts.map { |part| part.match?(/\A[a-z_]+\z/) ? part : ":id" }.join("/")
tags = {
method: request_event.method,
resource: resource,
code: request_event.http_status,
retries: request_event.num_retries
}
StatsD.distribution('stripe_request', request_event.duration, tags: tags)
end
```
### Writing a Plugin
If you're writing a plugin that uses the library, we'd appreciate it if you
identified using `#set_app_info`:
```ruby
Stripe.set_app_info('MyAwesomePlugin', version: '1.2.34', url: 'https://myawesomeplugin.info')
```
This information is passed along when the library makes calls to the Stripe
API.
### Telemetry
By default, the library sends telemetry to Stripe regarding request latency and feature usage. These
numbers help Stripe improve the overall latency of its API for all users, and
improve popular features.
You can disable this behavior if you prefer:
```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:
```sh
gem install stripe -v <replace-with-the-version-of-your-choice>
```
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`.
```ruby
client = Stripe::StripeClient.new(...)
resp = client.raw_request(:post, "/v1/beta_endpoint", params: {param: 123}, opts: {stripe_version: "2022-11-15; feature_beta=v3"})
# (Optional) resp is a StripeResponse. You can use `Stripe.deserialize` to get a StripeObject.
deserialized_resp = client.deserialize(resp.http_body)
```
## Support
New features and bug fixes are released on the latest major version of the Stripe Ruby library. If you are on an older major version, we recommend that you upgrade to the latest in order to use the new features and bug fixes including those for security vulnerabilities. Older major versions of the package will continue to be available for use, but will not be receiving any updates.
## Development
[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:
Run all tests:
```sh
just test
# or: bundle exec rake test
```
Run a single test suite:
```sh
bundle exec ruby -Ilib/ test/stripe/util_test.rb
```
Run a single test:
```sh
bundle exec ruby -Ilib/ test/stripe/util_test.rb -n /should.convert.names.to.symbols/
```
Run the linter:
```sh
just lint
# or: bundle exec rubocop
```
Update bundled CA certificates from the [Mozilla cURL release][curl]:
```sh
just update-certs
# or: bundle exec rake update_certs
```
Update the bundled [stripe-mock] by editing the version number found in
`.travis.yml`.
[api-keys]: https://dashboard.stripe.com/account/apikeys
[connect]: https://stripe.com/connect
[curl]: http://curl.haxx.se/docs/caextract.html
[idempotency-keys]: https://stripe.com/docs/api/idempotent_requests?lang=ruby
[stripe-mock]: https://github.com/stripe/stripe-mock
[versioning]: https://stripe.com/docs/api/versioning?lang=ruby
<!--
# vim: set tw=79:
-->

44
README.rdoc Normal file
View File

@ -0,0 +1,44 @@
= Stripe Ruby bindings {<img src="https://travis-ci.org/stripe/stripe-ruby.svg?branch=master" alt="Build Status" />}[https://travis-ci.org/stripe/stripe-ruby] {<img src="https://gemnasium.com/stripe/stripe-ruby.png" alt="Dependency Status" />}[https://gemnasium.com/stripe/stripe-ruby]
== Installation
You don't need this source code unless you want to modify the gem. If
you just want to use the Stripe Ruby bindings, you should run:
gem install --source https://code.stripe.com stripe
If you want to build the gem from source:
gem build stripe.gemspec
== Requirements
* Ruby 1.8.7 or above. (Ruby 1.8.6 may work if you load
ActiveSupport.) For Ruby versions before 1.9.2, you'll need to add this to your Gemfile:
if Gem::Version.new(RUBY_VERSION) < Gem::Version.new('1.9.2')
gem 'rest-client', '~> 1.6.8'
end
* rest-client, json
== Mirrors
The stripe gem is mirrored on Rubygems, so you should be able to
install it via <tt>gem install stripe</tt> if desired. We recommend using
the https://code.stripe.com mirror so all code is fetched over SSL.
Note that if you are installing via bundler, you should be sure to use the https
rubygems source in your Gemfile, as any gems fetched over http could potentially be
compromised in transit and alter the code of gems fetched securely over https:
source 'https://code.stripe.com'
source 'https://rubygems.org'
gem 'rails'
gem 'stripe'
== Development
Test cases can be run with: `bundle exec rake test`

View File

@ -1,34 +1,7 @@
# frozen_string_literal: true require 'rake/testtask'
require "rake/testtask" task :default => [:test]
task default: %i[test rubocop]
Rake::TestTask.new do |t| Rake::TestTask.new do |t|
t.pattern = "./test/**/*_test.rb" t.pattern = './test/**/*_test.rb'
end
desc "Update bundled certs"
task :update_certs do
require "net/http"
require "uri"
fetch_file "https://curl.haxx.se/ca/cacert.pem",
File.expand_path("lib/data/ca-certificates.crt", __dir__)
end
#
# helpers
#
def fetch_file(uri, dest)
File.open(dest, "w") do |file|
resp = Net::HTTP.get_response(URI.parse(uri))
unless resp.code.to_i == 200
abort("bad response when fetching: #{uri}\n" \
"Status #{resp.code}: #{resp.body}")
end
file.write(resp.body)
puts "Successfully fetched: #{uri}"
end
end end

View File

@ -1 +1 @@
15.2.1 1.17.1

7
bin/stripe-console Executable file
View File

@ -0,0 +1,7 @@
#!/usr/bin/env ruby
irb = RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? 'irb.bat' : 'irb'
libs = " -r irb/completion"
libs << " -r #{File.dirname(__FILE__) + '/../lib/stripe'}"
puts "Loading stripe gem"
exec "#{irb} #{libs} --simple-prompt"

View File

@ -1,27 +0,0 @@
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# This file was generated by Bundler.
#
# The application 'tapioca' is installed as part of a gem, and
# this file is here to facilitate running it.
#
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__)
bundle_binstub = File.expand_path("bundle", __dir__)
if File.file?(bundle_binstub)
if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
load(bundle_binstub)
else
abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
end
end
require "rubygems"
require "bundler/setup"
load Gem.bin_path("tapioca", "tapioca")

View File

@ -1,16 +0,0 @@
## Running an example
From the examples folder, run:
`RUBYLIB=../lib ruby your_example.rb`
e.g.
`RUBYLIB=../lib ruby thinevent_webhook_handler.rb`
## Adding a new example
1. Clone new_example.rb
2. Implement your example
3. Fill out the file comment. Include a description and key steps that are being demonstrated.
4. Run it (as per above)
5. 👍

View File

@ -1,36 +0,0 @@
# frozen_string_literal: true
# example_template.py - This is a template for defining new examples. It is not intended to be used directly.
#
# <describe what this example does>
#
# In this example, we:
# - <key step 1>
# - <key step 2
# - ...
#
# <describe assumptions about the user's stripe account, environment, or configuration;
# or things to watch out for when running>
require "stripe"
require "date"
class ExampleTemplate
attr_accessor :api_key
def initialize(api_key)
@api_key = api_key
end
def do_something_great
puts "Hello World"
# client = Stripe::StripeClient.new(api_key)
# client.v1
end
end
# Send meter events
api_key = "{{API_KEY}}"
example = ExampleTemplate.new(api_key)
example.do_something_great

View File

@ -1,57 +0,0 @@
# frozen_string_literal: true
# meter_event_stream.py - use the high-throughput meter event stream to report create billing meter events.
#
# In this example, we:
# - create a meter event session and store the session's authentication token
# - define an event with a payload
# - use the meter_event_stream service accessor in StripeClient to create an event stream that reports this event
#
# This example expects a billing meter with an event_name of 'alpaca_ai_tokens'. If you have
# a different meter event name, you can change it before running this example.
require "stripe"
require "date"
class MeterEventManager
attr_accessor :api_key, :meter_event_session
def initialize(api_key)
@api_key = api_key
@meter_event_session = nil
end
def refresh_meter_event_session
return unless @meter_event_session.nil? || DateTime.parse(@meter_event_session.expires_at) <= DateTime.now
# Create a new meter event session in case the existing session expired
client = Stripe::StripeClient.new(api_key)
@meter_event_session = client.v2.billing.meter_event_session.create
end
def send_meter_event(meter_event)
# Refresh the meter event session if necessary
refresh_meter_event_session
# Create a meter event with the current session's authentication token
client = Stripe::StripeClient.new(meter_event_session.authentication_token)
client.v2.billing.meter_event_stream.create(
events: [meter_event]
)
end
end
# Send meter events
api_key = "{{API_KEY}}"
customer_id = "{{CUSTOMER_ID}}"
manager = MeterEventManager.new(api_key)
manager.send_meter_event(
{
event_name: "alpaca_ai_tokens",
payload: {
"stripe_customer_id" => customer_id,
"value" => "25",
},
}
)

View File

@ -1,39 +0,0 @@
# frozen_string_literal: true
# typed: false
# thinevent_webhook_handler.rb - receive and process thin events like the
# v1.billing.meter.error_report_triggered event.
#
# In this example, we:
# - create a StripeClient called client
# - use client.parse_thin_event to parse the received thin event webhook body
# - call client.v2.core.events.retrieve to retrieve the full event object
# - if it is a V1BillingMeterErrorReportTriggeredEvent event type, call
# event.fetchRelatedObject to retrieve the Billing Meter object associated
# with the event.
require "stripe"
require "sinatra"
api_key = ENV.fetch("STRIPE_API_KEY", nil)
# Retrieve the webhook secret from the environment variable
webhook_secret = ENV.fetch("WEBHOOK_SECRET", nil)
client = Stripe::StripeClient.new(api_key)
post "/webhook" do
webhook_body = request.body.read
sig_header = request.env["HTTP_STRIPE_SIGNATURE"]
thin_event = client.parse_thin_event(webhook_body, sig_header, webhook_secret)
# Fetch the event data to understand the failure
event = client.v2.core.events.retrieve(thin_event.id)
if event.instance_of? Stripe::V1BillingMeterErrorReportTriggeredEvent
meter = event.fetch_related_object
meter_id = meter.id
puts "Success!", meter_id
end
# Record the failures and alert your team
status 200
end

View File

@ -1,16 +0,0 @@
#!/usr/bin/env ruby
# frozen_string_literal: true
require "irb"
require "irb/completion"
require "#{File.dirname(__FILE__)}/../lib/stripe"
# Config IRB to enable --simple-prompt and auto indent
IRB.conf[:PROMPT_MODE] = :SIMPLE
IRB.conf[:AUTO_INDENT] = true
puts "Loaded gem 'stripe'"
IRB.start

View File

@ -0,0 +1,10 @@
source "https://rubygems.org"
gemspec :path => File.join(File.dirname(__FILE__), "..")
if Gem::Version.new(RUBY_VERSION) < Gem::Version.new('1.9.3')
gem 'i18n', '< 0.7'
gem 'rest-client', '~> 1.6.8'
gem 'activesupport', '~> 3.2'
else
gem 'activesupport'
end

12
gemfiles/json.gemfile Normal file
View File

@ -0,0 +1,12 @@
source "https://rubygems.org"
gemspec :path => File.join(File.dirname(__FILE__), "..")
if Gem::Version.new(RUBY_VERSION) < Gem::Version.new('1.9.3')
gem 'i18n', '< 0.7'
gem 'rest-client', '~> 1.6.8'
gem 'activesupport', '~> 3.2'
else
gem 'activesupport'
end
gem 'json'

12
gemfiles/yajl.gemfile Normal file
View File

@ -0,0 +1,12 @@
source "https://rubygems.org"
gemspec :path => File.join(File.dirname(__FILE__), "..")
if Gem::Version.new(RUBY_VERSION) < Gem::Version.new('1.9.3')
gem 'i18n', '< 0.7'
gem 'rest-client', '~> 1.6.8'
gem 'activesupport', '~> 3.2'
else
gem 'activesupport'
end
gem 'yajl-ruby'

View File

@ -1,43 +0,0 @@
set quiet
import? '../sdk-codegen/utils.just'
_default:
just --list --unsorted
install *args:
bundle install {{ if is_dependency() == "true" {"--quiet"} else {""} }} {{ args }}
# ⭐ run all unit tests
test: install
bundle exec rake test
# check linting / formatting status of files
format-check *args: install
bundle exec rubocop {{ args }}
alias lint-check := format-check
# ⭐ check style & formatting for all files, fixing what we can
lint: (format-check "--autocorrect")
# NOTE: "-o /dev/null" is vital - rubocop has super noisy output and codegen will crash when formatting ruby if everything gets printed
# so, we send all its output to the void
# copy of `lint` with less output
format: (format-check "-o /dev/null --autocorrect")
update-certs: install
bundle exec rake update_certs
# run sorbet to check type definitions
typecheck: install
{{ if semver_matches(`ruby -e "puts RUBY_VERSION"`, ">=2.7") == "true" { \
"bundle exec srb tc" \
} else { \
"echo \"Ruby version < 2.7, skipping srb tc\"" \
} }}
# called by tooling
[private]
update-version version:
echo "{{ version }}" > VERSION
perl -pi -e 's|VERSION = "[.\-\w\d]+"|VERSION = "{{ version }}"|' lib/stripe/version.rb

File diff suppressed because it is too large Load Diff

View File

@ -1,160 +1,302 @@
# frozen_string_literal: true
# Stripe Ruby bindings # Stripe Ruby bindings
# API spec at https://stripe.com/docs/api # API spec at https://stripe.com/docs/api
require "cgi" require 'cgi'
require "json" require 'set'
require "logger" require 'openssl'
require "net/http" require 'rest_client'
require "openssl" require 'json'
require "rbconfig"
require "securerandom"
require "set"
require "socket"
require "uri"
require "forwardable"
# Version # Version
require "stripe/api_version" require 'stripe/version'
require "stripe/version"
# API operations # API operations
require "stripe/api_operations/create" require 'stripe/api_operations/create'
require "stripe/api_operations/delete" require 'stripe/api_operations/update'
require "stripe/api_operations/list" require 'stripe/api_operations/delete'
require "stripe/api_operations/nested_resource" require 'stripe/api_operations/list'
require "stripe/api_operations/request"
require "stripe/api_operations/save"
require "stripe/api_operations/singleton_save"
require "stripe/api_operations/search"
# API resource support classes # Resources
require "stripe/errors" require 'stripe/util'
require "stripe/object_types" require 'stripe/stripe_object'
require "stripe/event_types" require 'stripe/api_resource'
require "stripe/request_options" require 'stripe/singleton_api_resource'
require "stripe/request_params" require 'stripe/list_object'
require "stripe/util" require 'stripe/account'
require "stripe/connection_manager" require 'stripe/balance'
require "stripe/multipart_encoder" require 'stripe/balance_transaction'
require "stripe/api_requestor" require 'stripe/customer'
require "stripe/stripe_service" require 'stripe/certificate_blacklist'
require "stripe/stripe_client" require 'stripe/invoice'
require "stripe/stripe_object" require 'stripe/invoice_item'
require "stripe/stripe_response" require 'stripe/charge'
require "stripe/list_object" require 'stripe/plan'
require "stripe/v2_list_object" require 'stripe/file_upload'
require "stripe/search_result_object" require 'stripe/coupon'
require "stripe/error_object" require 'stripe/token'
require "stripe/api_resource" require 'stripe/event'
require "stripe/api_resource_test_helpers" require 'stripe/transfer'
require "stripe/singleton_api_resource" require 'stripe/recipient'
require "stripe/webhook" require 'stripe/card'
require "stripe/stripe_configuration" require 'stripe/subscription'
require "stripe/thin_event" require 'stripe/application_fee'
require 'stripe/refund'
require 'stripe/application_fee_refund'
# Named API resources # Errors
require "stripe/resources" require 'stripe/errors/stripe_error'
require "stripe/services" require 'stripe/errors/api_error'
require 'stripe/errors/api_connection_error'
# OAuth require 'stripe/errors/card_error'
require "stripe/oauth" require 'stripe/errors/invalid_request_error'
require "stripe/services/oauth_service" require 'stripe/errors/authentication_error'
module Stripe module Stripe
DEFAULT_CA_BUNDLE_PATH = __dir__ + "/data/ca-certificates.crt" DEFAULT_CA_BUNDLE_PATH = File.dirname(__FILE__) + '/data/ca-certificates.crt'
@api_base = 'https://api.stripe.com'
@connect_base = 'https://connect.stripe.com'
# map to the same values as the standard library's logger @ssl_bundle_path = DEFAULT_CA_BUNDLE_PATH
LEVEL_DEBUG = Logger::DEBUG @verify_ssl_certs = true
LEVEL_ERROR = Logger::ERROR @CERTIFICATE_VERIFIED = false
LEVEL_INFO = Logger::INFO
# API base constants
DEFAULT_API_BASE = "https://api.stripe.com"
DEFAULT_CONNECT_BASE = "https://connect.stripe.com"
DEFAULT_UPLOAD_BASE = "https://files.stripe.com"
DEFAULT_METER_EVENTS_BASE = "https://meter-events.stripe.com"
# Options that can be configured globally by users
USER_CONFIGURABLE_GLOBAL_OPTIONS = Set.new(%i[
api_key
api_version
stripe_account
api_base
uploads_base
connect_base
meter_events_base
open_timeout
read_timeout
write_timeout
proxy
verify_ssl_certs
ca_bundle_path
log_level
logger
max_network_retries
enable_telemetry
client_id
])
@app_info = nil
@config = Stripe::StripeConfiguration.setup
class << self class << self
extend Forwardable attr_accessor :api_key, :api_base, :verify_ssl_certs, :api_version, :connect_base
attr_reader :config
# User configurable options
def_delegators :@config, :api_key, :api_key=
def_delegators :@config, :api_version, :api_version=
def_delegators :@config, :stripe_account, :stripe_account=
def_delegators :@config, :api_base, :api_base=
def_delegators :@config, :uploads_base, :uploads_base=
def_delegators :@config, :connect_base, :connect_base=
def_delegators :@config, :meter_events_base, :meter_events_base=
def_delegators :@config, :open_timeout, :open_timeout=
def_delegators :@config, :read_timeout, :read_timeout=
def_delegators :@config, :write_timeout, :write_timeout=
def_delegators :@config, :proxy, :proxy=
def_delegators :@config, :verify_ssl_certs, :verify_ssl_certs=
def_delegators :@config, :ca_bundle_path, :ca_bundle_path=
def_delegators :@config, :log_level, :log_level=
def_delegators :@config, :logger, :logger=
def_delegators :@config, :max_network_retries, :max_network_retries=
def_delegators :@config, :enable_telemetry=, :enable_telemetry?
def_delegators :@config, :client_id=, :client_id
# Internal configurations
def_delegators :@config, :max_network_retry_delay
def_delegators :@config, :initial_network_retry_delay
def_delegators :@config, :ca_store
end end
# Gets the application for a plugin that's identified some. See def self.api_url(url='', api_base_url=nil)
# #set_app_info. (api_base_url || @api_base) + url
def self.app_info
@app_info
end end
def self.app_info=(info) def self.request(method, url, api_key, params={}, headers={}, api_base_url=nil)
@app_info = info api_base_url = api_base_url || @api_base
unless api_key ||= @api_key
raise AuthenticationError.new('No API key provided. ' +
'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.')
end end
# Sets some basic information about the running application that's sent along if api_key =~ /\s/
# with API requests. Useful for plugin authors to identify their plugin when raise AuthenticationError.new('Your API key is invalid, as it contains ' +
# communicating with Stripe. 'whitespace. (HINT: You can double-check your API key from the ' +
# 'Stripe web interface. See https://stripe.com/api for details, or ' +
# Takes a name and optional partner program ID, plugin URL, and version. 'email support@stripe.com if you have any questions.)')
def self.set_app_info(name, partner_id: nil, url: nil, version: nil) end
@app_info = {
name: name, request_opts = { :verify_ssl => false }
partner_id: partner_id,
url: url, if ssl_preflight_passed?
version: version, request_opts.update(:verify_ssl => OpenSSL::SSL::VERIFY_PEER,
:ssl_ca_file => @ssl_bundle_path)
end
if @verify_ssl_certs and !@CERTIFICATE_VERIFIED
@CERTIFICATE_VERIFIED = CertificateBlacklist.check_ssl_cert(api_base_url, @ssl_bundle_path)
end
params = Util.objects_to_ids(params)
url = api_url(url, api_base_url)
case method.to_s.downcase.to_sym
when :get, :head, :delete
# Make params into GET parameters
url += "#{URI.parse(url).query ? '&' : '?'}#{uri_encode(params)}" if params && params.any?
payload = nil
else
if headers[:content_type] && headers[:content_type] == "multipart/form-data"
payload = params
else
payload = uri_encode(params)
end
end
request_opts.update(:headers => request_headers(api_key).update(headers),
:method => method, :open_timeout => 30,
:payload => payload, :url => url, :timeout => 80)
begin
response = execute_request(request_opts)
rescue SocketError => e
handle_restclient_error(e, api_base_url)
rescue NoMethodError => e
# Work around RestClient bug
if e.message =~ /\WRequestFailed\W/
e = APIConnectionError.new('Unexpected HTTP response code')
handle_restclient_error(e, api_base_url)
else
raise
end
rescue RestClient::ExceptionWithResponse => e
if rcode = e.http_code and rbody = e.http_body
handle_api_error(rcode, rbody)
else
handle_restclient_error(e, api_base_url)
end
rescue RestClient::Exception, Errno::ECONNREFUSED => e
handle_restclient_error(e, api_base_url)
end
[parse(response), api_key]
end
private
def self.ssl_preflight_passed?
if !verify_ssl_certs && !@no_verify
$stderr.puts "WARNING: Running without SSL cert verification. " +
"Execute 'Stripe.verify_ssl_certs = true' to enable verification."
@no_verify = true
elsif !Util.file_readable(@ssl_bundle_path) && !@no_bundle
$stderr.puts "WARNING: Running without SSL cert verification " +
"because #{@ssl_bundle_path} isn't readable"
@no_bundle = true
end
!(@no_verify || @no_bundle)
end
def self.user_agent
@uname ||= get_uname
lang_version = "#{RUBY_VERSION} p#{RUBY_PATCHLEVEL} (#{RUBY_RELEASE_DATE})"
{
:bindings_version => Stripe::VERSION,
:lang => 'ruby',
:lang_version => lang_version,
:platform => RUBY_PLATFORM,
:publisher => 'stripe',
:uname => @uname
} }
end
def self.get_uname
`uname -a 2>/dev/null`.strip if RUBY_PLATFORM =~ /linux|darwin/i
rescue Errno::ENOMEM => ex # couldn't create subprocess
"uname lookup failed"
end
def self.uri_encode(params)
Util.flatten_params(params).
map { |k,v| "#{k}=#{Util.url_encode(v)}" }.join('&')
end
def self.request_headers(api_key)
headers = {
:user_agent => "Stripe/v1 RubyBindings/#{Stripe::VERSION}",
:authorization => "Bearer #{api_key}",
:content_type => 'application/x-www-form-urlencoded'
}
headers[:stripe_version] = api_version if api_version
begin
headers.update(:x_stripe_client_user_agent => JSON.generate(user_agent))
rescue => e
headers.update(:x_stripe_client_raw_user_agent => user_agent.inspect,
:error => "#{e} (#{e.class})")
end end
end end
Stripe.log_level = ENV["STRIPE_LOG"] unless ENV["STRIPE_LOG"].nil? def self.execute_request(opts)
RestClient::Request.execute(opts)
end
def self.parse(response)
begin
# Would use :symbolize_names => true, but apparently there is
# some library out there that makes symbolize_names not work.
response = JSON.parse(response.body)
rescue JSON::ParserError
raise general_api_error(response.code, response.body)
end
Util.symbolize_names(response)
end
def self.general_api_error(rcode, rbody)
APIError.new("Invalid response object from API: #{rbody.inspect} " +
"(HTTP response code was #{rcode})", rcode, rbody)
end
def self.handle_api_error(rcode, rbody)
begin
error_obj = JSON.parse(rbody)
error_obj = Util.symbolize_names(error_obj)
error = error_obj[:error] or raise StripeError.new # escape from parsing
rescue JSON::ParserError, StripeError
raise general_api_error(rcode, rbody)
end
case rcode
when 400, 404
raise invalid_request_error error, rcode, rbody, error_obj
when 401
raise authentication_error error, rcode, rbody, error_obj
when 402
raise card_error error, rcode, rbody, error_obj
else
raise api_error error, rcode, rbody, error_obj
end
end
def self.invalid_request_error(error, rcode, rbody, error_obj)
InvalidRequestError.new(error[:message], error[:param], rcode,
rbody, error_obj)
end
def self.authentication_error(error, rcode, rbody, error_obj)
AuthenticationError.new(error[:message], rcode, rbody, error_obj)
end
def self.card_error(error, rcode, rbody, error_obj)
CardError.new(error[:message], error[:param], error[:code],
rcode, rbody, error_obj)
end
def self.api_error(error, rcode, rbody, error_obj)
APIError.new(error[:message], rcode, rbody, error_obj)
end
def self.handle_restclient_error(e, api_base_url=nil)
api_base_url = @api_base unless api_base_url
connection_message = "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."
case e
when RestClient::RequestTimeout
message = "Could not connect to Stripe (#{api_base_url}). #{connection_message}"
when RestClient::ServerBrokeConnection
message = "The connection to the server (#{api_base_url}) broke before the " \
"request completed. #{connection_message}"
when RestClient::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."
when SocketError
message = "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."
else
message = "Unexpected error communicating with Stripe. " \
"If this problem persists, let us know at support@stripe.com."
end
raise APIConnectionError.new(message + "\n\n(Network error: #{e.message})")
end
end

9
lib/stripe/account.rb Normal file
View File

@ -0,0 +1,9 @@
module Stripe
class Account < SingletonAPIResource
def deauthorize(client_id, opts={})
api_key, headers = Util.parse_opts(opts)
response, api_key = Stripe.request(:post, '/oauth/deauthorize', api_key, { 'client_id' => client_id, 'stripe_user_id' => self.id }, headers, Stripe.connect_base)
Util.convert_to_stripe_object(response, api_key)
end
end
end

View File

@ -1,15 +1,16 @@
# frozen_string_literal: true
module Stripe module Stripe
module APIOperations module APIOperations
module Create module Create
module ClassMethods
def create(params={}, opts={}) def create(params={}, opts={})
request_stripe_object( api_key, headers = Util.parse_opts(opts)
method: :post, response, api_key = Stripe.request(:post, self.url, api_key, params, headers)
path: resource_url, Util.convert_to_stripe_object(response, api_key)
params: params, end
opts: opts end
)
def self.included(base)
base.extend(ClassMethods)
end end
end end
end end

View File

@ -1,43 +1,10 @@
# frozen_string_literal: true
module Stripe module Stripe
module APIOperations module APIOperations
module Delete module Delete
module ClassMethods
# Deletes an API resource
#
# Deletes the identified resource with the passed in parameters.
#
# ==== Attributes
#
# * +id+ - ID of the resource to delete.
# * +params+ - A hash of parameters to pass to the API
# * +opts+ - A Hash of additional options (separate from the params /
# object values) to be added to the request. E.g. to allow for an
# idempotency_key to be passed in the request headers, or for the
# api_key to be overwritten. See
# {APIOperations::Request.execute_resource_request}.
def delete(id, params = {}, opts = {})
request_stripe_object(
method: :delete,
path: "#{resource_url}/#{id}",
params: params,
opts: opts
)
end
end
def delete(params = {}, opts={}) def delete(params = {}, opts={})
request_stripe_object( api_key, headers = Util.parse_opts(opts)
method: :delete, response, api_key = Stripe.request(:delete, url, api_key, params, headers)
path: resource_url, refresh_from(response, api_key)
params: params,
opts: opts
)
end
def self.included(base)
base.extend(ClassMethods)
end end
end end
end end

View File

@ -1,15 +1,16 @@
# frozen_string_literal: true
module Stripe module Stripe
module APIOperations module APIOperations
module List module List
def list(filters = {}, opts = {}) module ClassMethods
request_stripe_object( def all(filters={}, opts={})
method: :get, api_key, headers = Util.parse_opts(opts)
path: resource_url, response, api_key = Stripe.request(:get, url, api_key, filters, headers)
params: filters, Util.convert_to_stripe_object(response, api_key)
opts: opts end
) end
def self.included(base)
base.extend(ClassMethods)
end end
end end
end end

View File

@ -1,101 +0,0 @@
# frozen_string_literal: true
module Stripe
module APIOperations
# Adds methods to help manipulate a subresource from its parent resource so
# that it's possible to do so from a static context (i.e. without a
# pre-existing collection of subresources on the parent).
#
# For example, a transfer gains the static methods for reversals so that the
# methods `.create_reversal`, `.retrieve_reversal`, `.update_reversal`,
# etc. all become available.
module NestedResource
def nested_resource_class_methods(resource, path: nil, operations: nil,
resource_plural: nil)
resource_plural ||= "#{resource}s"
path ||= resource_plural
raise ArgumentError, "operations array required" if operations.nil?
resource_url_method = :"#{resource}s_url"
define_singleton_method(resource_url_method) do |id, nested_id = nil|
url = "#{resource_url}/#{CGI.escape(id)}/#{CGI.escape(path)}"
url += "/#{CGI.escape(nested_id)}" unless nested_id.nil?
url
end
operations.each do |operation|
define_operation(
resource,
operation,
resource_url_method,
resource_plural
)
end
end
private def define_operation(
resource,
operation,
resource_url_method,
resource_plural
)
case operation
when :create
define_singleton_method(:"create_#{resource}") \
do |id, params = {}, opts = {}|
request_stripe_object(
method: :post,
path: send(resource_url_method, id),
params: params,
opts: opts
)
end
when :retrieve
define_singleton_method(:"retrieve_#{resource}") \
do |id, nested_id, params = {}, opts = {}|
request_stripe_object(
method: :get,
path: send(resource_url_method, id, nested_id),
params: params,
opts: opts
)
end
when :update
define_singleton_method(:"update_#{resource}") \
do |id, nested_id, params = {}, opts = {}|
request_stripe_object(
method: :post,
path: send(resource_url_method, id, nested_id),
params: params,
opts: opts
)
end
when :delete
define_singleton_method(:"delete_#{resource}") \
do |id, nested_id, params = {}, opts = {}|
request_stripe_object(
method: :delete,
path: send(resource_url_method, id, nested_id),
params: params,
opts: opts
)
end
when :list
define_singleton_method(:"list_#{resource_plural}") \
do |id, params = {}, opts = {}|
request_stripe_object(
method: :get,
path: send(resource_url_method, id),
params: params,
opts: opts
)
end
else
raise ArgumentError, "Unknown operation: #{operation.inspect}"
end
end
end
end
end

View File

@ -1,94 +0,0 @@
# frozen_string_literal: true
module Stripe
module APIOperations
module Request
module ClassMethods
def execute_resource_request(method, url, base_address = :api,
params = {}, opts = {}, usage = [])
execute_resource_request_internal(
:execute_request, method, url, base_address, params, opts, usage
)
end
def execute_resource_request_stream(method, url, base_address = :api,
params = {}, opts = {}, usage = [],
&read_body_chunk_block)
execute_resource_request_internal(
:execute_request_stream,
method,
url,
base_address,
params,
opts,
usage,
&read_body_chunk_block
)
end
private def request_stripe_object(method:, path:, base_address: :api, params: {}, opts: {}, usage: [])
execute_resource_request(method, path, base_address, params, opts, usage)
end
private def execute_resource_request_internal(client_request_method_sym,
method, url, base_address,
params, opts, usage,
&read_body_chunk_block)
params = params.to_h if params.is_a?(Stripe::RequestParams)
params ||= {}
error_on_invalid_params(params)
warn_on_opts_in_params(params)
opts = Util.normalize_opts(opts)
req_opts = RequestOptions.extract_opts_from_hash(opts)
APIRequestor.active_requestor.send(
client_request_method_sym,
method, url,
base_address,
params: params, opts: req_opts, usage: usage,
&read_body_chunk_block
)
end
private def error_on_invalid_params(params)
return if params.nil? || params.is_a?(Hash)
raise ArgumentError,
"request params should be either a Hash or nil " \
"(was a #{params.class})"
end
private def warn_on_opts_in_params(params)
RequestOptions::OPTS_USER_SPECIFIED.each do |opt|
warn("WARNING: '#{opt}' should be in opts instead of params.") if params.key?(opt)
end
end
end
def self.included(base)
base.extend(ClassMethods)
end
protected def execute_resource_request(method, url, base_address = :api,
params = {}, opts = {}, usage = [])
opts = @opts.merge(Util.normalize_opts(opts))
self.class.execute_resource_request(method, url, base_address, params, opts, usage)
end
protected def execute_resource_request_stream(method, url, base_address = :api,
params = {}, opts = {}, usage = [],
&read_body_chunk_block)
opts = @opts.merge(Util.normalize_opts(opts))
self.class.execute_resource_request_stream(
method, url, base_address, params, opts, usage, &read_body_chunk_block
)
end
private def request_stripe_object(method:, path:, params:, base_address: :api, opts: {}, usage: [])
execute_resource_request(method, path, base_address, params, opts, usage)
end
end
end
end

View File

@ -1,107 +0,0 @@
# frozen_string_literal: true
module Stripe
module APIOperations
module Save
module ClassMethods
# Updates an API resource
#
# Updates the identified resource with the passed in parameters.
#
# ==== Attributes
#
# * +id+ - ID of the resource to update.
# * +params+ - A hash of parameters to pass to the API
# * +opts+ - A Hash of additional options (separate from the params /
# object values) to be added to the request. E.g. to allow for an
# idempotency_key to be passed in the request headers, or for the
# api_key to be overwritten. See
# {APIOperations::Request.execute_resource_request}.
def update(id, params = {}, opts = {})
params.each_key do |k|
raise ArgumentError, "Cannot update protected field: #{k}" if protected_fields.include?(k)
end
request_stripe_object(
method: :post,
path: "#{resource_url}/#{id}",
params: params,
opts: opts
)
end
end
# The `save` method is DEPRECATED and will be removed in a future major
# version of the library. Use the `update` method on the resource instead.
#
# Creates or updates an API resource.
#
# If the resource doesn't yet have an assigned ID and the resource is one
# that can be created, then the method attempts to create the resource.
# The resource is updated otherwise.
#
# ==== Attributes
#
# * +params+ - Overrides any parameters in the resource's serialized data
# and includes them in the create or update. If +:req_url:+ is included
# in the list, it overrides the update URL used for the create or
# update.
# * +opts+ - A Hash of additional options (separate from the params /
# object values) to be added to the request. E.g. to allow for an
# idempotency_key to be passed in the request headers, or for the
# api_key to be overwritten. See
# {APIOperations::Request.execute_resource_request}.
def save(params = {}, opts = {})
# We started unintentionally (sort of) allowing attributes sent to
# +save+ to override values used during the update. So as not to break
# the API, this makes that official here.
update_attributes(params)
# Now remove any parameters that look like object attributes.
params = params.reject { |k, _| respond_to?(k) }
values = serialize_params(self).merge(params)
# Please note that id gets removed here our call to #url above has already
# generated a uri for this object with an identifier baked in
values.delete(:id)
opts = Util.normalize_opts(opts)
APIRequestor.active_requestor.execute_request_initialize_from(:post, save_url, :api, self,
params: values,
opts: RequestOptions.extract_opts_from_hash(opts),
usage: ["save"])
end
extend Gem::Deprecate
deprecate :save, "the `update` class method (for examples " \
"see https://github.com/stripe/stripe-ruby" \
"/wiki/Migration-guide-for-v8)", 2022, 11
def self.included(base)
# Set `metadata` as additive so that when it's set directly we remember
# to clear keys that may have been previously set by sending empty
# values for them.
#
# It's possible that not every object with `Save` has `metadata`, but
# it's a close enough heuristic, and having this option set when there
# is no `metadata` field is not harmful.
base.additive_object_param(:metadata)
base.extend(ClassMethods)
end
private def save_url
# This switch essentially allows us "upsert"-like functionality. If the
# API resource doesn't have an ID set (suggesting that it's new) and
# its class responds to .create (which comes from
# Stripe::APIOperations::Create), then use the URL to create a new
# resource. Otherwise, generate a URL based on the object's identifier
# for a normal update.
if self[:id].nil? && self.class.respond_to?(:create)
self.class.resource_url
else
resource_url
end
end
end
end
end

View File

@ -1,21 +0,0 @@
# frozen_string_literal: true
module Stripe
module APIOperations
# The _search method via API Operations is deprecated.
# Please use the search method from within the resource instead.
module Search
def _search(search_url, filters = {}, opts = {})
request_stripe_object(
method: :get,
path: search_url,
params: filters,
opts: opts
)
end
extend Gem::Deprecate
deprecate :_search, "request_stripe_object", 2024, 1
end
end
end

View File

@ -1,90 +0,0 @@
# frozen_string_literal: true
module Stripe
module APIOperations
module SingletonSave
module ClassMethods
# Updates a singleton API resource
#
# Updates the identified resource with the passed in parameters.
#
# ==== Attributes
#
# * +params+ - A hash of parameters to pass to the API
# * +opts+ - A Hash of additional options (separate from the params /
# object values) to be added to the request. E.g. to allow for an
# idempotency_key to be passed in the request headers, or for the
# api_key to be overwritten. See
# {APIOperations::Request.execute_resource_request}.
def update(params = {}, opts = {})
params.each_key do |k|
raise ArgumentError, "Cannot update protected field: #{k}" if protected_fields.include?(k)
end
request_stripe_object(
method: :post,
path: resource_url,
params: params,
opts: opts
)
end
end
# The `save` method is DEPRECATED and will be removed in a future major
# version of the library. Use the `update` method on the resource instead.
#
# Updates a singleton API resource.
#
# If the resource doesn't yet have an assigned ID and the resource is one
# that can be created, then the method attempts to create the resource.
# The resource is updated otherwise.
#
# ==== Attributes
#
# * +params+ - Overrides any parameters in the resource's serialized data
# and includes them in the create or update. If +:req_url:+ is included
# in the list, it overrides the update URL used for the create or
# update.
# * +opts+ - A Hash of additional options (separate from the params /
# object values) to be added to the request. E.g. to allow for an
# idempotency_key to be passed in the request headers, or for the
# api_key to be overwritten. See
# {APIOperations::Request.execute_resource_request}.
def save(params = {}, opts = {})
# We started unintentionally (sort of) allowing attributes sent to
# +save+ to override values used during the update. So as not to break
# the API, this makes that official here.
update_attributes(params)
# Now remove any parameters that look like object attributes.
params = params.reject { |k, _| respond_to?(k) }
values = serialize_params(self).merge(params)
opts = Util.normalize_opts(opts)
APIRequestor.active_requestor.execute_request_initialize_from(:post, resource_url, :api, self,
params: values,
opts: RequestOptions.extract_opts_from_hash(opts),
usage: ["save"])
end
extend Gem::Deprecate
deprecate :save, "the `update` class method (for examples " \
"see https://github.com/stripe/stripe-ruby" \
"/wiki/Migration-guide-for-v8)", 2022, 11
def self.included(base)
# Set `metadata` as additive so that when it's set directly we remember
# to clear keys that may have been previously set by sending empty
# values for them.
#
# It's possible that not every object with `Save` has `metadata`, but
# it's a close enough heuristic, and having this option set when there
# is no `metadata` field is not harmful.
base.additive_object_param(:metadata)
base.extend(ClassMethods)
end
end
end
end

View File

@ -0,0 +1,57 @@
module Stripe
module APIOperations
module Update
def save(opts={})
values = serialize_params(self).merge(opts)
if @values[:metadata]
values[:metadata] = serialize_metadata
end
if values.length > 0
values.delete(:id)
response, api_key = Stripe.request(:post, url, @api_key, values)
refresh_from(response, api_key)
end
self
end
def serialize_metadata
if @unsaved_values.include?(:metadata)
# the metadata object has been reassigned
# i.e. as object.metadata = {key => val}
metadata_update = @values[:metadata] # new hash
new_keys = metadata_update.keys.map(&:to_sym)
# remove keys at the server, but not known locally
keys_to_unset = @previous_metadata.keys - new_keys
keys_to_unset.each {|key| metadata_update[key] = ''}
metadata_update
else
# metadata is a StripeObject, and can be serialized normally
serialize_params(@values[:metadata])
end
end
def serialize_params(obj)
case obj
when nil
''
when StripeObject
unsaved_keys = obj.instance_variable_get(:@unsaved_values)
obj_values = obj.instance_variable_get(:@values)
update_hash = {}
unsaved_keys.each do |k|
update_hash[k] = serialize_params(obj_values[k])
end
update_hash
else
obj
end
end
end
end
end

File diff suppressed because it is too large Load Diff

View File

@ -1,142 +1,32 @@
# frozen_string_literal: true
module Stripe module Stripe
class APIResource < StripeObject class APIResource < StripeObject
include Stripe::APIOperations::Request
# A flag that can be set a behavior that will cause this resource to be
# encoded and sent up along with an update of its parent resource. This is
# usually not desirable because resources are updated individually on their
# own endpoints, but there are certain cases, replacing a customer's source
# for example, where this is allowed.
attr_accessor :save_with_parent
# TODO: (major) Remove OBJECT_NAME and stop using const_get here
# This is a workaround to avoid breaking users who have defined their own
# APIResource subclasses with a custom OBJECT_NAME. We should never fallback
# on this case otherwise.
OBJECT_NAME = ""
def self.object_name
const_get(:OBJECT_NAME)
end
def self.class_name def self.class_name
name.split("::")[-1] self.name.split('::')[-1]
end
def self.resource_url
if name.include?("Stripe::V2")
raise NotImplementedError,
"V2 resources do not have a defined URL. Please use the StripeClient " \
"to make V2 requests"
end end
def self.url
if self == APIResource if self == APIResource
raise NotImplementedError, raise NotImplementedError.new('APIResource is an abstract class. You should perform actions on its subclasses (Charge, Customer, etc.)')
"APIResource is an abstract class. You should perform actions " \
"on its subclasses (Charge, Customer, etc.)"
end end
# Namespaces are separated in object names with periods (.) and in URLs "/v1/#{CGI.escape(class_name.downcase)}s"
# with forward slashes (/), so replace the former with the latter.
"/v1/#{object_name.downcase.tr('.', '/')}s"
end end
# A metaprogramming call that specifies that a field of a resource can be def url
# its own type of API resource (say a nested card under an account for unless id = self['id']
# example), and if that resource is set, it should be transmitted to the raise InvalidRequestError.new("Could not determine which URL to request: #{self.class} instance has invalid ID: #{id.inspect}", 'id')
# API on a create or update. Doing so is not the default behavior because
# API resources should normally be persisted on their own RESTful
# endpoints.
def self.save_nested_resource(name)
define_method(:"#{name}=") do |value|
super(value)
# The parent setter will perform certain useful operations like
# converting to an APIResource if appropriate. Refresh our argument
# value to whatever it mutated to.
value = send(name)
# Note that the value may be subresource, but could also be a scalar
# (like a tokenized card's ID for example), so we check the type before
# setting #save_with_parent here.
value.save_with_parent = true if value.is_a?(APIResource)
value
end end
end "#{self.class.url}/#{CGI.escape(id)}"
# Adds a custom method to a resource class. This is used to add support for
# non-CRUDL API requests, e.g. capturing charges. custom_method takes the
# following parameters:
# - name: the name of the custom method to create (as a symbol)
# - http_verb: the HTTP verb for the API request (:get, :post, or :delete)
# - http_path: the path to append to the resource's URL. If not provided,
# the name is used as the path
#
# For example, this call:
# custom_method :capture, http_verb: post
# adds a `capture` class method to the resource class that, when called,
# will send a POST request to `/v1/<object_name>/capture`.
def self.custom_method(name, http_verb:, http_path: nil)
Util.custom_method self, self, name, http_verb, http_path
end
def resource_url
unless (id = self["id"])
raise InvalidRequestError.new(
"Could not determine which URL to request: #{self.class} instance " \
"has invalid ID: #{id.inspect}",
"id"
)
end
"#{self.class.resource_url}/#{CGI.escape(id)}"
end end
def refresh def refresh
if self.class.name.include?("Stripe::V2") response, api_key = Stripe.request(:get, url, @api_key, @retrieve_options)
raise NotImplementedError, refresh_from(response, api_key)
"It is not possible to refresh v2 objects. Please retrieve the object using the StripeClient instead."
end end
opts = RequestOptions.extract_opts_from_hash(@retrieve_opts || {}) def self.retrieve(id, api_key=nil)
@retrieve_opts = {} # Make sure to clear the retrieve options instance = self.new(id, api_key)
@obj = @requestor.execute_request_initialize_from(:get, resource_url, :api, self, params: @retrieve_params,
opts: opts)
initialize_from(
@obj.last_response.data,
@obj.instance_variable_get(:@opts),
@obj.last_response,
api_mode: :v1,
requestor: @requestor
)
end
def self.retrieve(id, opts = {})
if name.include?("Stripe::V2")
raise NotImplementedError,
"It is not possible to retrieve v2 objects on the resource. Please use the StripeClient instead."
end
instance = new(id)
# Explicitly send options for the retrieve call, to preserve custom headers
# This is so we can pass custom headers from this static function
# to the instance variable method call
# The custom headers will be cleaned up with the rest of the RequestOptions
instance.instance_variable_set(:@retrieve_opts, Util.normalize_opts(opts))
instance.refresh instance.refresh
end instance
def request_stripe_object(method:, path:, params:, base_address: :api, opts: {})
APIRequestor.active_requestor.execute_request_initialize_from(method, path, base_address, self,
params: params, opts: opts)
end
protected def request_stream(method:, path:, params:, base_address: :api, opts: {},
&read_body_chunk_block)
resp, = execute_resource_request_stream(
method, path, base_address, params, opts, &read_body_chunk_block
)
resp
end end
end end
end end

View File

@ -1,53 +0,0 @@
# frozen_string_literal: true
module Stripe
# The base class for nested TestHelpers classes in resource objects.
# The APIResourceTestHelpers handles URL generation and custom method
# support for test-helper methods.
#
# class MyAPIResource < APIResource
# class TestHelpers < APIResourceTestHelpers
class APIResourceTestHelpers
include Stripe::APIOperations::Request
def initialize(resource)
@resource = resource
end
def self.resource_class
nil
end
# Adds a custom method to a test helper. This is used to add support for
# non-CRUDL API requests, e.g. capturing charges. custom_method takes the
# following parameters:
# - name: the name of the custom method to create (as a symbol)
# - http_verb: the HTTP verb for the API request (:get, :post, or :delete)
# - http_path: the path to append to the resource's URL. If not provided,
# the name is used as the path
#
# For example, this call:
# custom_method :capture, http_verb: post
# adds a `capture` class method to the resource class that, when called,
# will send a POST request to `/v1/<object_name>/capture`.
def self.custom_method(name, http_verb:, http_path: nil)
Util.custom_method resource_class, self, name, http_verb, http_path
end
def self.resource_url
"/v1/test_helpers/" \
"#{resource_class.object_name.downcase.tr('.', '/')}s"
end
def resource_url
unless (id = @resource["id"])
raise InvalidRequestError.new(
"Could not determine which URL to request: #{self.class} instance " \
"has invalid ID: #{id.inspect}",
"id"
)
end
"#{self.class.resource_url}/#{CGI.escape(id)}"
end
end
end

View File

@ -1,8 +0,0 @@
# File generated from our OpenAPI spec
# frozen_string_literal: true
module Stripe
module ApiVersion
CURRENT = "2025-05-28.basil"
end
end

View File

@ -0,0 +1,21 @@
module Stripe
class ApplicationFee < APIResource
include Stripe::APIOperations::List
def self.url
'/v1/application_fees'
end
def refund(params={}, opts={})
api_key, headers = Util.parse_opts(opts)
response, api_key = Stripe.request(:post, refund_url, api_key, params, headers)
refresh_from(response, api_key)
end
private
def refund_url
url + '/refund'
end
end
end

View File

@ -0,0 +1,14 @@
module Stripe
class ApplicationFeeRefund < APIResource
include Stripe::APIOperations::Update
include Stripe::APIOperations::List
def url
"#{ApplicationFee.url}/#{CGI.escape(fee)}/refunds/#{CGI.escape(id)}"
end
def self.retrieve(id, api_key=nil)
raise NotImplementedError.new("Refunds cannot be retrieved without an application fee ID. Retrieve a refund using appfee.refunds.retrieve('refund_id')")
end
end
end

4
lib/stripe/balance.rb Normal file
View File

@ -0,0 +1,4 @@
module Stripe
class Balance < SingletonAPIResource
end
end

View File

@ -0,0 +1,9 @@
module Stripe
class BalanceTransaction < APIResource
include Stripe::APIOperations::List
def self.url
'/v1/balance/history'
end
end
end

19
lib/stripe/card.rb Normal file
View File

@ -0,0 +1,19 @@
module Stripe
class Card < APIResource
include Stripe::APIOperations::Update
include Stripe::APIOperations::Delete
include Stripe::APIOperations::List
def url
if respond_to?(:recipient)
"#{Recipient.url}/#{CGI.escape(recipient)}/cards/#{CGI.escape(id)}"
elsif respond_to?(:customer)
"#{Customer.url}/#{CGI.escape(customer)}/cards/#{CGI.escape(id)}"
end
end
def self.retrieve(id, api_key=nil)
raise NotImplementedError.new("Cards cannot be retrieved without a customer ID. Retrieve a card using customer.cards.retrieve('card_id')")
end
end
end

View File

@ -0,0 +1,55 @@
require 'uri'
require 'digest/sha1'
module Stripe
module CertificateBlacklist
BLACKLIST = {
"api.stripe.com" => [
'05c0b3643694470a888c6e7feb5c9e24e823dc53',
],
"revoked.stripe.com" => [
'5b7dc7fbc98d78bf76d4d4fa6f597a0c901fad5c',
]
}
# Preflight the SSL certificate presented by the backend. This isn't 100%
# bulletproof, in that we're not actually validating the transport used to
# communicate with Stripe, merely that the first attempt to does not use a
# revoked certificate.
# Unfortunately the interface to OpenSSL doesn't make it easy to check the
# certificate before sending potentially sensitive data on the wire. This
# approach raises the bar for an attacker significantly.
def self.check_ssl_cert(uri, ca_file)
uri = URI.parse(uri)
sock = TCPSocket.new(uri.host, uri.port)
ctx = OpenSSL::SSL::SSLContext.new
ctx.set_params(:verify_mode => OpenSSL::SSL::VERIFY_PEER,
:ca_file => ca_file)
socket = OpenSSL::SSL::SSLSocket.new(sock, ctx)
socket.connect
certificate = socket.peer_cert.to_der
fingerprint = Digest::SHA1.hexdigest(certificate)
if blacklisted_certs = BLACKLIST[uri.host]
if blacklisted_certs.include?(fingerprint)
raise APIConnectionError.new(
"Invalid server certificate. You tried to connect to a server that" +
"has a revoked SSL certificate, which means we cannot securely send" +
"data to that server. Please email support@stripe.com if you need" +
"help connecting to the correct API server."
)
end
end
socket.close
return true
end
end
end

70
lib/stripe/charge.rb Normal file
View File

@ -0,0 +1,70 @@
module Stripe
class Charge < APIResource
include Stripe::APIOperations::List
include Stripe::APIOperations::Create
include Stripe::APIOperations::Update
def refund(params={}, opts={})
api_key, headers = Util.parse_opts(opts)
response, api_key = Stripe.request(
:post, refund_url, api_key || @api_key, params, headers)
refresh_from(response, api_key)
end
def capture(params={}, opts={})
api_key, headers = Util.parse_opts(opts)
response, api_key = Stripe.request(
:post, capture_url, api_key || @api_key, params, headers)
refresh_from(response, api_key)
end
def update_dispute(params={}, opts={})
api_key, headers = Util.parse_opts(opts)
response, api_key = Stripe.request(
:post, dispute_url, api_key || @api_key, params, headers)
refresh_from({ :dispute => response }, api_key, true)
dispute
end
def close_dispute(params={}, opts={})
api_key, headers = Util.parse_opts(opts)
response, api_key = Stripe.request(
:post, close_dispute_url, api_key || @api_key, params, headers)
refresh_from(response, api_key)
end
def mark_as_fraudulent
params = {
:fraud_details => { :user_report => 'fraudulent' }
}
response, api_key = Stripe.request(:post, url, @api_key, params)
refresh_from(response, api_key)
end
def mark_as_safe
params = {
:fraud_details => { :user_report => 'safe' }
}
response, api_key = Stripe.request(:post, url, @api_key, params)
refresh_from(response, api_key)
end
private
def refund_url
url + '/refund'
end
def capture_url
url + '/capture'
end
def dispute_url
url + '/dispute'
end
def close_dispute_url
url + '/dispute/close'
end
end
end

View File

@ -1,196 +0,0 @@
# frozen_string_literal: true
module Stripe
# Manages connections across multiple hosts which is useful because the
# library may connect to multiple hosts during a typical session (main API,
# Connect, Uploads). Ruby doesn't provide an easy way to make this happen
# easily, so this class is designed to track what we're connected to and
# manage the lifecycle of those connections.
#
# Note that this class in itself is *not* thread safe. We expect it to be
# instantiated once per thread.
class ConnectionManager
# Timestamp (in seconds procured from the system's monotonic clock)
# indicating when the connection manager last made a request. This is used
# by `APIRequestor` to determine whether a connection manager should be
# garbage collected or not.
attr_reader :last_used
attr_reader :config
def initialize(config = Stripe.config)
@config = config
@active_connections = {}
@last_used = Util.monotonic_time
# A connection manager may be accessed across threads as one thread makes
# requests on it while another is trying to clear it (either because it's
# trying to garbage collect the manager or trying to clear it because a
# configuration setting has changed). That's probably thread-safe already
# because of Ruby's GIL, but just in case the library's running on JRuby
# or the like, use a mutex to synchronize access in this connection
# manager.
@mutex = Mutex.new
end
# Finishes any active connections by closing their TCP connection and
# clears them from internal tracking.
def clear
@mutex.synchronize do
@active_connections.each_value(&:finish)
@active_connections = {}
end
end
# Gets a connection for a given URI. This is for internal use only as it's
# subject to change (we've moved between HTTP client schemes in the past
# and may do it again).
#
# `uri` is expected to be a string.
def connection_for(uri)
@mutex.synchronize do
u = URI.parse(uri)
connection = @active_connections[[u.host, u.port]]
if connection.nil?
connection = create_connection(u)
connection.start
@active_connections[[u.host, u.port]] = connection
end
connection
end
end
# Executes an HTTP request to the given URI with the given method. Also
# allows a request body, headers, and query string to be specified.
def execute_request(method, uri, body: nil, headers: nil, query: nil,
&block)
# Perform some basic argument validation because it's easy to get
# confused between strings and hashes for things like body and query
# parameters.
raise ArgumentError, "method should be a symbol" \
unless method.is_a?(Symbol)
raise ArgumentError, "uri should be a string" \
unless uri.is_a?(String)
raise ArgumentError, "body should be a string" \
if body && !body.is_a?(String)
raise ArgumentError, "headers should be a hash" \
if headers && !headers.is_a?(Hash)
raise ArgumentError, "query should be a string" \
if query && !query.is_a?(String)
@last_used = Util.monotonic_time
connection = connection_for(uri)
u = URI.parse(uri)
path = if query
u.path + "?" + query
else
u.path
end
method_name = method.to_s.upcase
has_response_body = method_name != "HEAD"
request = Net::HTTPGenericRequest.new(
method_name,
(body ? true : false),
has_response_body,
path,
headers
)
Util.log_debug("ConnectionManager starting request",
method_name: method_name,
path: path,
process_id: Process.pid,
thread_object_id: Thread.current.object_id,
connection_manager_object_id: object_id,
connection_object_id: connection.object_id,
log_timestamp: Util.monotonic_time)
resp = @mutex.synchronize do
# The block parameter is special here. If a block is provided, the block
# is invoked with the Net::HTTPResponse. However, the body will not have
# been read yet in the block, and can be streamed by calling
# HTTPResponse#read_body.
connection.request(request, body, &block)
end
Util.log_debug("ConnectionManager request complete",
method_name: method_name,
path: path,
process_id: Process.pid,
thread_object_id: Thread.current.object_id,
connection_manager_object_id: object_id,
connection_object_id: connection.object_id,
response_object_id: resp.object_id,
log_timestamp: Util.monotonic_time)
resp
end
#
# private
#
# `uri` should be a parsed `URI` object.
private def create_connection(uri)
# These all come back as `nil` if no proxy is configured.
proxy_host, proxy_port, proxy_user, proxy_pass = proxy_parts
connection = Net::HTTP.new(uri.host, uri.port,
proxy_host, proxy_port,
proxy_user, proxy_pass)
# Time in seconds within which Net::HTTP will try to reuse an already
# open connection when issuing a new operation. Outside this window, Ruby
# will transparently close and re-open the connection without trying to
# reuse it.
#
# Ruby's default of 2 seconds is almost certainly too short. Here I've
# reused Go's default for `DefaultTransport`.
connection.keep_alive_timeout = 30
connection.open_timeout = config.open_timeout
connection.read_timeout = config.read_timeout
connection.write_timeout = config.write_timeout if connection.respond_to?(:write_timeout=)
connection.use_ssl = uri.scheme == "https"
if config.verify_ssl_certs
connection.verify_mode = OpenSSL::SSL::VERIFY_PEER
connection.cert_store = config.ca_store
else
connection.verify_mode = OpenSSL::SSL::VERIFY_NONE
warn_ssl_verify_none
end
connection
end
# `Net::HTTP` somewhat awkwardly requires each component of a proxy URI
# (host, port, etc.) rather than the URI itself. This method simply parses
# out those pieces to make passing them into a new connection a little less
# ugly.
private def proxy_parts
if config.proxy.nil?
[nil, nil, nil, nil]
else
u = URI.parse(config.proxy)
[u.host, u.port, u.user, u.password]
end
end
private def warn_ssl_verify_none
return if @verify_ssl_warned
@verify_ssl_warned = true
warn("WARNING: Running without SSL cert verification. " \
"You should never do this in production. " \
"Execute `Stripe.verify_ssl_certs = true` to enable " \
"verification.")
end
end
end

8
lib/stripe/coupon.rb Normal file
View File

@ -0,0 +1,8 @@
module Stripe
class Coupon < APIResource
include Stripe::APIOperations::Create
include Stripe::APIOperations::Update
include Stripe::APIOperations::Delete
include Stripe::APIOperations::List
end
end

77
lib/stripe/customer.rb Normal file
View File

@ -0,0 +1,77 @@
module Stripe
class Customer < APIResource
include Stripe::APIOperations::Create
include Stripe::APIOperations::Delete
include Stripe::APIOperations::Update
include Stripe::APIOperations::List
def add_invoice_item(params, opts={})
opts[:api_key] = @api_key
InvoiceItem.create(params.merge(:customer => id), opts)
end
def invoices
Invoice.all({ :customer => id }, @api_key)
end
def invoice_items
InvoiceItem.all({ :customer => id }, @api_key)
end
def upcoming_invoice
Invoice.upcoming({ :customer => id }, @api_key)
end
def charges
Charge.all({ :customer => id }, @api_key)
end
def create_upcoming_invoice(params={}, opts={})
opts[:api_key] = @api_key
Invoice.create(params.merge(:customer => id), opts)
end
def cancel_subscription(params={}, opts={})
api_key, headers = Util.parse_opts(opts)
response, api_key = Stripe.request(
:delete, subscription_url, api_key || @api_key, params, headers)
refresh_from({ :subscription => response }, api_key, true)
subscription
end
def update_subscription(params={}, opts={})
api_key, headers = Util.parse_opts(opts)
response, api_key = Stripe.request(
:post, subscription_url, api_key || @api_key, params, headers)
refresh_from({ :subscription => response }, api_key, true)
subscription
end
def create_subscription(params={}, opts={})
api_key, headers = Util.parse_opts(opts)
response, api_key = Stripe.request(
:post, subscriptions_url, api_key || @api_key, params, headers)
refresh_from({ :subscription => response }, api_key, true)
subscription
end
def delete_discount
Stripe.request(:delete, discount_url, @api_key)
refresh_from({ :discount => nil }, api_key, true)
end
private
def discount_url
url + '/discount'
end
def subscription_url
url + '/subscription'
end
def subscriptions_url
url + '/subscriptions'
end
end
end

View File

@ -1,93 +0,0 @@
# frozen_string_literal: true
module Stripe
# Represents an error object as returned by the API.
#
# @see https://stripe.com/docs/api/errors
class ErrorObject < StripeObject
# Unlike other objects, we explicitly declare getter methods here. This
# is because the API doesn't return `null` values for fields on this
# object, rather the fields are omitted entirely. Not declaring the getter
# methods would cause users to run into `NoMethodError` exceptions and
# get in the way of generic error handling.
# For card errors, the ID of the failed charge.
def charge
@values[:charge]
end
# For some errors that could be handled programmatically, a short string
# indicating the error code reported.
def code
@values[:code]
end
# For card errors resulting from a card issuer decline, a short string
# indicating the card issuer's reason for the decline if they provide one.
def decline_code
@values[:decline_code]
end
# A URL to more information about the error code reported.
def doc_url
@values[:doc_url]
end
# A human-readable message providing more details about the error. For card
# errors, these messages can be shown to your users.
def message
@values[:message]
end
# If the error is parameter-specific, the parameter related to the error.
# For example, you can use this to display a message near the correct form
# field.
def param
@values[:param]
end
# The PaymentIntent object for errors returned on a request involving a
# PaymentIntent.
def payment_intent
@values[:payment_intent]
end
# The PaymentMethod object for errors returned on a request involving a
# PaymentMethod.
def payment_method
@values[:payment_method]
end
# The SetupIntent object for errors returned on a request involving a
# SetupIntent.
def setup_intent
@values[:setup_intent]
end
# The source object for errors returned on a request involving a source.
def source
@values[:source]
end
# The type of error returned. One of `api_error`, `card_error`,
# `idempotency_error`, or `invalid_request_error`.
def type
@values[:type]
end
end
# Represents on OAuth error returned by the OAuth API.
#
# @see https://stripe.com/docs/connect/oauth-reference#post-token-errors
class OAuthErrorObject < StripeObject
# A unique error code per error type.
def error
@values[:error]
end
# A human readable description of the error.
def error_description
@values[:error_description]
end
end
end

View File

@ -1,168 +0,0 @@
# frozen_string_literal: true
module Stripe
# StripeError is the base error from which all other more specific Stripe
# errors derive.
class StripeError < StandardError
attr_reader :message, :code, :error, :http_body, :http_headers, :http_status, :json_body, :request_id
# Response contains a StripeResponse object that has some basic information
# about the response that conveyed the error.
attr_accessor :response # equivalent to #data
# Initializes a StripeError.
def initialize(message = nil, http_status: nil, http_body: nil, # rubocop:todo Lint/MissingSuper
json_body: nil, http_headers: nil, code: nil)
@message = message
@http_status = http_status
@http_body = http_body
@http_headers = http_headers || {}
@idempotent_replayed = @http_headers["idempotent-replayed"] == "true"
@json_body = json_body
@code = code
@request_id = @http_headers["request-id"]
@error = construct_error_object
end
def construct_error_object
return nil if @json_body.nil? || !@json_body.key?(:error)
# ErrorObject is shared between v1 and v2, so use original object_classes to find
ErrorObject.construct_from(@json_body[:error], {}, nil, :v1)
end
def to_s
status_string = @http_status.nil? ? "" : "(Status #{@http_status}) "
id_string = @request_id.nil? ? "" : "(Request #{@request_id}) "
"#{status_string}#{id_string}#{@message}"
end
end
# AuthenticationError is raised when invalid credentials are used to connect
# to Stripe's servers.
class AuthenticationError < StripeError
end
# APIConnectionError is raised in the event that the SDK can't connect to
# Stripe's servers. That can be for a variety of different reasons from a
# downed network to a bad TLS certificate.
class APIConnectionError < StripeError
end
# APIError is a generic error that may be raised in cases where none of the
# other named errors cover the problem. It could also be raised in the case
# that a new error has been introduced in the API, but this version of the
# Ruby SDK doesn't know how to handle it.
class APIError < StripeError
end
# CardError is raised when a user enters a card that can't be charged for
# some reason.
class CardError < StripeError
attr_reader :param
def initialize(message, param, code: nil, http_status: nil, http_body: nil,
json_body: nil, http_headers: nil)
super(message, http_status: http_status, http_body: http_body,
json_body: json_body, http_headers: http_headers,
code: code)
@param = param
end
end
# IdempotencyError is raised in cases where an idempotency key was used
# improperly.
class IdempotencyError < StripeError
end
# InvalidRequestError is raised when a request is initiated with invalid
# parameters.
class InvalidRequestError < StripeError
attr_accessor :param
def initialize(message, param, http_status: nil, http_body: nil,
json_body: nil, http_headers: nil, code: nil)
super(message, http_status: http_status, http_body: http_body,
json_body: json_body, http_headers: http_headers,
code: code)
@param = param
end
end
# PermissionError is raised in cases where access was attempted on a resource
# that wasn't allowed.
class PermissionError < StripeError
end
# RateLimitError is raised in cases where an account is putting too much load
# on Stripe's API servers (usually by performing too many requests). Please
# back off on request rate.
class RateLimitError < StripeError
end
# SignatureVerificationError is raised when the signature verification for a
# webhook fails
class SignatureVerificationError < StripeError
attr_accessor :sig_header
def initialize(message, sig_header, http_body: nil)
super(message, http_body: http_body)
@sig_header = sig_header
end
end
module OAuth
# OAuthError is raised when the OAuth API returns an error.
class OAuthError < StripeError
def initialize(code, description, http_status: nil, http_body: nil,
json_body: nil, http_headers: nil)
super(description, http_status: http_status, http_body: http_body,
json_body: json_body, http_headers: http_headers,
code: code)
end
def construct_error_object
return nil if @json_body.nil?
OAuthErrorObject.construct_from(@json_body, {}, nil, :v1)
end
end
# InvalidClientError is raised when the client doesn't belong to you, or
# the API key mode (live or test) doesn't match the client mode. Or the
# stripe_user_id doesn't exist or isn't connected to your application.
class InvalidClientError < OAuthError
end
# InvalidGrantError is raised when a specified code doesn't exist, is
# expired, has been used, or doesn't belong to you; a refresh token doesn't
# exist, or doesn't belong to you; or if an API key's mode (live or test)
# doesn't match the mode of a code or refresh token.
class InvalidGrantError < OAuthError
end
# InvalidRequestError is raised when a code, refresh token, or grant type
# parameter is not provided, but was required.
class InvalidRequestError < OAuthError
end
# InvalidScopeError is raised when an invalid scope parameter is provided.
class InvalidScopeError < OAuthError
end
# UnsupportedGrantTypeError is raised when an unuspported grant type
# parameter is specified.
class UnsupportedGrantTypeError < OAuthError
end
# UnsupportedResponseTypeError is raised when an unsupported response type
# parameter is specified.
class UnsupportedResponseTypeError < OAuthError
end
end
# class definitions: The beginning of the section generated from our OpenAPI spec
class TemporarySessionExpiredError < StripeError
end
# class definitions: The end of the section generated from our OpenAPI spec
end

View File

@ -0,0 +1,4 @@
module Stripe
class APIConnectionError < StripeError
end
end

View File

@ -0,0 +1,4 @@
module Stripe
class APIError < StripeError
end
end

View File

@ -0,0 +1,4 @@
module Stripe
class AuthenticationError < StripeError
end
end

View File

@ -0,0 +1,11 @@
module Stripe
class CardError < StripeError
attr_reader :param, :code
def initialize(message, param, code, http_status=nil, http_body=nil, json_body=nil)
super(message, http_status, http_body, json_body)
@param = param
@code = code
end
end
end

View File

@ -0,0 +1,10 @@
module Stripe
class InvalidRequestError < StripeError
attr_accessor :param
def initialize(message, param, http_status=nil, http_body=nil, json_body=nil)
super(message, http_status, http_body, json_body)
@param = param
end
end
end

View File

@ -0,0 +1,20 @@
module Stripe
class StripeError < StandardError
attr_reader :message
attr_reader :http_status
attr_reader :http_body
attr_reader :json_body
def initialize(message=nil, http_status=nil, http_body=nil, json_body=nil)
@message = message
@http_status = http_status
@http_body = http_body
@json_body = json_body
end
def to_s
status_string = @http_status.nil? ? "" : "(Status #{@http_status}) "
"#{status_string}#{@message}"
end
end
end

5
lib/stripe/event.rb Normal file
View File

@ -0,0 +1,5 @@
module Stripe
class Event < APIResource
include Stripe::APIOperations::List
end
end

View File

@ -1,15 +0,0 @@
# frozen_string_literal: true
module Stripe
module EventTypes
def self.thin_event_names_to_classes
{
# The beginning of the section generated from our OpenAPI spec
V1BillingMeterErrorReportTriggeredEvent.lookup_type => V1BillingMeterErrorReportTriggeredEvent,
V1BillingMeterNoMeterFoundEvent.lookup_type => V1BillingMeterNoMeterFoundEvent,
V2CoreEventDestinationPingEvent.lookup_type => V2CoreEventDestinationPingEvent,
# The end of the section generated from our OpenAPI spec
}
end
end
end

View File

@ -1,23 +0,0 @@
# File generated from our OpenAPI spec
# frozen_string_literal: true
module Stripe
# Occurs when a Meter has invalid async usage events.
class V1BillingMeterErrorReportTriggeredEvent < Stripe::V2::Event
def self.lookup_type
"v1.billing.meter.error_report_triggered"
end
# There is additional data present for this event, accessible with the `data` property.
# See the Stripe API docs for more information.
# Retrieves the related object from the API. Make an API request on every call.
def fetch_related_object
_request(
method: :get,
path: related_object.url,
base_address: :api,
opts: { stripe_account: context }
)
end
end
end

View File

@ -1,13 +0,0 @@
# File generated from our OpenAPI spec
# frozen_string_literal: true
module Stripe
# Occurs when a Meter's id is missing or invalid in async usage events.
class V1BillingMeterNoMeterFoundEvent < Stripe::V2::Event
def self.lookup_type
"v1.billing.meter.no_meter_found"
end
# There is additional data present for this event, accessible with the `data` property.
# See the Stripe API docs for more information.
end
end

View File

@ -1,21 +0,0 @@
# File generated from our OpenAPI spec
# frozen_string_literal: true
module Stripe
# A ping event used to test the connection to an event destination.
class V2CoreEventDestinationPingEvent < Stripe::V2::Event
def self.lookup_type
"v2.core.event_destination.ping"
end
# Retrieves the related object from the API. Make an API request on every call.
def fetch_related_object
_request(
method: :get,
path: related_object.url,
base_address: :api,
opts: { stripe_account: context }
)
end
end
end

27
lib/stripe/file_upload.rb Normal file
View File

@ -0,0 +1,27 @@
module Stripe
class FileUpload < APIResource
UPLOADS_API_BASE = "https://uploads.stripe.com"
def self.url
"/v1/files"
end
def self.request_headers
{
:content_type => 'multipart/form-data',
}
end
def self.create(params={}, api_key=nil)
response, api_key = Stripe.request(
:post, self.url, api_key, params, self.request_headers, UPLOADS_API_BASE)
Util.convert_to_stripe_object(response, api_key)
end
def refresh
response, api_key = Stripe.request(
:get, url, @api_key, @retrieve_options, self.class.request_headers, UPLOADS_API_BASE)
refresh_from(response, api_key)
end
end
end

View File

@ -1,106 +0,0 @@
# frozen_string_literal: true
module Stripe
class Instrumentation
# Event emitted on `request_begin` callback.
class RequestBeginEvent
attr_reader :method, :path
# Arbitrary user-provided data in the form of a Ruby hash that's passed
# from subscribers on `request_begin` to subscribers on `request_end`.
# `request_begin` subscribers can set keys which will then be available
# in `request_end`.
#
# Note that all subscribers of `request_begin` share the same object, so
# they must be careful to set unique keys so as to not conflict with data
# set by other subscribers.
attr_reader :user_data
def initialize(method:, path:, user_data:)
@method = method
@path = path
@user_data = user_data
freeze
end
end
# Event emitted on `request_end` callback.
class RequestEndEvent
attr_reader :duration, :http_status, :method, :num_retries, :path, :request_id, :response_header, :response_body,
:request_header, :request_body
# Arbitrary user-provided data in the form of a Ruby hash that's passed
# from subscribers on `request_begin` to subscribers on `request_end`.
# `request_begin` subscribers can set keys which will then be available
# in `request_end`.
attr_reader :user_data
def initialize(request_context:, response_context:,
num_retries:, user_data: nil)
@duration = request_context.duration
@http_status = response_context.http_status
@method = request_context.method
@num_retries = num_retries
@path = request_context.path
@request_id = request_context.request_id
@user_data = user_data
@response_header = response_context.header
@response_body = response_context.body
@request_header = request_context.header
@request_body = request_context.body
freeze
end
end
class RequestContext
attr_reader :duration, :method, :path, :request_id, :body, :header
def initialize(duration:, context:, header:)
@duration = duration
@method = context.method
@path = context.path
@request_id = context.request_id
@body = context.body
@header = header
end
end
class ResponseContext
attr_reader :http_status, :body, :header
def initialize(http_status:, response:)
@http_status = http_status
@header = response ? response.to_hash : nil
@body = response ? response.body : nil
end
end
# This class was renamed for consistency. This alias is here for backwards
# compatibility.
RequestEvent = RequestEndEvent
# Returns true if there are a non-zero number of subscribers on the given
# topic, and false otherwise.
def self.any_subscribers?(topic)
!subscribers[topic].empty?
end
def self.subscribe(topic, name = rand, &block)
subscribers[topic][name] = block
name
end
def self.unsubscribe(topic, name)
subscribers[topic].delete(name)
end
def self.notify(topic, event)
subscribers[topic].each_value { |subscriber| subscriber.call(event) }
end
def self.subscribers
@subscribers ||= Hash.new { |hash, key| hash[key] = {} }
end
private_class_method :subscribers
end
end

27
lib/stripe/invoice.rb Normal file
View File

@ -0,0 +1,27 @@
module Stripe
class Invoice < APIResource
include Stripe::APIOperations::List
include Stripe::APIOperations::Update
include Stripe::APIOperations::Create
def self.upcoming(params, api_key = nil)
response, api_key = Stripe.request(:get, upcoming_url, api_key, params)
Util.convert_to_stripe_object(response, api_key)
end
def pay
response, api_key = Stripe.request(:post, pay_url, @api_key)
refresh_from(response, api_key)
end
private
def self.upcoming_url
url + '/upcoming'
end
def pay_url
url + '/pay'
end
end
end

View File

@ -0,0 +1,8 @@
module Stripe
class InvoiceItem < APIResource
include Stripe::APIOperations::List
include Stripe::APIOperations::Create
include Stripe::APIOperations::Delete
include Stripe::APIOperations::Update
end
end

View File

@ -1,141 +1,37 @@
# frozen_string_literal: true
module Stripe module Stripe
class ListObject < StripeObject class ListObject < StripeObject
include Enumerable
include Stripe::APIOperations::List
include Stripe::APIOperations::Request
include Stripe::APIOperations::Create
OBJECT_NAME = "list" def [](k)
def self.object_name case k
"list"
end
# This accessor allows a `ListObject` to inherit various filters that were
# given to a predecessor. This allows for things like consistent limits,
# expansions, and predicates as a user pages through resources.
attr_accessor :filters
# An empty list object. This is returned from +next+ when we know that
# there isn't a next page in order to replicate the behavior of the API
# when it attempts to return a page beyond the last.
def self.empty_list(opts = {})
ListObject.construct_from({ data: [] }, opts, nil, :v1)
end
def initialize(*args)
super
self.filters = {}
end
def [](key)
case key
when String, Symbol when String, Symbol
super super
else else
raise ArgumentError, raise ArgumentError.new("You tried to access the #{k.inspect} index, but ListObject types only support String keys. (HINT: List calls return an object with a 'data' (which is the data array). You likely want to call #data[#{k.inspect}])")
"You tried to access the #{key.inspect} index, but ListObject " \
"types only support String keys. (HINT: List calls return an " \
"object with a 'data' (which is the data array). You likely " \
"want to call #data[#{key.inspect}])"
end end
end end
# Iterates through each resource in the page represented by the current
# `ListObject`.
#
# Note that this method makes no effort to fetch a new page when it gets to
# the end of the current page's resources. See also +auto_paging_each+.
def each(&blk) def each(&blk)
data.each(&blk) self.data.each(&blk)
end end
# Iterates through each resource in all pages, making additional fetches to def retrieve(id, api_key=nil)
# the API as necessary. api_key ||= @api_key
# response, api_key = Stripe.request(:get,"#{url}/#{CGI.escape(id)}", api_key)
# The default iteration direction is forwards according to Stripe's API Util.convert_to_stripe_object(response, api_key)
# "natural" ordering direction -- newer objects first, and moving towards
# older objects.
#
# However, if the initial list object was fetched using an `ending_before`
# cursor (and only `ending_before`, `starting_after` cannot also be
# included), the method assumes that the user is trying to iterate
# backwards compared to natural ordering and returns results that way --
# older objects first, and moving towards newer objects.
#
# Note that this method will make as many API calls as necessary to fetch
# all resources. For more granular control, please see +each+ and
# +next_page+.
def auto_paging_each(&blk)
return enum_for(:auto_paging_each) unless block_given?
page = self
loop do
# Backward iterating activates if we have an `ending_before` constraint
# and _just_ an `ending_before` constraint. If `starting_after` was
# also used, we iterate forwards normally.
if filters.include?(:ending_before) &&
!filters.include?(:starting_after)
page.reverse_each(&blk)
page = page.previous_page
else
page.each(&blk)
page = page.next_page
end end
break if page.empty? def create(params={}, opts={})
end api_key, headers = Util.parse_opts(opts)
api_key ||= @api_key
response, api_key = Stripe.request(:post, url, api_key, params, headers)
Util.convert_to_stripe_object(response, api_key)
end end
# Returns true if the page object contains no elements. def all(params={}, opts={})
def empty? api_key, headers = Util.parse_opts(opts)
data.empty? api_key ||= @api_key
end response, api_key = Stripe.request(:get, url, api_key, params, headers)
Util.convert_to_stripe_object(response, api_key)
def retrieve(id, opts = {})
id, retrieve_params = Util.normalize_id(id)
url = "#{resource_url}/#{CGI.escape(id)}"
execute_resource_request(:get, url, :api, retrieve_params, opts)
end
# Fetches the next page in the resource list (if there is one).
#
# This method will try to respect the limit of the current page. If none
# was given, the default limit will be fetched again.
def next_page(params = {}, opts = {})
return self.class.empty_list(opts) unless has_more
last_id = data.last.id
params = filters.merge(starting_after: last_id).merge(params)
list(params, opts)
end
# Fetches the previous page in the resource list (if there is one).
#
# This method will try to respect the limit of the current page. If none
# was given, the default limit will be fetched again.
def previous_page(params = {}, opts = {})
return self.class.empty_list(opts) unless has_more
first_id = data.first.id
params = filters.merge(ending_before: first_id).merge(params)
list(params, opts)
end
def resource_url
url ||
raise(ArgumentError, "List object does not contain a 'url' field.")
end
# Iterates through each resource in the page represented by the current
# `ListObject` in reverse.
def reverse_each(&blk)
data.reverse_each(&blk)
end end
end end
end end

View File

@ -1,131 +0,0 @@
# frozen_string_literal: true
require "securerandom"
require "tempfile"
module Stripe
# Encodes parameters into a `multipart/form-data` payload as described by RFC
# 2388:
#
# https://tools.ietf.org/html/rfc2388
#
# This is most useful for transferring file-like objects.
#
# Parameters should be added with `#encode`. When ready, use `#body` to get
# the encoded result and `#content_type` to get the value that should be
# placed in the `Content-Type` header of a subsequent request (which includes
# a boundary value).
class MultipartEncoder
MULTIPART_FORM_DATA = "multipart/form-data"
# A shortcut for encoding a single set of parameters and finalizing a
# result.
#
# Returns an encoded body and the value that should be set in the content
# type header of a subsequent request.
def self.encode(params)
encoder = MultipartEncoder.new
encoder.encode(params)
encoder.close
[encoder.body, encoder.content_type]
end
# Gets the object's randomly generated boundary string.
attr_reader :boundary
# Initializes a new multipart encoder.
def initialize
# Kind of weird, but required by Rubocop because the unary plus operator
# is considered faster than `Stripe.new`.
@body = +""
# Chose the same number of random bytes that Go uses in its standard
# library implementation. Easily enough entropy to ensure that it won't
# be present in a file we're sending.
@boundary = SecureRandom.hex(30)
@closed = false
@first_field = true
end
# Gets the encoded body. `#close` must be called first.
def body
raise "object must be closed before getting body" unless @closed
@body
end
# Finalizes the object by writing the final boundary.
def close
raise "object already closed" if @closed
@body << "\r\n"
@body << "--#{@boundary}--"
@closed = true
nil
end
# Gets the value including boundary that should be put into a multipart
# request's `Content-Type`.
def content_type
"#{MULTIPART_FORM_DATA}; boundary=#{@boundary}"
end
# Encodes a set of parameters to the body.
#
# Note that parameters are expected to be a hash, but a "flat" hash such
# that complex substructures like hashes and arrays have already been
# appropriately Stripe-encoded. Pass a complex structure through
# `Util.flatten_params` first before handing it off to this method.
def encode(params)
raise "no more parameters can be written to closed object" if @closed
params.each do |name, val|
if val.is_a?(::File) || val.is_a?(::Tempfile)
write_field(name, val.read, filename: ::File.basename(val.path))
elsif val.respond_to?(:read)
write_field(name, val.read, filename: "blob")
else
write_field(name, val, filename: nil)
end
end
nil
end
#
# private
#
# Escapes double quotes so that the given value can be used in a
# double-quoted string and replaces any linebreak characters with spaces.
private def escape(str)
str.gsub('"', "%22").tr("\n", " ").tr("\r", " ")
end
private def write_field(name, data, filename:)
if @first_field
@first_field = false
else
@body << "\r\n"
end
@body << "--#{@boundary}\r\n"
if filename
@body << (%(Content-Disposition: form-data) +
%(; name="#{escape(name.to_s)}") +
%(; filename="#{escape(filename)}"\r\n))
@body << %(Content-Type: application/octet-stream\r\n)
else
@body << (%(Content-Disposition: form-data) +
%(; name="#{escape(name.to_s)}"\r\n))
end
@body << "\r\n"
@body << data.to_s
end
end
end

View File

@ -1,58 +0,0 @@
# frozen_string_literal: true
module Stripe
module OAuth
module OAuthOperations
extend APIOperations::Request::ClassMethods
def self.execute_resource_request(method, url, base_address, params, opts)
opts = Util.normalize_opts(opts)
super
end
end
def self.get_client_id(params = {})
client_id = params[:client_id] || Stripe.client_id
unless client_id
raise AuthenticationError, "No client_id provided. " \
'Set your client_id using "Stripe.client_id = <CLIENT-ID>". ' \
"You can find your client_ids in your Stripe dashboard at " \
"https://dashboard.stripe.com/account/applications/settings, " \
"after registering your account as a platform. See " \
"https://stripe.com/docs/connect/standalone-accounts for details, " \
"or email support@stripe.com if you have any questions."
end
client_id
end
def self.authorize_url(params = {}, opts = {})
base = opts[:connect_base] || APIRequestor.active_requestor.config.connect_base
path = "/oauth/authorize"
path = "/express" + path if opts[:express]
params[:client_id] = get_client_id(params)
params[:response_type] ||= "code"
query = Util.encode_parameters(params, :v1)
"#{base}#{path}?#{query}"
end
def self.token(params = {}, opts = {})
opts = Util.normalize_opts(opts)
opts[:api_key] = params[:client_secret] if params[:client_secret]
OAuthOperations.execute_resource_request(
:post, "/oauth/token", :connect, params, opts
)
end
def self.deauthorize(params = {}, opts = {})
opts = Util.normalize_opts(opts)
params[:client_id] = get_client_id(params)
OAuthOperations.execute_resource_request(
:post, "/oauth/deauthorize", :connect, params, opts
)
end
end
end

View File

@ -1,173 +0,0 @@
# frozen_string_literal: true
# rubocop:disable Metrics/MethodLength
module Stripe
module ObjectTypes
def self.object_names_to_classes
{
# data structures
ListObject.object_name => ListObject,
SearchResultObject.object_name => SearchResultObject,
File.object_name_alt => File,
# object classes: The beginning of the section generated from our OpenAPI spec
Account.object_name => Account,
AccountLink.object_name => AccountLink,
AccountSession.object_name => AccountSession,
ApplePayDomain.object_name => ApplePayDomain,
Application.object_name => Application,
ApplicationFee.object_name => ApplicationFee,
ApplicationFeeRefund.object_name => ApplicationFeeRefund,
Apps::Secret.object_name => Apps::Secret,
Balance.object_name => Balance,
BalanceTransaction.object_name => BalanceTransaction,
BankAccount.object_name => BankAccount,
Billing::Alert.object_name => Billing::Alert,
Billing::AlertTriggered.object_name => Billing::AlertTriggered,
Billing::CreditBalanceSummary.object_name => Billing::CreditBalanceSummary,
Billing::CreditBalanceTransaction.object_name => Billing::CreditBalanceTransaction,
Billing::CreditGrant.object_name => Billing::CreditGrant,
Billing::Meter.object_name => Billing::Meter,
Billing::MeterEvent.object_name => Billing::MeterEvent,
Billing::MeterEventAdjustment.object_name => Billing::MeterEventAdjustment,
Billing::MeterEventSummary.object_name => Billing::MeterEventSummary,
BillingPortal::Configuration.object_name => BillingPortal::Configuration,
BillingPortal::Session.object_name => BillingPortal::Session,
Capability.object_name => Capability,
Card.object_name => Card,
CashBalance.object_name => CashBalance,
Charge.object_name => Charge,
Checkout::Session.object_name => Checkout::Session,
Climate::Order.object_name => Climate::Order,
Climate::Product.object_name => Climate::Product,
Climate::Supplier.object_name => Climate::Supplier,
ConfirmationToken.object_name => ConfirmationToken,
ConnectCollectionTransfer.object_name => ConnectCollectionTransfer,
CountrySpec.object_name => CountrySpec,
Coupon.object_name => Coupon,
CreditNote.object_name => CreditNote,
CreditNoteLineItem.object_name => CreditNoteLineItem,
Customer.object_name => Customer,
CustomerBalanceTransaction.object_name => CustomerBalanceTransaction,
CustomerCashBalanceTransaction.object_name => CustomerCashBalanceTransaction,
CustomerSession.object_name => CustomerSession,
Discount.object_name => Discount,
Dispute.object_name => Dispute,
Entitlements::ActiveEntitlement.object_name => Entitlements::ActiveEntitlement,
Entitlements::ActiveEntitlementSummary.object_name => Entitlements::ActiveEntitlementSummary,
Entitlements::Feature.object_name => Entitlements::Feature,
EphemeralKey.object_name => EphemeralKey,
Event.object_name => Event,
ExchangeRate.object_name => ExchangeRate,
File.object_name => File,
FileLink.object_name => FileLink,
FinancialConnections::Account.object_name => FinancialConnections::Account,
FinancialConnections::AccountOwner.object_name => FinancialConnections::AccountOwner,
FinancialConnections::AccountOwnership.object_name => FinancialConnections::AccountOwnership,
FinancialConnections::Session.object_name => FinancialConnections::Session,
FinancialConnections::Transaction.object_name => FinancialConnections::Transaction,
Forwarding::Request.object_name => Forwarding::Request,
FundingInstructions.object_name => FundingInstructions,
Identity::VerificationReport.object_name => Identity::VerificationReport,
Identity::VerificationSession.object_name => Identity::VerificationSession,
Invoice.object_name => Invoice,
InvoiceItem.object_name => InvoiceItem,
InvoiceLineItem.object_name => InvoiceLineItem,
InvoicePayment.object_name => InvoicePayment,
InvoiceRenderingTemplate.object_name => InvoiceRenderingTemplate,
Issuing::Authorization.object_name => Issuing::Authorization,
Issuing::Card.object_name => Issuing::Card,
Issuing::Cardholder.object_name => Issuing::Cardholder,
Issuing::Dispute.object_name => Issuing::Dispute,
Issuing::PersonalizationDesign.object_name => Issuing::PersonalizationDesign,
Issuing::PhysicalBundle.object_name => Issuing::PhysicalBundle,
Issuing::Token.object_name => Issuing::Token,
Issuing::Transaction.object_name => Issuing::Transaction,
LineItem.object_name => LineItem,
LoginLink.object_name => LoginLink,
Mandate.object_name => Mandate,
PaymentIntent.object_name => PaymentIntent,
PaymentLink.object_name => PaymentLink,
PaymentMethod.object_name => PaymentMethod,
PaymentMethodConfiguration.object_name => PaymentMethodConfiguration,
PaymentMethodDomain.object_name => PaymentMethodDomain,
Payout.object_name => Payout,
Person.object_name => Person,
Plan.object_name => Plan,
Price.object_name => Price,
Product.object_name => Product,
ProductFeature.object_name => ProductFeature,
PromotionCode.object_name => PromotionCode,
Quote.object_name => Quote,
Radar::EarlyFraudWarning.object_name => Radar::EarlyFraudWarning,
Radar::ValueList.object_name => Radar::ValueList,
Radar::ValueListItem.object_name => Radar::ValueListItem,
Refund.object_name => Refund,
Reporting::ReportRun.object_name => Reporting::ReportRun,
Reporting::ReportType.object_name => Reporting::ReportType,
ReserveTransaction.object_name => ReserveTransaction,
Reversal.object_name => Reversal,
Review.object_name => Review,
SetupAttempt.object_name => SetupAttempt,
SetupIntent.object_name => SetupIntent,
ShippingRate.object_name => ShippingRate,
Sigma::ScheduledQueryRun.object_name => Sigma::ScheduledQueryRun,
Source.object_name => Source,
SourceMandateNotification.object_name => SourceMandateNotification,
SourceTransaction.object_name => SourceTransaction,
Subscription.object_name => Subscription,
SubscriptionItem.object_name => SubscriptionItem,
SubscriptionSchedule.object_name => SubscriptionSchedule,
Tax::Calculation.object_name => Tax::Calculation,
Tax::CalculationLineItem.object_name => Tax::CalculationLineItem,
Tax::Registration.object_name => Tax::Registration,
Tax::Settings.object_name => Tax::Settings,
Tax::Transaction.object_name => Tax::Transaction,
Tax::TransactionLineItem.object_name => Tax::TransactionLineItem,
TaxCode.object_name => TaxCode,
TaxDeductedAtSource.object_name => TaxDeductedAtSource,
TaxId.object_name => TaxId,
TaxRate.object_name => TaxRate,
Terminal::Configuration.object_name => Terminal::Configuration,
Terminal::ConnectionToken.object_name => Terminal::ConnectionToken,
Terminal::Location.object_name => Terminal::Location,
Terminal::Reader.object_name => Terminal::Reader,
TestHelpers::TestClock.object_name => TestHelpers::TestClock,
Token.object_name => Token,
Topup.object_name => Topup,
Transfer.object_name => Transfer,
Treasury::CreditReversal.object_name => Treasury::CreditReversal,
Treasury::DebitReversal.object_name => Treasury::DebitReversal,
Treasury::FinancialAccount.object_name => Treasury::FinancialAccount,
Treasury::FinancialAccountFeatures.object_name => Treasury::FinancialAccountFeatures,
Treasury::InboundTransfer.object_name => Treasury::InboundTransfer,
Treasury::OutboundPayment.object_name => Treasury::OutboundPayment,
Treasury::OutboundTransfer.object_name => Treasury::OutboundTransfer,
Treasury::ReceivedCredit.object_name => Treasury::ReceivedCredit,
Treasury::ReceivedDebit.object_name => Treasury::ReceivedDebit,
Treasury::Transaction.object_name => Treasury::Transaction,
Treasury::TransactionEntry.object_name => Treasury::TransactionEntry,
WebhookEndpoint.object_name => WebhookEndpoint,
# object classes: The end of the section generated from our OpenAPI spec
}
end
def self.v2_object_names_to_classes
{
V2::ListObject.object_name => V2::ListObject,
# v2 object classes: The beginning of the section generated from our OpenAPI spec
V2::Billing::MeterEvent.object_name => V2::Billing::MeterEvent,
V2::Billing::MeterEventAdjustment.object_name => V2::Billing::MeterEventAdjustment,
V2::Billing::MeterEventSession.object_name => V2::Billing::MeterEventSession,
V2::Event.object_name => V2::Event,
V2::EventDestination.object_name => V2::EventDestination,
# v2 object classes: The end of the section generated from our OpenAPI spec
}
end
end
end
# rubocop:enable Metrics/AbcSize
# rubocop:enable Metrics/MethodLength

8
lib/stripe/plan.rb Normal file
View File

@ -0,0 +1,8 @@
module Stripe
class Plan < APIResource
include Stripe::APIOperations::Create
include Stripe::APIOperations::Delete
include Stripe::APIOperations::List
include Stripe::APIOperations::Update
end
end

12
lib/stripe/recipient.rb Normal file
View File

@ -0,0 +1,12 @@
module Stripe
class Recipient < APIResource
include Stripe::APIOperations::Create
include Stripe::APIOperations::Delete
include Stripe::APIOperations::Update
include Stripe::APIOperations::List
def transfers
Transfer.all({ :recipient => id }, @api_key)
end
end
end

14
lib/stripe/refund.rb Normal file
View File

@ -0,0 +1,14 @@
module Stripe
class Refund < APIResource
include Stripe::APIOperations::Update
include Stripe::APIOperations::List
def url
"#{Charge.url}/#{CGI.escape(charge)}/refunds/#{CGI.escape(id)}"
end
def self.retrieve(id, api_key=nil)
raise NotImplementedError.new("Refunds cannot be retrieved without a charge ID. Retrieve a refund using charge.refunds.retrieve('refund_id')")
end
end
end

View File

@ -1,129 +0,0 @@
# frozen_string_literal: true
# typed: true
module Stripe
# RequestOptions is a class that encapsulates configurable options
# for requests made to the Stripe API. It is used by the APIRequestor
# to set per-request options.
#
# For internal use only. Does not provide a stable API and may be broken
# with future non-major changes.
module RequestOptions
# Options that a user is allowed to specify.
OPTS_USER_SPECIFIED = Set[
:api_key,
:idempotency_key,
:stripe_account,
:stripe_context,
:stripe_version
].freeze
# Options that should be copyable from one StripeObject to another
# including options that may be internal.
OPTS_COPYABLE = (
OPTS_USER_SPECIFIED + Set[:api_base]
).freeze
# Options that should be persisted between API requests.
OPTS_PERSISTABLE = (
OPTS_USER_SPECIFIED - Set[:idempotency_key, :stripe_context]
).freeze
# Merges requestor options on a StripeConfiguration object
# with a per-request options hash, giving precedence
# to the per-request options. Expects StripeConfiguration and hash.
def self.merge_config_and_opts(config, req_opts)
# Raise an error if config is not a StripeConfiguration object
unless config.is_a?(StripeConfiguration)
raise ArgumentError, "config must be a Stripe::StripeConfiguration object"
end
merged_opts = {
api_key: req_opts[:api_key] || config.api_key,
idempotency_key: req_opts[:idempotency_key],
stripe_account: req_opts[:stripe_account] || config.stripe_account,
stripe_context: req_opts[:stripe_context] || config.stripe_context,
stripe_version: req_opts[:stripe_version] || config.api_version,
headers: req_opts[:headers] || {},
}
# Remove nil values from headers
merged_opts.delete_if { |_, v| v.nil? }
merged_opts
end
# Merges requestor options hash on a StripeObject
# with a per-request options hash, giving precedence
# to the per-request options. Returns the merged request options.
# Expects two hashes, expects extract_opts_from_hash to be called first!!!
def self.combine_opts(object_opts, req_opts)
merged_opts = {
api_key: req_opts[:api_key] || object_opts[:api_key],
idempotency_key: req_opts[:idempotency_key],
stripe_account: req_opts[:stripe_account] || object_opts[:stripe_account],
stripe_context: req_opts[:stripe_context] || object_opts[:stripe_context],
stripe_version: req_opts[:stripe_version] || object_opts[:stripe_version],
headers: req_opts[:headers] || {},
}
# Remove nil values from headers
merged_opts.delete_if { |_, v| v.nil? }
merged_opts
end
# Extracts options from a user-provided hash, returning a new request options hash
# containing the recognized request options and a `headers` entry for the remaining options.
def self.extract_opts_from_hash(opts)
req_opts = {}
normalized_opts = Util.normalize_opts(opts.clone)
RequestOptions.error_on_non_string_user_opts(normalized_opts)
OPTS_USER_SPECIFIED.each do |opt|
req_opts[opt] = normalized_opts[opt] if normalized_opts.key?(opt)
normalized_opts.delete(opt)
end
# Remaining user-provided opts should be treated as headers
req_opts[:headers] = Util.normalize_headers(normalized_opts) if normalized_opts.any?
req_opts
end
# Validates a normalized opts hash.
def self.error_on_non_string_user_opts(normalized_opts)
OPTS_USER_SPECIFIED.each do |opt|
next unless normalized_opts.key?(opt)
val = normalized_opts[opt]
next if val.nil?
next if val.is_a?(String)
raise ArgumentError,
"request option '#{opt}' should be a string value " \
"(was a #{val.class})"
end
end
# Get options that persist between requests
def self.persistable(req_opts)
opts_to_persist = {}
# Hash#select returns an array before 1.9
req_opts.each do |k, v|
opts_to_persist[k] = v if RequestOptions::OPTS_PERSISTABLE.include?(k)
end
opts_to_persist
end
# Get options that are copyable from StripeObject to StripeObject
def self.copyable(req_opts)
req_opts.select do |k, _v|
RequestOptions::OPTS_COPYABLE.include?(k)
end
end
end
end

View File

@ -1,24 +0,0 @@
# frozen_string_literal: true
# typed: true
module Stripe
# For internal use only. Does not provide a stable API and may be broken
# with future non-major changes.
class RequestParams
def to_h
instance_variables.each_with_object({}) do |var, hash|
key = var.to_s.delete("@").to_sym
value = instance_variable_get(var)
hash[key] = if value.is_a?(RequestParams)
value.to_h
# Check if value is an array and contains RequestParams objects
elsif value.is_a?(Array)
value.map { |item| item.is_a?(RequestParams) ? item.to_h : item }
else
value
end
end
end
end
end

View File

@ -1,148 +0,0 @@
# File generated from our OpenAPI spec
# frozen_string_literal: true
require "stripe/resources/account"
require "stripe/resources/account_link"
require "stripe/resources/account_session"
require "stripe/resources/apple_pay_domain"
require "stripe/resources/application"
require "stripe/resources/application_fee"
require "stripe/resources/application_fee_refund"
require "stripe/resources/apps/secret"
require "stripe/resources/balance"
require "stripe/resources/balance_transaction"
require "stripe/resources/bank_account"
require "stripe/resources/billing/alert"
require "stripe/resources/billing/alert_triggered"
require "stripe/resources/billing/credit_balance_summary"
require "stripe/resources/billing/credit_balance_transaction"
require "stripe/resources/billing/credit_grant"
require "stripe/resources/billing/meter"
require "stripe/resources/billing/meter_event"
require "stripe/resources/billing/meter_event_adjustment"
require "stripe/resources/billing/meter_event_summary"
require "stripe/resources/billing_portal/configuration"
require "stripe/resources/billing_portal/session"
require "stripe/resources/capability"
require "stripe/resources/card"
require "stripe/resources/cash_balance"
require "stripe/resources/charge"
require "stripe/resources/checkout/session"
require "stripe/resources/climate/order"
require "stripe/resources/climate/product"
require "stripe/resources/climate/supplier"
require "stripe/resources/confirmation_token"
require "stripe/resources/connect_collection_transfer"
require "stripe/resources/country_spec"
require "stripe/resources/coupon"
require "stripe/resources/credit_note"
require "stripe/resources/credit_note_line_item"
require "stripe/resources/customer"
require "stripe/resources/customer_balance_transaction"
require "stripe/resources/customer_cash_balance_transaction"
require "stripe/resources/customer_session"
require "stripe/resources/discount"
require "stripe/resources/dispute"
require "stripe/resources/entitlements/active_entitlement"
require "stripe/resources/entitlements/active_entitlement_summary"
require "stripe/resources/entitlements/feature"
require "stripe/resources/ephemeral_key"
require "stripe/resources/event"
require "stripe/resources/exchange_rate"
require "stripe/resources/file"
require "stripe/resources/file_link"
require "stripe/resources/financial_connections/account"
require "stripe/resources/financial_connections/account_owner"
require "stripe/resources/financial_connections/account_ownership"
require "stripe/resources/financial_connections/session"
require "stripe/resources/financial_connections/transaction"
require "stripe/resources/forwarding/request"
require "stripe/resources/funding_instructions"
require "stripe/resources/identity/verification_report"
require "stripe/resources/identity/verification_session"
require "stripe/resources/invoice"
require "stripe/resources/invoice_item"
require "stripe/resources/invoice_line_item"
require "stripe/resources/invoice_payment"
require "stripe/resources/invoice_rendering_template"
require "stripe/resources/issuing/authorization"
require "stripe/resources/issuing/card"
require "stripe/resources/issuing/cardholder"
require "stripe/resources/issuing/dispute"
require "stripe/resources/issuing/personalization_design"
require "stripe/resources/issuing/physical_bundle"
require "stripe/resources/issuing/token"
require "stripe/resources/issuing/transaction"
require "stripe/resources/line_item"
require "stripe/resources/login_link"
require "stripe/resources/mandate"
require "stripe/resources/payment_intent"
require "stripe/resources/payment_link"
require "stripe/resources/payment_method"
require "stripe/resources/payment_method_configuration"
require "stripe/resources/payment_method_domain"
require "stripe/resources/payout"
require "stripe/resources/person"
require "stripe/resources/plan"
require "stripe/resources/price"
require "stripe/resources/product"
require "stripe/resources/product_feature"
require "stripe/resources/promotion_code"
require "stripe/resources/quote"
require "stripe/resources/radar/early_fraud_warning"
require "stripe/resources/radar/value_list"
require "stripe/resources/radar/value_list_item"
require "stripe/resources/refund"
require "stripe/resources/reporting/report_run"
require "stripe/resources/reporting/report_type"
require "stripe/resources/reserve_transaction"
require "stripe/resources/reversal"
require "stripe/resources/review"
require "stripe/resources/setup_attempt"
require "stripe/resources/setup_intent"
require "stripe/resources/shipping_rate"
require "stripe/resources/sigma/scheduled_query_run"
require "stripe/resources/source"
require "stripe/resources/source_mandate_notification"
require "stripe/resources/source_transaction"
require "stripe/resources/subscription"
require "stripe/resources/subscription_item"
require "stripe/resources/subscription_schedule"
require "stripe/resources/tax/calculation"
require "stripe/resources/tax/calculation_line_item"
require "stripe/resources/tax/registration"
require "stripe/resources/tax/settings"
require "stripe/resources/tax/transaction"
require "stripe/resources/tax/transaction_line_item"
require "stripe/resources/tax_code"
require "stripe/resources/tax_deducted_at_source"
require "stripe/resources/tax_id"
require "stripe/resources/tax_rate"
require "stripe/resources/terminal/configuration"
require "stripe/resources/terminal/connection_token"
require "stripe/resources/terminal/location"
require "stripe/resources/terminal/reader"
require "stripe/resources/test_helpers/test_clock"
require "stripe/resources/token"
require "stripe/resources/topup"
require "stripe/resources/transfer"
require "stripe/resources/treasury/credit_reversal"
require "stripe/resources/treasury/debit_reversal"
require "stripe/resources/treasury/financial_account"
require "stripe/resources/treasury/financial_account_features"
require "stripe/resources/treasury/inbound_transfer"
require "stripe/resources/treasury/outbound_payment"
require "stripe/resources/treasury/outbound_transfer"
require "stripe/resources/treasury/received_credit"
require "stripe/resources/treasury/received_debit"
require "stripe/resources/treasury/transaction"
require "stripe/resources/treasury/transaction_entry"
require "stripe/resources/v2/billing/meter_event"
require "stripe/resources/v2/billing/meter_event_adjustment"
require "stripe/resources/v2/billing/meter_event_session"
require "stripe/resources/v2/event"
require "stripe/resources/v2/event_destination"
require "stripe/resources/webhook_endpoint"
require "stripe/events/v1_billing_meter_error_report_triggered_event"
require "stripe/events/v1_billing_meter_no_meter_found_event"
require "stripe/events/v2_core_event_destination_ping_event"

File diff suppressed because it is too large Load Diff

View File

@ -1,76 +0,0 @@
# File generated from our OpenAPI spec
# frozen_string_literal: true
module Stripe
# 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)
class AccountLink < APIResource
extend Stripe::APIOperations::Create
OBJECT_NAME = "account_link"
def self.object_name
"account_link"
end
class CreateParams < Stripe::RequestParams
class CollectionOptions < 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
def initialize(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
def initialize(
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.
def self.create(params = {}, opts = {})
request_stripe_object(method: :post, path: "/v1/account_links", params: params, opts: opts)
end
end
end

View File

@ -1,868 +0,0 @@
# File generated from our OpenAPI spec
# frozen_string_literal: true
module Stripe
# 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)
class AccountSession < APIResource
extend Stripe::APIOperations::Create
OBJECT_NAME = "account_session"
def self.object_name
"account_session"
end
class Components < Stripe::StripeObject
class AccountManagement < Stripe::StripeObject
class Features < 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 dont 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 youre 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
class AccountOnboarding < Stripe::StripeObject
class Features < 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 dont 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 youre 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
class Balances < Stripe::StripeObject
class Features < 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 dont 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 youre 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
class DisputesList < Stripe::StripeObject
class Features < 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.
attr_reader :destination_on_behalf_of_charge_management
# 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
class Documents < Stripe::StripeObject
class Features < Stripe::StripeObject; end
# Whether the embedded component is enabled.
attr_reader :enabled
# Attribute for field features
attr_reader :features
end
class FinancialAccount < Stripe::StripeObject
class Features < 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 dont 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.
attr_reader :external_account_collection
# Whether to allow sending money.
attr_reader :send_money
# Whether to allow transferring balance.
attr_reader :transfer_balance
end
# Whether the embedded component is enabled.
attr_reader :enabled
# Attribute for field features
attr_reader :features
end
class FinancialAccountTransactions < Stripe::StripeObject
class Features < Stripe::StripeObject
# 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
class IssuingCard < Stripe::StripeObject
class Features < 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
class IssuingCardsList < Stripe::StripeObject
class Features < 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 youre 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
class NotificationBanner < Stripe::StripeObject
class Features < 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 dont 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 youre 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
class PaymentDetails < Stripe::StripeObject
class Features < 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.
attr_reader :destination_on_behalf_of_charge_management
# 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
class PaymentDisputes < Stripe::StripeObject
class Features < Stripe::StripeObject
# Whether to allow connected accounts to manage destination charges that are created on behalf of them. This is `false` by default.
attr_reader :destination_on_behalf_of_charge_management
# 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
class Payments < Stripe::StripeObject
class Features < 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.
attr_reader :destination_on_behalf_of_charge_management
# 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
class Payouts < Stripe::StripeObject
class Features < 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 dont 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 youre 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
class PayoutsList < Stripe::StripeObject
class Features < Stripe::StripeObject; end
# Whether the embedded component is enabled.
attr_reader :enabled
# Attribute for field features
attr_reader :features
end
class TaxRegistrations < Stripe::StripeObject
class Features < Stripe::StripeObject; end
# Whether the embedded component is enabled.
attr_reader :enabled
# Attribute for field features
attr_reader :features
end
class TaxSettings < Stripe::StripeObject
class Features < 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
class CreateParams < Stripe::RequestParams
class Components < Stripe::RequestParams
class AccountManagement < Stripe::RequestParams
class Features < 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 dont 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 youre 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
def initialize(
disable_stripe_user_authentication: nil,
external_account_collection: nil
)
@disable_stripe_user_authentication = disable_stripe_user_authentication
@external_account_collection = external_account_collection
end
end
# Whether the embedded component is enabled.
attr_accessor :enabled
# The list of features enabled in the embedded component.
attr_accessor :features
def initialize(enabled: nil, features: nil)
@enabled = enabled
@features = features
end
end
class AccountOnboarding < Stripe::RequestParams
class Features < 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 dont 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 youre 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
def initialize(
disable_stripe_user_authentication: nil,
external_account_collection: nil
)
@disable_stripe_user_authentication = disable_stripe_user_authentication
@external_account_collection = external_account_collection
end
end
# Whether the embedded component is enabled.
attr_accessor :enabled
# The list of features enabled in the embedded component.
attr_accessor :features
def initialize(enabled: nil, features: nil)
@enabled = enabled
@features = features
end
end
class Balances < Stripe::RequestParams
class Features < 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 dont 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 youre 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.
attr_accessor :standard_payouts
def initialize(
disable_stripe_user_authentication: nil,
edit_payout_schedule: nil,
external_account_collection: nil,
instant_payouts: nil,
standard_payouts: nil
)
@disable_stripe_user_authentication = disable_stripe_user_authentication
@edit_payout_schedule = edit_payout_schedule
@external_account_collection = external_account_collection
@instant_payouts = instant_payouts
@standard_payouts = standard_payouts
end
end
# Whether the embedded component is enabled.
attr_accessor :enabled
# The list of features enabled in the embedded component.
attr_accessor :features
def initialize(enabled: nil, features: nil)
@enabled = enabled
@features = features
end
end
class DisputesList < Stripe::RequestParams
class Features < Stripe::RequestParams
# Whether to allow capturing and cancelling payment intents. This is `true` by default.
attr_accessor :capture_payments
# Whether to allow connected accounts to manage destination charges that are created on behalf of them. This is `false` by default.
attr_accessor :destination_on_behalf_of_charge_management
# Whether to allow responding to disputes, including submitting evidence and accepting disputes. This is `true` by default.
attr_accessor :dispute_management
# Whether to allow sending refunds. This is `true` by default.
attr_accessor :refund_management
def initialize(
capture_payments: nil,
destination_on_behalf_of_charge_management: nil,
dispute_management: nil,
refund_management: nil
)
@capture_payments = capture_payments
@destination_on_behalf_of_charge_management = destination_on_behalf_of_charge_management
@dispute_management = dispute_management
@refund_management = refund_management
end
end
# Whether the embedded component is enabled.
attr_accessor :enabled
# The list of features enabled in the embedded component.
attr_accessor :features
def initialize(enabled: nil, features: nil)
@enabled = enabled
@features = features
end
end
class Documents < Stripe::RequestParams
class Features < Stripe::RequestParams; end
# Whether the embedded component is enabled.
attr_accessor :enabled
# The list of features enabled in the embedded component.
attr_accessor :features
def initialize(enabled: nil, features: nil)
@enabled = enabled
@features = features
end
end
class FinancialAccount < Stripe::RequestParams
class Features < 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 dont 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.
attr_accessor :external_account_collection
# Whether to allow sending money.
attr_accessor :send_money
# Whether to allow transferring balance.
attr_accessor :transfer_balance
def initialize(
disable_stripe_user_authentication: nil,
external_account_collection: nil,
send_money: nil,
transfer_balance: nil
)
@disable_stripe_user_authentication = disable_stripe_user_authentication
@external_account_collection = external_account_collection
@send_money = send_money
@transfer_balance = transfer_balance
end
end
# Whether the embedded component is enabled.
attr_accessor :enabled
# The list of features enabled in the embedded component.
attr_accessor :features
def initialize(enabled: nil, features: nil)
@enabled = enabled
@features = features
end
end
class FinancialAccountTransactions < Stripe::RequestParams
class Features < Stripe::RequestParams
# Whether to allow card spend dispute management features.
attr_accessor :card_spend_dispute_management
def initialize(card_spend_dispute_management: nil)
@card_spend_dispute_management = card_spend_dispute_management
end
end
# Whether the embedded component is enabled.
attr_accessor :enabled
# The list of features enabled in the embedded component.
attr_accessor :features
def initialize(enabled: nil, features: nil)
@enabled = enabled
@features = features
end
end
class IssuingCard < Stripe::RequestParams
class Features < 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
# Whether to allow spend control management features.
attr_accessor :spend_control_management
def initialize(
card_management: nil,
card_spend_dispute_management: nil,
cardholder_management: nil,
spend_control_management: nil
)
@card_management = card_management
@card_spend_dispute_management = card_spend_dispute_management
@cardholder_management = cardholder_management
@spend_control_management = spend_control_management
end
end
# Whether the embedded component is enabled.
attr_accessor :enabled
# The list of features enabled in the embedded component.
attr_accessor :features
def initialize(enabled: nil, features: nil)
@enabled = enabled
@features = features
end
end
class IssuingCardsList < Stripe::RequestParams
class Features < 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 youre 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.
attr_accessor :spend_control_management
def initialize(
card_management: nil,
card_spend_dispute_management: nil,
cardholder_management: nil,
disable_stripe_user_authentication: nil,
spend_control_management: nil
)
@card_management = card_management
@card_spend_dispute_management = card_spend_dispute_management
@cardholder_management = cardholder_management
@disable_stripe_user_authentication = disable_stripe_user_authentication
@spend_control_management = spend_control_management
end
end
# Whether the embedded component is enabled.
attr_accessor :enabled
# The list of features enabled in the embedded component.
attr_accessor :features
def initialize(enabled: nil, features: nil)
@enabled = enabled
@features = features
end
end
class NotificationBanner < Stripe::RequestParams
class Features < 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 dont 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 youre 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
def initialize(
disable_stripe_user_authentication: nil,
external_account_collection: nil
)
@disable_stripe_user_authentication = disable_stripe_user_authentication
@external_account_collection = external_account_collection
end
end
# Whether the embedded component is enabled.
attr_accessor :enabled
# The list of features enabled in the embedded component.
attr_accessor :features
def initialize(enabled: nil, features: nil)
@enabled = enabled
@features = features
end
end
class PaymentDetails < Stripe::RequestParams
class Features < Stripe::RequestParams
# Whether to allow capturing and cancelling payment intents. This is `true` by default.
attr_accessor :capture_payments
# Whether to allow connected accounts to manage destination charges that are created on behalf of them. This is `false` by default.
attr_accessor :destination_on_behalf_of_charge_management
# Whether to allow responding to disputes, including submitting evidence and accepting disputes. This is `true` by default.
attr_accessor :dispute_management
# Whether to allow sending refunds. This is `true` by default.
attr_accessor :refund_management
def initialize(
capture_payments: nil,
destination_on_behalf_of_charge_management: nil,
dispute_management: nil,
refund_management: nil
)
@capture_payments = capture_payments
@destination_on_behalf_of_charge_management = destination_on_behalf_of_charge_management
@dispute_management = dispute_management
@refund_management = refund_management
end
end
# Whether the embedded component is enabled.
attr_accessor :enabled
# The list of features enabled in the embedded component.
attr_accessor :features
def initialize(enabled: nil, features: nil)
@enabled = enabled
@features = features
end
end
class PaymentDisputes < Stripe::RequestParams
class Features < Stripe::RequestParams
# Whether to allow connected accounts to manage destination charges that are created on behalf of them. This is `false` by default.
attr_accessor :destination_on_behalf_of_charge_management
# Whether to allow responding to disputes, including submitting evidence and accepting disputes. This is `true` by default.
attr_accessor :dispute_management
# Whether to allow sending refunds. This is `true` by default.
attr_accessor :refund_management
def initialize(
destination_on_behalf_of_charge_management: nil,
dispute_management: nil,
refund_management: nil
)
@destination_on_behalf_of_charge_management = destination_on_behalf_of_charge_management
@dispute_management = dispute_management
@refund_management = refund_management
end
end
# Whether the embedded component is enabled.
attr_accessor :enabled
# The list of features enabled in the embedded component.
attr_accessor :features
def initialize(enabled: nil, features: nil)
@enabled = enabled
@features = features
end
end
class Payments < Stripe::RequestParams
class Features < Stripe::RequestParams
# Whether to allow capturing and cancelling payment intents. This is `true` by default.
attr_accessor :capture_payments
# Whether to allow connected accounts to manage destination charges that are created on behalf of them. This is `false` by default.
attr_accessor :destination_on_behalf_of_charge_management
# Whether to allow responding to disputes, including submitting evidence and accepting disputes. This is `true` by default.
attr_accessor :dispute_management
# Whether to allow sending refunds. This is `true` by default.
attr_accessor :refund_management
def initialize(
capture_payments: nil,
destination_on_behalf_of_charge_management: nil,
dispute_management: nil,
refund_management: nil
)
@capture_payments = capture_payments
@destination_on_behalf_of_charge_management = destination_on_behalf_of_charge_management
@dispute_management = dispute_management
@refund_management = refund_management
end
end
# Whether the embedded component is enabled.
attr_accessor :enabled
# The list of features enabled in the embedded component.
attr_accessor :features
def initialize(enabled: nil, features: nil)
@enabled = enabled
@features = features
end
end
class Payouts < Stripe::RequestParams
class Features < 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 dont 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 youre 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.
attr_accessor :standard_payouts
def initialize(
disable_stripe_user_authentication: nil,
edit_payout_schedule: nil,
external_account_collection: nil,
instant_payouts: nil,
standard_payouts: nil
)
@disable_stripe_user_authentication = disable_stripe_user_authentication
@edit_payout_schedule = edit_payout_schedule
@external_account_collection = external_account_collection
@instant_payouts = instant_payouts
@standard_payouts = standard_payouts
end
end
# Whether the embedded component is enabled.
attr_accessor :enabled
# The list of features enabled in the embedded component.
attr_accessor :features
def initialize(enabled: nil, features: nil)
@enabled = enabled
@features = features
end
end
class PayoutsList < Stripe::RequestParams
class Features < Stripe::RequestParams; end
# Whether the embedded component is enabled.
attr_accessor :enabled
# The list of features enabled in the embedded component.
attr_accessor :features
def initialize(enabled: nil, features: nil)
@enabled = enabled
@features = features
end
end
class TaxRegistrations < Stripe::RequestParams
class Features < Stripe::RequestParams; end
# Whether the embedded component is enabled.
attr_accessor :enabled
# The list of features enabled in the embedded component.
attr_accessor :features
def initialize(enabled: nil, features: nil)
@enabled = enabled
@features = features
end
end
class TaxSettings < Stripe::RequestParams
class Features < Stripe::RequestParams; end
# Whether the embedded component is enabled.
attr_accessor :enabled
# The list of features enabled in the embedded component.
attr_accessor :features
def initialize(enabled: nil, features: nil)
@enabled = enabled
@features = features
end
end
# Configuration for the account management embedded component.
attr_accessor :account_management
# Configuration for the account onboarding embedded component.
attr_accessor :account_onboarding
# Configuration for the balances embedded component.
attr_accessor :balances
# Configuration for the disputes list embedded component.
attr_accessor :disputes_list
# Configuration for the documents embedded component.
attr_accessor :documents
# Configuration for the financial account embedded component.
attr_accessor :financial_account
# Configuration for the financial account transactions embedded component.
attr_accessor :financial_account_transactions
# Configuration for the issuing card embedded component.
attr_accessor :issuing_card
# Configuration for the issuing cards list embedded component.
attr_accessor :issuing_cards_list
# Configuration for the notification banner embedded component.
attr_accessor :notification_banner
# Configuration for the payment details embedded component.
attr_accessor :payment_details
# Configuration for the payment disputes embedded component.
attr_accessor :payment_disputes
# Configuration for the payments embedded component.
attr_accessor :payments
# Configuration for the payouts embedded component.
attr_accessor :payouts
# Configuration for the payouts list embedded component.
attr_accessor :payouts_list
# Configuration for the tax registrations embedded component.
attr_accessor :tax_registrations
# Configuration for the tax settings embedded component.
attr_accessor :tax_settings
def initialize(
account_management: nil,
account_onboarding: nil,
balances: nil,
disputes_list: nil,
documents: nil,
financial_account: nil,
financial_account_transactions: nil,
issuing_card: nil,
issuing_cards_list: nil,
notification_banner: nil,
payment_details: nil,
payment_disputes: nil,
payments: nil,
payouts: nil,
payouts_list: nil,
tax_registrations: nil,
tax_settings: nil
)
@account_management = account_management
@account_onboarding = account_onboarding
@balances = balances
@disputes_list = disputes_list
@documents = documents
@financial_account = financial_account
@financial_account_transactions = financial_account_transactions
@issuing_card = issuing_card
@issuing_cards_list = issuing_cards_list
@notification_banner = notification_banner
@payment_details = payment_details
@payment_disputes = payment_disputes
@payments = payments
@payouts = payouts
@payouts_list = payouts_list
@tax_registrations = tax_registrations
@tax_settings = tax_settings
end
end
# 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.
attr_accessor :expand
def initialize(account: nil, components: nil, expand: nil)
@account = account
@components = components
@expand = expand
end
end
# 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.
def self.create(params = {}, opts = {})
request_stripe_object(method: :post, path: "/v1/account_sessions", params: params, opts: opts)
end
end
end

View File

@ -1,34 +0,0 @@
# frozen_string_literal: true
module Stripe
class AlipayAccount < APIResource
include Stripe::APIOperations::Save
include Stripe::APIOperations::Delete
OBJECT_NAME = "alipay_account"
def resource_url
if !respond_to?(:customer) || customer.nil?
raise NotImplementedError,
"Alipay accounts cannot be accessed without a customer ID."
end
"#{Customer.resource_url}/#{CGI.escape(customer)}/sources" \
"/#{CGI.escape(id)}"
end
def self.update(_id, _params = nil, _opts = nil)
raise NotImplementedError,
"Alipay accounts cannot be updated without a customer ID. " \
"Update an Alipay account using `Customer.update_source(" \
"'customer_id', 'alipay_account_id', update_params)`"
end
def self.retrieve(_id, _opts = nil)
raise NotImplementedError,
"Alipay accounts cannot be retrieved without a customer ID. " \
"Retrieve an Alipay account using `Customer.retrieve_source(" \
"'customer_id', 'alipay_account_id')`"
end
end
end

View File

@ -1,108 +0,0 @@
# File generated from our OpenAPI spec
# frozen_string_literal: true
module Stripe
# Domains registered for Apple Pay on the Web
class ApplePayDomain < APIResource
extend Stripe::APIOperations::Create
include Stripe::APIOperations::Delete
extend Stripe::APIOperations::List
OBJECT_NAME = "apple_pay_domain"
def self.object_name
"apple_pay_domain"
end
class DeleteParams < Stripe::RequestParams; end
class ListParams < Stripe::RequestParams
# Attribute for param field domain_name
attr_accessor :domain_name
# 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
def initialize(
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
class CreateParams < Stripe::RequestParams
# Attribute for param field domain_name
attr_accessor :domain_name
# Specifies which fields in the response should be expanded.
attr_accessor :expand
def initialize(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.
attr_reader :object
# Always true for a deleted object
attr_reader :deleted
# Create an apple pay domain.
def self.create(params = {}, opts = {})
request_stripe_object(
method: :post,
path: "/v1/apple_pay/domains",
params: params,
opts: opts
)
end
# Delete an apple pay domain.
def self.delete(domain, params = {}, opts = {})
request_stripe_object(
method: :delete,
path: format("/v1/apple_pay/domains/%<domain>s", { domain: CGI.escape(domain) }),
params: params,
opts: opts
)
end
# Delete an apple pay domain.
def delete(params = {}, opts = {})
request_stripe_object(
method: :delete,
path: format("/v1/apple_pay/domains/%<domain>s", { domain: CGI.escape(self["id"]) }),
params: params,
opts: opts
)
end
# List apple pay domains.
def self.list(params = {}, opts = {})
request_stripe_object(method: :get, path: "/v1/apple_pay/domains", params: params, opts: opts)
end
def self.resource_url
"/v1/apple_pay/domains"
end
end
end

View File

@ -1,20 +0,0 @@
# File generated from our OpenAPI spec
# frozen_string_literal: true
module Stripe
class Application < APIResource
OBJECT_NAME = "application"
def self.object_name
"application"
end
# Unique identifier for the object.
attr_reader :id
# The name of the application.
attr_reader :name
# String representing the object's type. Objects of the same type share the same value.
attr_reader :object
# Always true for a deleted object
attr_reader :deleted
end
end

View File

@ -1,108 +0,0 @@
# File generated from our OpenAPI spec
# frozen_string_literal: true
module Stripe
class ApplicationFee < APIResource
extend Stripe::APIOperations::List
extend Stripe::APIOperations::NestedResource
OBJECT_NAME = "application_fee"
def self.object_name
"application_fee"
end
nested_resource_class_methods :refund, operations: %i[create retrieve update list]
class FeeSource < Stripe::StripeObject
# Charge ID that created this application fee.
attr_reader :charge
# Payout ID that created this application fee.
attr_reader :payout
# Type of object that created the application fee.
attr_reader :type
end
class ListParams < Stripe::RequestParams
class Created < 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
def initialize(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
def initialize(
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.
def self.list(params = {}, opts = {})
request_stripe_object(method: :get, path: "/v1/application_fees", params: params, opts: opts)
end
end
end

View File

@ -1,55 +0,0 @@
# File generated from our OpenAPI spec
# frozen_string_literal: true
module Stripe
# `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)
class ApplicationFeeRefund < APIResource
include Stripe::APIOperations::Save
OBJECT_NAME = "fee_refund"
def self.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.
attr_reader :object
def resource_url
"#{ApplicationFee.resource_url}/#{CGI.escape(fee)}/refunds" \
"/#{CGI.escape(id)}"
end
def self.update(_id, _params = nil, _opts = nil)
raise NotImplementedError,
"Application fee refunds cannot be updated without an " \
"application fee ID. Update an application fee refund using " \
"`ApplicationFee.update_refund('fee_id', 'refund_id', " \
"update_params)`"
end
def self.retrieve(_id, _api_key = nil)
raise NotImplementedError,
"Application fee refunds cannot be retrieved without an " \
"application fee ID. Retrieve an application fee refund using " \
"`ApplicationFee.retrieve_refund('fee_id', 'refund_id')`"
end
end
end

View File

@ -1,196 +0,0 @@
# File generated from our OpenAPI spec
# frozen_string_literal: true
module Stripe
module Apps
# 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)
class Secret < APIResource
extend Stripe::APIOperations::Create
extend Stripe::APIOperations::List
OBJECT_NAME = "apps.secret"
def self.object_name
"apps.secret"
end
class Scope < Stripe::StripeObject
# The secret scope type.
attr_reader :type
# The user ID, if type is set to "user"
attr_reader :user
end
class ListParams < Stripe::RequestParams
class Scope < 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
def initialize(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.
attr_accessor :starting_after
def initialize(ending_before: nil, expand: nil, limit: nil, scope: nil, starting_after: nil)
@ending_before = ending_before
@expand = expand
@limit = limit
@scope = scope
@starting_after = starting_after
end
end
class CreateParams < Stripe::RequestParams
class Scope < 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
def initialize(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.
attr_accessor :scope
def initialize(expand: nil, expires_at: nil, name: nil, payload: nil, scope: nil)
@expand = expand
@expires_at = expires_at
@name = name
@payload = payload
@scope = scope
end
end
class FindParams < Stripe::RequestParams
class Scope < 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
def initialize(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
def initialize(expand: nil, name: nil, scope: nil)
@expand = expand
@name = name
@scope = scope
end
end
class DeleteWhereParams < Stripe::RequestParams
class Scope < 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
def initialize(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
def initialize(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.
attr_reader :object
# The plaintext secret value to be stored.
attr_reader :payload
# Attribute for field scope
attr_reader :scope
# Create or replace a secret in the secret store.
def self.create(params = {}, opts = {})
request_stripe_object(method: :post, path: "/v1/apps/secrets", params: params, opts: opts)
end
# Deletes a secret from the secret store by name and scope.
def self.delete_where(params = {}, opts = {})
request_stripe_object(
method: :post,
path: "/v1/apps/secrets/delete",
params: params,
opts: opts
)
end
# Finds a secret in the secret store by name and scope.
def self.find(params = {}, opts = {})
request_stripe_object(
method: :get,
path: "/v1/apps/secrets/find",
params: params,
opts: opts
)
end
# List all secrets stored on the given scope.
def self.list(params = {}, opts = {})
request_stripe_object(method: :get, path: "/v1/apps/secrets", params: params, opts: opts)
end
end
end
end

View File

@ -1,186 +0,0 @@
# File generated from our OpenAPI spec
# frozen_string_literal: true
module Stripe
# 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)
class Balance < SingletonAPIResource
OBJECT_NAME = "balance"
def self.object_name
"balance"
end
class Available < Stripe::StripeObject
class SourceTypes < 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
class ConnectReserved < Stripe::StripeObject
class SourceTypes < 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
class InstantAvailable < Stripe::StripeObject
class NetAvailable < Stripe::StripeObject
class SourceTypes < 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
class SourceTypes < 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
class Issuing < Stripe::StripeObject
class Available < Stripe::StripeObject
class SourceTypes < 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
class Pending < Stripe::StripeObject
class SourceTypes < 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
class RefundAndDisputePrefunding < Stripe::StripeObject
class Available < Stripe::StripeObject
class SourceTypes < 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
class Pending < Stripe::StripeObject
class SourceTypes < 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
attr_reader :refund_and_dispute_prefunding
end
end

Some files were not shown because too many files have changed in this diff Show More