Skip to content
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

Dynamically fetch OAuth URLs when needed #3841

Merged
merged 6 commits into from
Feb 6, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.txt
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
* Fix - Improve the appearance of Stripe elements in checkout pages to match the store theme.
* Fix - Hide ECE button for synced subscription variations.
* Fix - Use the original shipping address for Amazon Pay pay for orders.
* Tweak - Improve settings page load by delaying oauth URL generation.

= 9.1.1 - 2025-01-10 =
* Fix - Fixes the webhook order retrieval by intent charges. The processed event is an object, not an array.
Expand Down
67 changes: 61 additions & 6 deletions client/settings/stripe-auth-account/stripe-auth-actions.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* global wc_stripe_settings_params */
/* global wc_stripe_settings_params, ajaxurl */
import { __ } from '@wordpress/i18n';
import { React } from 'react';
import { Button, ExternalLink } from '@wordpress/components';
import { React, useState, useEffect } from 'react';
import { Button, ExternalLink, Spinner } from '@wordpress/components';
import interpolateComponents from 'interpolate-components';
import ConfigureWebhookButton from './configure-webhook-button';
import InlineNotice from 'wcstripe/components/inline-notice';
Expand All @@ -16,9 +16,64 @@ import InlineNotice from 'wcstripe/components/inline-notice';
* @return {JSX.Element} The rendered StripeAuthActions component.
*/
const StripeAuthActions = ( { testMode, displayWebhookConfigure } ) => {
const oauthUrl = testMode // eslint-disable-next-line camelcase
? wc_stripe_settings_params.stripe_test_oauth_url // eslint-disable-next-line camelcase
: wc_stripe_settings_params.stripe_oauth_url;
const [ oauthUrls, setOauthUrls ] = useState( {
oauth_url: '',
test_oauth_url: '',
} );
const [ isLoading, setIsLoading ] = useState( true );
const [ error, setError ] = useState( null );

useEffect( () => {
const fetchOAuthUrls = async () => {
try {
const response = await jQuery.ajax( {
url: ajaxurl,
method: 'POST',
data: {
action: 'wc_stripe_get_oauth_urls',
nonce: wc_stripe_settings_params.oauth_nonce, // eslint-disable-line camelcase
},
} );

if ( response.success ) {
setOauthUrls( response.data );
} else {
setError(
response.data?.message ||
__(
'Failed to fetch OAuth URLs',
'woocommerce-gateway-stripe'
)
);
}
} catch ( err ) {
setError(
__(
'Failed to fetch OAuth URLs',
'woocommerce-gateway-stripe'
)
);
} finally {
setIsLoading( false );
}
};

fetchOAuthUrls();
}, [] );

if ( isLoading ) {
return <Spinner />;
}

if ( error ) {
return (
<InlineNotice isDismissible={ false } status="error">
{ error }
</InlineNotice>
);
}

const oauthUrl = testMode ? oauthUrls.test_oauth_url : oauthUrls.oauth_url;

return oauthUrl ? (
<div className="woocommerce-stripe-auth__actions">
Expand Down
67 changes: 61 additions & 6 deletions includes/admin/class-wc-stripe-settings-controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ public function __construct( WC_Stripe_Account $account, ?WC_Stripe_Payment_Gate
add_action( 'admin_init', [ $this, 'maybe_update_account_data' ] );

add_action( 'update_option_woocommerce_gateway_order', [ $this, 'set_stripe_gateways_in_list' ] );

// Add AJAX handler for OAuth URLs
add_action( 'wp_ajax_wc_stripe_get_oauth_urls', [ $this, 'ajax_get_oauth_urls' ] );
}

/**
Expand Down Expand Up @@ -115,6 +118,53 @@ public function admin_options( WC_Stripe_Payment_Gateway $gateway ) {
echo $account_data_exists ? '<div id="wc-stripe-account-settings-container"></div>' : '<div id="wc-stripe-new-account-container"></div>';
}

/**
* AJAX handler to get OAuth URLs for the configuration modal
*/
public function ajax_get_oauth_urls() {
// Check nonce and capabilities
if ( ! check_ajax_referer( 'wc_stripe_get_oauth_urls', 'nonce', false ) ||
! current_user_can( 'manage_woocommerce' ) ) {
wp_send_json_error( [ 'message' => __( 'You do not have permission to do this.', 'woocommerce-gateway-stripe' ) ] );
return;
}

$oauth_url = woocommerce_gateway_stripe()->connect->get_oauth_url();
$test_oauth_url = woocommerce_gateway_stripe()->connect->get_oauth_url( '', 'test' );

wp_send_json_success(
[
'oauth_url' => is_wp_error( $oauth_url ) ? '' : $oauth_url,
'test_oauth_url' => is_wp_error( $test_oauth_url ) ? '' : $test_oauth_url,
]
);
}

/**
* Determines if OAuth URLs need to be generated.
* URLs are needed for new accounts or accounts not connected via OAuth.
*
* @return bool True if OAuth URLs are needed
*/
public function needs_oauth_urls() {
$settings = WC_Stripe_Helper::get_stripe_settings();
$has_live_keys = ! empty( $settings['publishable_key'] ) && ! empty( $settings['secret_key'] );
$has_test_keys = ! empty( $settings['test_publishable_key'] ) && ! empty( $settings['test_secret_key'] );

// If no keys at all, we need OAuth URLs for new account setup
if ( ! $has_live_keys && ! $has_test_keys ) {
return true;
}

$stripe_connect = woocommerce_gateway_stripe()->connect;

// Check each mode only if it has keys
$needs_live_oauth = $has_live_keys && ! $stripe_connect->is_connected_via_oauth( 'live' );
$needs_test_oauth = $has_test_keys && ! $stripe_connect->is_connected_via_oauth( 'test' );

return $needs_live_oauth || $needs_test_oauth;
}

/**
* Load admin scripts.
*/
Expand All @@ -139,8 +189,6 @@ public function admin_scripts( $hook_suffix ) {
return;
}

$suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';

// Webpack generates an assets file containing a dependencies array for our built JS file.
$script_asset_path = WC_STRIPE_PLUGIN_PATH . '/build/upe_settings.asset.php';
$script_asset = file_exists( $script_asset_path )
Expand All @@ -164,11 +212,17 @@ public function admin_scripts( $hook_suffix ) {
$script_asset['version']
);

$oauth_url = woocommerce_gateway_stripe()->connect->get_oauth_url();
$oauth_url = is_wp_error( $oauth_url ) ? '' : $oauth_url;
$oauth_url = '';
$test_oauth_url = '';

$test_oauth_url = woocommerce_gateway_stripe()->connect->get_oauth_url( '', 'test' );
$test_oauth_url = is_wp_error( $test_oauth_url ) ? '' : $test_oauth_url;
// Get URLs at page load only if account doesn't exist or if account exists but not connected via OAuth
if ( $this->needs_oauth_urls() ) {
$oauth_url = woocommerce_gateway_stripe()->connect->get_oauth_url();
$oauth_url = is_wp_error( $oauth_url ) ? '' : $oauth_url;

$test_oauth_url = woocommerce_gateway_stripe()->connect->get_oauth_url( '', 'test' );
$test_oauth_url = is_wp_error( $test_oauth_url ) ? '' : $test_oauth_url;
}

$message = sprintf(
/* translators: 1) Html strong opening tag 2) Html strong closing tag */
Expand All @@ -193,6 +247,7 @@ public function admin_scripts( $hook_suffix ) {
'are_apms_deprecated' => WC_Stripe_Feature_Flags::are_apms_deprecated(),
'is_ece_enabled' => WC_Stripe_Feature_Flags::is_stripe_ece_enabled(),
'is_amazon_pay_available' => WC_Stripe_Feature_Flags::is_amazon_pay_available(),
'oauth_nonce' => wp_create_nonce( 'wc_stripe_get_oauth_urls' ),
];
wp_localize_script(
'woocommerce_stripe_admin',
Expand Down
1 change: 1 addition & 0 deletions readme.txt
Original file line number Diff line number Diff line change
Expand Up @@ -148,5 +148,6 @@ If you get stuck, you can ask for help in the [Plugin Forum](https://wordpress.o
* Fix - Improve the appearance of Stripe elements in checkout pages to match the store theme.
* Fix - Hide ECE button for synced subscription variations.
* Fix - Use the original shipping address for Amazon Pay pay for orders.
* Tweak - Improve settings page load by delaying oauth URL generation.

[See changelog for all versions](https://raw.githubusercontent.com/woocommerce/woocommerce-gateway-stripe/trunk/changelog.txt).
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,13 @@ public function test_add_buttons_action_is_called_on_order_admin_page() {
$output = ob_get_clean();
$this->assertStringMatchesFormat( '%aclass="button button-disabled"%a', $output );
}

/**
* Test that needs_oauth_urls returns true for new accounts with no keys
*/
public function test_needs_oauth_urls_new_account() {
WC_Stripe_Helper::delete_main_stripe_settings();

$this->assertTrue( $this->controller->needs_oauth_urls() );
}
}
Loading