Skip to content
  •  
  •  
  •  
2 changes: 1 addition & 1 deletion .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ extend-select =
per-file-ignores =
*/__init__.py: IMP100, E402, F401, E501
# we test various import patterns
tests/test_exports.py: IMP100, IMP101, IMP102
tests/test_exports.py: IMP100, IMP101, IMP102, F401
tests/*: IMP101, IMP102, BAN100, ASY100, E501
# backcompat with outdated import patterns
stripe/api_resources/*: IMP100, E402, F401
Expand Down
2 changes: 1 addition & 1 deletion OPENAPI_VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
2c5c64cd284682e65b0d792ea01971f01486ee74
2c5c64cd284682e65b0d792ea01971f01486ee74
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,10 +114,10 @@ You can configure your `StripeClient` to use `urlfetch`, `requests`, `pycurl`, o
`urllib` with the `http_client` option:

```python
client = StripeClient("sk_test_...", http_client=stripe.http_client.UrlFetchClient())
client = StripeClient("sk_test_...", http_client=stripe.http_client.RequestsClient())
client = StripeClient("sk_test_...", http_client=stripe.http_client.PycurlClient())
client = StripeClient("sk_test_...", http_client=stripe.http_client.UrllibClient())
client = StripeClient("sk_test_...", http_client=stripe.UrlFetchClient())
client = StripeClient("sk_test_...", http_client=stripe.RequestsClient())
client = StripeClient("sk_test_...", http_client=stripe.PycurlClient())
client = StripeClient("sk_test_...", http_client=stripe.UrllibClient())
```

Without a configured client, by default the library will attempt to load
Expand Down
17 changes: 0 additions & 17 deletions examples/charge.py

This file was deleted.

8 changes: 8 additions & 0 deletions examples/event_notification_webhook_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@

import os
from stripe import StripeClient
from stripe import Event
from stripe.v2.core import Event as V2Event, EventNotification
from stripe.events import (
V2CoreEventDestinationPingEventNotification,
V1BillingMeterErrorReportTriggeredEvent,
UnknownEventNotification,
ALL_EVENT_NOTIFICATIONS,
)

from flask import Flask, request, jsonify

Expand Down
22 changes: 14 additions & 8 deletions examples/oauth.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import os

import stripe
from stripe import StripeClient
from stripe.oauth_error import OAuthError

from flask import Flask, request, redirect


stripe.api_key = os.environ.get("STRIPE_SECRET_KEY")
stripe.client_id = os.environ.get("STRIPE_CLIENT_ID")
client = StripeClient(
api_key=os.environ["STRIPE_SECRET_KEY"],
client_id=os.environ.get("STRIPE_CLIENT_ID"),
)

app = Flask(__name__)

Expand All @@ -17,16 +21,18 @@ def index():

@app.route("/authorize")
def authorize():
url = stripe.OAuth.authorize_url(scope="read_only")
url = client.oauth.authorize_url(scope="read_only")
return redirect(url)


@app.route("/oauth/callback")
def callback():
code = request.args.get("code")
try:
resp = stripe.OAuth.token(grant_type="authorization_code", code=code)
except stripe.oauth_error.OAuthError as e:
resp = client.oauth.token(
params={"grant_type": "authorization_code", "code": code}
)
except OAuthError as e:
return "Error: " + str(e)

return """
Expand All @@ -40,8 +46,8 @@ def callback():
def deauthorize():
stripe_user_id = request.args.get("stripe_user_id")
try:
stripe.OAuth.deauthorize(stripe_user_id=stripe_user_id)
except stripe.oauth_error.OAuthError as e:
client.oauth.deauthorize(params={"stripe_user_id": stripe_user_id})
except OAuthError as e:
return "Error: " + str(e)

return """
Expand Down
50 changes: 27 additions & 23 deletions examples/proxy.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,39 @@
import os

import stripe


stripe.api_key = os.environ.get("STRIPE_SECRET_KEY")
from stripe import (
StripeClient,
RequestsClient,
HTTPClient,
UrllibClient,
verify_ssl_certs,
PycurlClient,
)

print("Attempting charge...")

proxy = {
proxy: HTTPClient._Proxy = {
"http": "http://<user>:<pass>@<proxy>:<port>",
"https": "http://<user>:<pass>@<proxy>:<port>",
}

clients = (
stripe.http_client.RequestsClient(
verify_ssl_certs=stripe.verify_ssl_certs, proxy=proxy
),
stripe.http_client.PycurlClient(
verify_ssl_certs=stripe.verify_ssl_certs, proxy=proxy
),
stripe.http_client.UrllibClient(
verify_ssl_certs=stripe.verify_ssl_certs, proxy=proxy
),
http_clients = (
RequestsClient(verify_ssl_certs=verify_ssl_certs, proxy=proxy),
PycurlClient(verify_ssl_certs=verify_ssl_certs, proxy=proxy),
UrllibClient(verify_ssl_certs=verify_ssl_certs, proxy=proxy),
)

for c in clients:
stripe.default_http_client = c
resp = stripe.Charge.create(
amount=200,
currency="usd",
card="tok_visa",
description="customer@gmail.com",
for http_client in http_clients:
client_with_proxy = StripeClient(
api_key=os.environ["STRIPE_SECRET_KEY"],
http_client=http_client,
)
print("Success: %s, %r" % (c.name, resp))

resp = client_with_proxy.v1.charges.create(
params={
"amount": 200,
"currency": "usd",
"description": "customer@example.com",
}
)

print("Success: %s, %r" % (http_client.name, resp))
15 changes: 9 additions & 6 deletions examples/webhooks.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import os

import stripe
from stripe import StripeClient, Webhook, SignatureVerificationError

from flask import Flask, request


stripe.api_key = os.environ.get("STRIPE_SECRET_KEY")
client = StripeClient(
api_key=os.environ["STRIPE_SECRET_KEY"],
client_id=os.environ.get("STRIPE_CLIENT_ID"),
)

webhook_secret = os.environ.get("WEBHOOK_SECRET")

app = Flask(__name__)
Expand All @@ -16,13 +21,11 @@ def webhooks():
received_sig = request.headers.get("Stripe-Signature", None)

try:
event = stripe.Webhook.construct_event(
payload, received_sig, webhook_secret
)
event = Webhook.construct_event(payload, received_sig, webhook_secret)
except ValueError:
print("Error while decoding event!")
return "Bad payload", 400
except stripe.error.SignatureVerificationError:
except SignatureVerificationError:
print("Invalid signature!")
return "Bad signature", 400

Expand Down
68 changes: 13 additions & 55 deletions stripe/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,7 @@
from stripe._api_version import _ApiVersion
from stripe._api_requestor import _APIRequestor

# We must import the app_info module early to populate it into
# `sys.modules`; otherwise doing `import stripe.app_info` will end up
# importing that module, and not the global `AppInfo` name from below.
import stripe.app_info

from stripe._app_info import AppInfo as AppInfo
from stripe._version import VERSION as VERSION

Expand Down Expand Up @@ -126,6 +123,7 @@ def add_beta_version(
beta_name: str,
beta_version: str,
):
global api_version
# Validate beta_version format
if not beta_version.startswith("v") or not beta_version[1:].isdigit():
raise ValueError(
Expand All @@ -134,24 +132,22 @@ def add_beta_version(

# Check if beta_name already exists
beta_entry = f"; {beta_name}="
if beta_entry in stripe.api_version:
start_index = stripe.api_version.index(beta_entry) + len(beta_entry)
end_index = stripe.api_version.find(";", start_index)
end_index = end_index if end_index != -1 else len(stripe.api_version)
existing_version = int(
stripe.api_version[(start_index + 1) : end_index]
)
if beta_entry in api_version:
start_index = api_version.index(beta_entry) + len(beta_entry)
end_index = api_version.find(";", start_index)
end_index = end_index if end_index != -1 else len(api_version)
existing_version = int(api_version[(start_index + 1) : end_index])
new_version = int(beta_version[1:])
if new_version <= existing_version:
return # Keep the higher version, no update needed
# Remove the existing beta entry
stripe.api_version = (
stripe.api_version[: stripe.api_version.index(beta_entry)]
+ stripe.api_version[end_index:]
api_version = (
api_version[: api_version.index(beta_entry)]
+ api_version[end_index:]
)

# Add the new beta version
stripe.api_version = f"{stripe.api_version}; {beta_name}={beta_version}"
api_version = f"{api_version}; {beta_name}={beta_version}"


# Infrastructure types
Expand Down Expand Up @@ -235,52 +231,13 @@ def add_beta_version(
UrlFetchClient as UrlFetchClient,
HTTPXClient as HTTPXClient,
AIOHTTPClient as AIOHTTPClient,
UrllibClient as UrllibClient,
new_default_http_client as new_default_http_client,
)

# Util
from stripe._util import convert_to_stripe_object as convert_to_stripe_object

# Backwards compatibility re-exports
if not TYPE_CHECKING:
from stripe import _stripe_response as stripe_response
from stripe import _stripe_object as stripe_object
from stripe import _error_object as error_object
from stripe import _error as error
from stripe import _http_client as http_client
from stripe import _util as util
from stripe import _oauth as oauth
from stripe import _webhook as webhook
from stripe import _multipart_data_generator as multipart_data_generator
from stripe import _request_metrics as request_metrics
from stripe._file import File as FileUpload

# Python 3.7+ supports module level __getattr__ that allows us to lazy load deprecated modules
# this matters because if we pre-load all modules from api_resources while suppressing warning
# users will never see those warnings
if _sys.version_info[:2] >= (3, 7):

def __getattr__(name):
if name == "abstract":
import stripe.api_resources.abstract as _abstract

return _abstract
if name == "api_resources":
import stripe.api_resources as _api_resources

return _api_resources
raise AttributeError(
f"module {__name__!r} has no attribute {name!r}"
)

else:
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=DeprecationWarning)

import stripe.api_resources.abstract as abstract
import stripe.api_resources as api_resources


# API resources

# The beginning of the section generated from our OpenAPI spec
Expand All @@ -297,6 +254,7 @@ def __getattr__(name):
forwarding as forwarding,
identity as identity,
issuing as issuing,
params as params,
privacy as privacy,
radar as radar,
reporting as reporting,
Expand Down
Loading