-
Notifications
You must be signed in to change notification settings - Fork 216
Enforce plugin rate limit when Stripe returns 429 errors #4327
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
daledupreez
wants to merge
8
commits into
develop
Choose a base branch
from
try/detect-disconnected-stripe-via-401-errors
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 4 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
bc95775
Enforce plugin rate limit when Stripe has rate limited us
daledupreez 67a1581
Keep basic history so we can see if this is recurring on a site
daledupreez ab72abc
Add explicit checks for 4xx and 5xx HTTP responses
daledupreez 06b7e62
Separate rate checks from error handling
daledupreez 88b405a
Merge branch 'develop' into try/detect-disconnected-stripe-via-401-er…
daledupreez 2ec56a2
Changelog
daledupreez 84e5af2
Improve name for duration constant
daledupreez 4e638b8
Use multiline OR for $response checks
daledupreez File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -16,6 +16,28 @@ class WC_Stripe_API { | |
const ENDPOINT = 'https://api.stripe.com/v1/'; | ||
const STRIPE_API_VERSION = '2024-06-20'; | ||
|
||
|
||
/** | ||
* Option key for cases where Stripe rate limits our live API calls. | ||
* | ||
* @var string | ||
*/ | ||
public const LIVE_MODE_STRIPE_API_RATE_LIMIT_OPTION_KEY = 'wc_stripe_live_api_rate_limit'; | ||
|
||
/** | ||
* Option key for cases where Stripe rate limits our test API calls. | ||
* | ||
* @var string | ||
*/ | ||
public const TEST_MODE_STRIPE_API_RATE_LIMIT_OPTION_KEY = 'wc_stripe_test_api_rate_limit'; | ||
|
||
/** | ||
* Duration we will use to disable Stripe API calls if we have been rate limited. | ||
* | ||
* @var int | ||
*/ | ||
public const STRIPE_API_RATE_LIMIT_DURATION = 30; | ||
|
||
/** | ||
* Secret API Key. | ||
* | ||
|
@@ -231,6 +253,10 @@ public static function request( $request, $api = 'charges', $method = 'POST', $w | |
* @param string $api | ||
*/ | ||
public static function retrieve( $api ) { | ||
if ( self::is_stripe_api_rate_limited() ) { | ||
return null; | ||
} | ||
|
||
WC_Stripe_Logger::log( "{$api}" ); | ||
|
||
$response = wp_safe_remote_get( | ||
|
@@ -242,6 +268,8 @@ public static function retrieve( $api ) { | |
] | ||
); | ||
|
||
self::check_stripe_api_error_response( $response ); | ||
|
||
if ( is_wp_error( $response ) || empty( $response['body'] ) ) { | ||
WC_Stripe_Logger::log( 'Error Response: ' . print_r( $response, true ) ); | ||
return new WP_Error( 'stripe_error', __( 'There was a problem connecting to the Stripe API endpoint.', 'woocommerce-gateway-stripe' ) ); | ||
|
@@ -250,6 +278,80 @@ public static function retrieve( $api ) { | |
return json_decode( $response['body'] ); | ||
} | ||
|
||
/** | ||
* Checks if the Stripe API for the current mode (i.e. test or live) is rate limited. | ||
* | ||
* @return bool True if the Stripe API is rate limited, false otherwise. | ||
*/ | ||
public static function is_stripe_api_rate_limited() { | ||
$rate_limit_option_key = WC_Stripe_Mode::is_test() ? self::TEST_MODE_STRIPE_API_RATE_LIMIT_OPTION_KEY : self::LIVE_MODE_STRIPE_API_RATE_LIMIT_OPTION_KEY; | ||
|
||
$rate_limit_expiration = get_option( $rate_limit_option_key ); | ||
if ( ! $rate_limit_expiration ) { | ||
return false; | ||
} | ||
|
||
$now = time(); | ||
if ( $now > $rate_limit_expiration ) { | ||
delete_option( $rate_limit_option_key ); | ||
return false; | ||
} | ||
|
||
return true; | ||
} | ||
|
||
/** | ||
* Helper function to check error responses from Stripe and ensure we prevent unnecessary API calls, | ||
* primarily in cases where we have been rate limited or we don't have valid keys.. | ||
* | ||
* @param array|WP_Error $response The response from the Stripe API. | ||
* @return void | ||
*/ | ||
protected static function check_stripe_api_error_response( $response ) { | ||
// If we don't have an array for $response, return early, as we won't have an HTTP status code. | ||
if ( ! is_array( $response ) ) { | ||
return; | ||
} | ||
|
||
// We specifically want to check $response['response']['code']. If it's not present, return early. | ||
if ( ! isset( $response['response'] ) || ! is_array( $response['response'] ) || ! isset( $response['response']['code'] ) ) { | ||
annemirasol marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return; | ||
} | ||
|
||
$status_code = $response['response']['code']; | ||
|
||
if ( 429 === $status_code ) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Based on https://docs.stripe.com/rate-limits#rate-limited-requests, it is better to check for the header. It is possible that a 429 may not be related to rate-limiting. Both work fine, but checking the header would be more consistent. |
||
// Stripe has rate limited us, so disable API calls for a period of time. | ||
$is_test_mode = WC_Stripe_Mode::is_test(); | ||
|
||
$timestamp = time(); | ||
$rate_limit_option_key = $is_test_mode ? self::TEST_MODE_STRIPE_API_RATE_LIMIT_OPTION_KEY : self::LIVE_MODE_STRIPE_API_RATE_LIMIT_OPTION_KEY; | ||
update_option( $rate_limit_option_key, $timestamp + self::STRIPE_API_RATE_LIMIT_DURATION ); | ||
daledupreez marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
$mode = $is_test_mode ? 'test' : 'LIVE'; | ||
$message = "Stripe {$mode} mode API has been rate limited, disabling API calls for " . self::STRIPE_API_RATE_LIMIT_DURATION . ' seconds.'; | ||
|
||
error_log( 'woocommerce-gateway-stripe: WARNING: ' . $message ); | ||
annemirasol marked this conversation as resolved.
Show resolved
Hide resolved
|
||
WC_Stripe_Logger::error( $message ); | ||
|
||
// Store history of rate limits so we can see how often they're occurring. | ||
$history_option_key = $rate_limit_option_key . '_history'; | ||
$history = get_option( $history_option_key, [] ); | ||
if ( ! is_array( $history ) ) { | ||
$history = []; | ||
} | ||
// Keep a maximum of 20 rate limit history entries. | ||
$history = array_slice( $history, -19 ); | ||
$history[] = [ | ||
'timestamp' => $timestamp, | ||
'datetime' => gmdate( 'Y-m-d H:i:s', $timestamp ) . ' UTC', | ||
'duration' => self::STRIPE_API_RATE_LIMIT_DURATION, | ||
]; | ||
// Note that we set autoload to false - we don't want this option to be autoloaded by default. | ||
update_option( $history_option_key, $history, false ); | ||
} | ||
} | ||
|
||
/** | ||
* Send the request to Stripe's API with level 3 data generated | ||
* from the order. If the request fails due to an error related | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.