JFIF $ d d 7 * Z qn )ZP 0 !1 A "#a$2Qr D8 a Ri [f \m I ykI w0 c u F c Rı?lO7 к _f˓ [C $殷WF< _W ԣ s Kc ëI zyQy /_LK ℂ ;C",p F A : /] =H ~ , l s / 9 ć: [=/#f ; ) x { ٛE Q )~ = 𘙲r*2~ a _V = ' ku m F D } KYYC )( { * g& f `툪 r y ` = ^ c J. I ]( * `wq 1dđ #̩ ͑ 0 ; H ] u 搂 @:~ ו K L N s h } O I R* 8 :2 ! lD JV o ( 3 = M ( z Ȱ+i *N A r6K n S l ) ! J J Ӂ* % ݉?|D } d5: eP0 R; {$X' x F @ .ÊB {,WJ uQ ɲRI ;9 Q E琯 6 2fT .DU J ;*c P A\IL Nj! J ۱+ O\ ͔ ] ޒ S J ȧ c%A N ol ՎprU L Zԛe r E2= X D Xg VQeӓ k y P7 U* o m Q I s ,K `) 6\G3t?pgjr m ۛجw luGt f h 9uyP 0D;Uڽ"OXl i f $ ) &|ML 0 Z rm1 [ H XP l P R0 'G=i 2N +0 e 2 ]] 9 VT P O 7 h(F * 癈 ' = Q VZD F,d ߬ ~ T X G[ `le 69C R(!S2! P < 0 x < !1AQ "Raq 02Br #S CTb ? Ζ "]mH5WR 7 k.ۛ ! } Q~ + yԏ z |@ T20 S~ K e k *zF f^2X *( @ 8 r ? C I uI|֓>^Ex LgNU Y+{.R Ѫ τV YT D I 6 2 '8Y2 7'\T P.6 d &˦ @V q i |8 -O Ε ] ʔ U= T L 8= ;6c | !qfF3 a ů& ~$ l} 'NW U s$U k^S V : U#6w + +s &r+n ڐ { @ 29gL u " T Ù M=6 (^ "7 r}=6Yݾ lC u hquymp Ǧ G jhs ǜNl ɻ} o 7 #S6 a w 4 ! OS r D 5 7 % | ?x> L | / nD 6?/8 w # [ ) L 7 +6〼T A T g ! %5 Mm Z /c -{1_Je "| ^$ 'O & ޱմ < H vNqϡQ$ < 6 &Nݛ ֨tǻN (9 n ru~'όN sMG& ,uH Kw *Ī 5@ u6 BԒ i YN * f 0 _ GhKW u lT <nj- 0{ M L~ | /a v\ E = ?1 \ɟuq Ђ Y O a K ޡP q $ H8o Q˼EV ~ k 0 h' L Pp M -M" m^ !6l nմ 쮝C U T . ! :vMǨb h ډ Vc r @~p # !1QAa q ? AL0L x LU 4 d ; x " 16ad0 7.\ߋ 0 = P l v/ " c A Ay A|2pO8"d MV #1] = \ " ˡ ] k v I9 d ۓ & q ) ǐq E ꞅ v "P )q X &Q З non]я u ג./ ; gZ$ M QР 2M ]h ni 0 P $ێ 3CɏGjώy : m c # S_ l@ '_ \m|C 2`K _ 1 cIvGc $? PCQ S+D ? K aײ k Fr b 8 ύ NEدg ĝ U 3 6 #Ik+ v { v i ( ވ ? a e) X xy/*@Q Ǽ Ծ ) $ IWO l c G; !i k{ gOŀ L ('x T rb $ w) R $ & N1E td U3Uȉ1p M"N* (DNy d96.(jQ) X 5 c QɎMy W ? Q *!R > 6=7)Xj 5`J ] e 8%t ! + ' ! 1Q 5 !1 AQaq ё #2 "0BRb ? G t^ ## .l lQ T $ v , ,m 㵜5u bV =sY+ @d { N ! dn O < .- B; _w J t 6;Q Jd. Q c%p{ 1 ,sND dF H I0 Гo X ш e黅X ۢ F :)[ F G X ƹ / w _c MeD ,ʡc c . W D tA $ j@ : ) - #u c1< @ۗ9F ) KJ- hpP] _ x [ q B lb p ʖ w q " LFGd ƶ * s +ډ_Zc " ? % t[I P 6 J ]# =ɺ V v v CGs Gh1 > )6 |e y ? L ӣ m,4 G W Ui ` ] uJVo VDG< SB 6ϏQ @ TiU l y O U 0 kfV ~ ~}S Z @ *WU Ui ## ; s /[ = ! 7}" W N ] ' (L ! ~ y5 g9T̅J kbM' +s :S +B) v @ M j e C f j E 0 Y\Qn z G 1 д~ W o{T 9?` Rm yhsy3 !HAD ] m c1 ~ 2 L S u7x T ;j$ `} 4-> L# vzŏ I L S ֭ T { r jGK C ; b pU= - ` Bs K. S F w4 M q] Z dH S 0 ) tLg
<?php
namespace WPForms\Integrations\PayPalCommerce\Admin;
use RuntimeException;
use WPForms\Admin\Payments\BuilderReturnNotice;
use WPForms\Helpers\Transient;
use WPForms\Integrations\PayPalCommerce\Api\Api;
use WPForms\Integrations\PayPalCommerce\Api\WebhooksManager;
use WPForms\Integrations\PayPalCommerce\Connection;
use WPForms\Integrations\PayPalCommerce\Helpers;
use WPForms\Integrations\PayPalCommerce\PaymentMethods\ApplePay\DomainManager;
use WPForms\Integrations\PayPalCommerce\PayPalCommerce;
/**
* PayPal Commerce Connect functionality.
*
* @since 1.10.0
*/
class Connect {
/**
* WPForms website URL.
*
* @since 1.10.0
*/
public const WPFORMS_URL = 'https://wpformsapi.com/paypal/v1';
/**
* Disconnect nonce.
*
* @since 1.10.0
*/
public const DISCONNECT_ACTION_NONCE = 'wpforms_paypal_commerce_disconnect';
/**
* Merchant info name.
*
* @since 1.10.0
*/
public const MERCHANT_INFO_TRANSIENT_NAME = 'wpforms_paypal_commerce_merchant_info_';
/**
* Signup transient name.
*
* @since 1.10.0
*/
private const SIGNUP_TRANSIENT_NAME = 'wpforms_paypal_commerce_signup_link_';
/**
* Signup Site URL transient name.
*
* @since 1.10.1
*/
private const SIGNUP_SITE_URL_TRANSIENT_NAME = 'wpforms_paypal_commerce_signup_site_url';
/**
* Lock Signup transient name.
*
* @since 1.10.0
*/
private const LOCK_SIGNUP_TRANSIENT_NAME = 'wpforms_paypal_commerce_lock_signup_link_';
/**
* Lock Connect option name.
*
* @since 1.10.0
*/
private const LOCK_CONNECT_OPTION_NAME = 'wpforms_paypal_commerce_lock_connect_';
/**
* Unlock Connect transient name.
*
* @since 1.10.0
*/
private const UNLOCK_CONNECT_TRANSIENT_NAME = 'wpforms_paypal_commerce_unlock_connect_';
/**
* Secret Signup transient name.
*
* @since 1.10.0
*/
private const SECRET_SIGNUP_TRANSIENT_NAME = 'wpforms_paypal_commerce_secret_signup_link_';
/**
* Refresh the signup key.
*
* @since 1.10.0
*/
private const REFRESH_SIGNUP_KEY = 'paypal_commerce_refresh_signup';
/**
* Init class.
*
* @since 1.10.0
*/
public function init(): Connect {
$this->hooks();
return $this;
}
/**
* Register hooks.
*
* @since 1.10.0
*/
public function hooks(): void {
add_action( 'admin_init', [ $this, 'handle_actions' ] );
add_action( 'admin_init', [ $this, 'maybe_queue_builder_return_notice' ], 20 );
add_action( 'update_option_wpforms_license', [ $this, 'update_license_option' ], 10, 3 );
add_action( 'add_option_wpforms_license', [ $this, 'add_license_option' ], 10, 2 );
}
/**
* Handle actions.
*
* @since 1.10.0
*/
public function handle_actions(): void {
if ( wp_doing_ajax() || ! wpforms_current_user_can() ) {
return;
}
$this->validate_scopes();
if ( ! wpforms_is_admin_page( 'settings', 'payments' ) ) {
return;
}
if (
isset( $_GET['merchantId'], $_GET['merchantIdInPayPal'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
) {
$this->handle_connect();
return;
}
if (
isset( $_GET['_wpnonce'] ) &&
wp_verify_nonce( sanitize_key( $_GET['_wpnonce'] ), self::DISCONNECT_ACTION_NONCE )
) {
$this->handle_disconnect();
}
}
/**
* Update license for the connected customer.
*
* @since 1.10.0
*
* @param mixed $old_value Old license value.
* @param mixed $value New license value.
* @param string $option Option name.
*
* @noinspection PhpUnusedParameterInspection
* @noinspection PhpMissingParamTypeInspection
*/
public function update_license_option( $old_value, $value, $option ): void { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed
$this->update_license( $value['key'] ?? null );
}
/**
* Queue the "Return to your form" success notice after the user completes
* the PayPal Commerce Connect flow that they started from the form builder.
*
* @since 1.10.1.1
*/
public function maybe_queue_builder_return_notice(): void {
BuilderReturnNotice::maybe_queue_oauth( 'paypal_commerce', __( 'PayPal Commerce', 'wpforms-lite' ) );
}
/**
* Update license for the connected customer.
*
* @since 1.10.0
*
* @param string $option Option name.
* @param mixed $value License value.
*
* @noinspection PhpUnusedParameterInspection
* @noinspection PhpMissingParamTypeInspection
*/
public function add_license_option( $option, $value ): void { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed
$this->update_license( $value['key'] ?? null );
}
/**
* Update license for the connected customer.
*
* @since 1.10.0
*
* @param string|null $license License key value.
*/
private function update_license( $license ): void {
$connection = Connection::get();
if ( ! $connection ) {
return;
}
$api = PayPalCommerce::get_api( $connection );
if ( ! $api || ! method_exists( $api, 'update_customer' ) ) {
return;
}
$api->update_customer( [ 'license_key' => $license ] );
}
/**
* Handle connection.
*
* @since 1.10.0
*
* @throws RuntimeException Credentials request was failed.
*/
private function handle_connect(): void {
$mode = Helpers::get_mode();
$settings_page = Helpers::get_settings_page_url();
$return_form_id = isset( $_GET['wpforms_return_form_id'] ) ? absint( $_GET['wpforms_return_form_id'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( $return_form_id > 0 ) {
$settings_page = add_query_arg(
[
'wpforms_connected' => 'paypal_commerce',
'wpforms_return_form_id' => $return_form_id,
],
$settings_page
);
}
// If already processing, let the first request finish.
if ( ! add_option( self::LOCK_CONNECT_OPTION_NAME . $mode, time() ) ) {
$start = microtime( true );
// Wait up to 5 seconds for the first request to completion.
while ( microtime( true ) - $start < 5 ) {
if ( Transient::get( self::UNLOCK_CONNECT_TRANSIENT_NAME . $mode ) ) {
break;
}
usleep( 200000 ); // 200 ms
}
wp_safe_redirect( $settings_page );
exit;
}
try {
$connection_data = $this->get_credentials();
if ( ! $connection_data ) {
throw new RuntimeException( 'Missing or invalid connection credentials.' );
}
$connection = new Connection( $connection_data );
$api = new Api( $connection );
$connection = self::refresh_access_token( $connection, $api );
$merchant_info = $api->get_merchant_info();
$status = $connection->validate_permissions( $merchant_info );
$connection->set_status( $status )->save();
// Sync the settings mode with a connection mode.
Helpers::set_mode( $mode );
( new WebhooksManager() )->connect();
/**
* Fires after successful PayPal Commerce connection.
*
* @since 1.10.0
*
* @param Connection $connection Connection instance.
* @param string $mode Connection mode.
*/
do_action( 'wpforms_integrations_paypal_commerce_admin_connect_after_handle', $connection, $mode ); // phpcs:ignore WPForms.PHP.ValidateHooks.InvalidHookName
// Clear the transients.
Transient::delete( self::SECRET_SIGNUP_TRANSIENT_NAME . $mode );
Transient::delete( self::LOCK_SIGNUP_TRANSIENT_NAME . $mode );
Transient::delete( self::SIGNUP_TRANSIENT_NAME . $mode );
} catch ( \Exception $e ) {
Helpers::log_errors(
'PayPal Connect error.',
'',
$e->getMessage()
);
} finally {
delete_option( self::LOCK_CONNECT_OPTION_NAME . $mode );
Transient::set( self::UNLOCK_CONNECT_TRANSIENT_NAME . $mode, 1, 10 );
wp_safe_redirect( $settings_page );
exit;
}
}
/**
* Get credentials.
*
* @since 1.10.0
*
* @return array
*/
private function get_credentials(): array {
$mode = Helpers::get_mode();
$merchant_id = sanitize_text_field( wp_unslash( $_GET['merchantIdInPayPal'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotValidated
$secret = sanitize_text_field( wp_unslash( $_GET['merchantId'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotValidated
$referral_link = Transient::get( self::SIGNUP_TRANSIENT_NAME . $mode );
$referral_params = [];
if ( $secret !== Transient::get( self::SECRET_SIGNUP_TRANSIENT_NAME . $mode ) ) {
Helpers::log_errors(
'PayPal Secret mismatch detected.',
'',
$referral_link
);
return [];
}
if ( $referral_link ) {
$referral_query = wp_parse_url( $referral_link, PHP_URL_QUERY );
parse_str( $referral_query, $referral_params );
}
$credentials_response = wp_remote_post(
self::get_server_url() . '/oauth/credentials',
[
'body' => [
'secret' => $secret,
'merchant_id' => $merchant_id,
'referral_token' => $referral_params['referralToken'] ?? '',
'license_key' => wpforms_get_license_key(),
'webhooks_url' => Helpers::get_webhook_url(),
'site_url' => site_url(),
'live_mode' => (int) ( $mode === Helpers::PRODUCTION ),
],
'timeout' => 15,
]
);
if ( is_wp_error( $credentials_response ) ) {
Helpers::log_errors(
'PayPal Credentials Error.',
'',
$credentials_response
);
return [];
}
$body = wp_remote_retrieve_body( $credentials_response );
$connection_data = json_decode( $body, true );
$required_keys = [ 'partner_merchant_id', 'client_id', 'client_token', 'client_token_expires_in', 'sdk_client_token', 'sdk_client_token_expires_in' ];
if ( empty( $connection_data ) || count( array_diff( $required_keys, array_keys( $connection_data ) ) ) !== 0 ) {
Helpers::log_errors(
'PayPal Connection data missed required keys.',
'',
$connection_data
);
return [];
}
$connection_data['merchant_id'] = $merchant_id;
$connection_data['secret'] = $secret;
$connection_data['type'] = Connection::TYPE_THIRD_PARTY;
return $connection_data;
}
/**
* Handle disconnection.
*
* @since 1.10.0
*/
private function handle_disconnect(): void {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$live_mode = isset( $_GET['live_mode'] ) ? absint( $_GET['live_mode'] ) : 0;
$mode = $live_mode ? Helpers::PRODUCTION : Helpers::SANDBOX;
$connection = Connection::get( $mode );
if ( ! $connection ) {
return;
}
if ( ! Helpers::is_legacy() ) {
if ( Helpers::is_webhook_enabled() ) {
// Disconnect webhooks.
PayPalCommerce::get_webhooks_manager()->disconnect_webhook();
}
$api = PayPalCommerce::get_api( $connection );
// Ensure we have a fresh access token before any API calls.
self::refresh_access_token( $connection, $api );
/**
* Fires before PayPal Commerce disconnection.
*
* @since 1.10.0
*
* @param Connection $connection Connection instance.
* @param string $mode Connection mode.
*/
do_action( 'wpforms_integrations_paypal_commerce_admin_disconnect_before_handle', $connection, $mode ); // phpcs:ignore WPForms.PHP.ValidateHooks.InvalidHookName
$disconnected = $api->disconnect();
if ( ! $disconnected ) {
Helpers::log_errors(
'PayPal Disconnect failed.',
'',
'Unauthorized or other API failure.'
);
wp_safe_redirect( add_query_arg( 'paypal_commerce_disconnect', 'failed', Helpers::get_settings_page_url() ) );
exit;
}
}
$connection->delete();
Transient::delete( self::SECRET_SIGNUP_TRANSIENT_NAME . $mode );
Transient::delete( self::LOCK_SIGNUP_TRANSIENT_NAME . $mode );
Transient::delete( self::SIGNUP_TRANSIENT_NAME . $mode );
Transient::delete( self::MERCHANT_INFO_TRANSIENT_NAME . $mode );
Transient::delete( DomainManager::DOMAIN_REGISTERED_TRANSIENT_NAME . $mode );
wp_safe_redirect( Helpers::get_settings_page_url() );
exit;
}
/**
* Refresh access token.
*
* @since 1.10.0
*
* @param Connection|\WPFormsPaypalCommerce\Connection $connection Current Connection.
* @param Api|\WPFormsPaypalCommerce\Api\Api $api Current API.
*
* @return Connection|\WPFormsPaypalCommerce\Connection
*/
public static function refresh_access_token( $connection, $api = null ) {
if ( is_null( $api ) ) {
$api = PayPalCommerce::get_api( $connection );
}
if ( is_null( $api ) ) {
return $connection;
}
$access_token = $api->generate_access_token();
if ( ! empty( $access_token['access_token'] ) ) {
$connection->set_access_token( $access_token['access_token'] )->set_access_token_expires_in( time() + $access_token['expires_in'] )->save();
}
return $connection;
}
/**
* Refresh client token.
*
* @since 1.10.0
*
* @param Connection|\WPFormsPaypalCommerce\Connection $connection Current Connection.
*
* @return Connection|\WPFormsPaypalCommerce\Connection
*/
public static function refresh_client_token( $connection ) {
$api = PayPalCommerce::get_api( $connection );
if ( is_null( $api ) ) {
return $connection;
}
$client_token = $api->generate_client_token();
if ( ! empty( $client_token['client_token'] ) ) {
$connection->set_client_token( $client_token['client_token'] )->set_client_token_expires_in( time() + $client_token['expires_in'] )->save();
}
return $connection;
}
/**
* Refresh client token.
*
* @since 1.10.0
*
* @param Connection|\WPFormsPaypalCommerce\Connection $connection Current Connection.
*
* @return Connection|\WPFormsPaypalCommerce\Connection
*/
public static function refresh_sdk_client_token( $connection ) {
$api = PayPalCommerce::get_api( $connection );
if ( is_null( $api ) ) {
return $connection;
}
$sdk_client_token = $api->generate_sdk_client_token();
if ( ! empty( $sdk_client_token['sdk_client_token'] ) ) {
$connection->set_sdk_client_token( $sdk_client_token['sdk_client_token'] )->set_sdk_client_token_expires_in( time() + $sdk_client_token['expires_in'] )->save();
}
return $connection;
}
/**
* Get Connect URL.
*
* @since 1.10.0
* @since 1.10.1.1 Added `$site_url` parameter to override the default
* post-OAuth callback URL.
*
* @param string $mode Connection mode.
* @param string $site_url Optional. Absolute URL that PayPal will redirect
* to after onboarding. Must point at a page where
* the OAuth handshake handler is registered (the
* Payments settings page). Defaults to the current
* admin URL for backwards compatibility.
*
* @return string
*/
public function get_connect_url( string $mode, string $site_url = '' ): string {
$mode = Helpers::validate_mode( $mode );
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( isset( $_GET[ self::REFRESH_SIGNUP_KEY ] ) ) {
Transient::delete( self::LOCK_SIGNUP_TRANSIENT_NAME . $mode );
Transient::delete( self::SIGNUP_TRANSIENT_NAME . $mode );
}
if ( Transient::get( self::LOCK_SIGNUP_TRANSIENT_NAME . $mode ) ) {
return '';
}
$link = Transient::get( self::SIGNUP_TRANSIENT_NAME . $mode );
$site_url = $site_url !== '' ? $site_url : remove_query_arg( self::REFRESH_SIGNUP_KEY, wpforms_current_url() );
if ( ! empty( $link ) && $site_url === Transient::get( self::SIGNUP_SITE_URL_TRANSIENT_NAME ) ) {
return (string) $link;
}
$secret = Transient::get( self::SECRET_SIGNUP_TRANSIENT_NAME . $mode );
if ( empty( $secret ) ) {
$secret = bin2hex( random_bytes( 16 ) );
Transient::set( self::SECRET_SIGNUP_TRANSIENT_NAME . $mode, $secret );
}
$response = wp_remote_post(
self::get_server_url() . '/oauth/partner-referral',
[
'body' => [
'secret' => $secret,
'site_url' => $site_url,
'live_mode' => (int) ( $mode === Helpers::PRODUCTION ),
],
'timeout' => 15,
]
);
if ( ! is_wp_error( $response ) && wp_remote_retrieve_response_code( $response ) === 200 ) {
$body = json_decode( wp_remote_retrieve_body( $response ), true );
$link = isset( $body['url'] ) ? $body['url'] . '&displayMode=minibrowser' : '';
if ( $link ) {
Transient::set( self::SIGNUP_TRANSIENT_NAME . $mode, $link, $body['expires_in'] );
Transient::set( self::SIGNUP_SITE_URL_TRANSIENT_NAME, $site_url );
return $link;
}
}
Transient::set( self::LOCK_SIGNUP_TRANSIENT_NAME . $mode, true, HOUR_IN_SECONDS );
return '';
}
/**
* Validate connection scopes.
*
* @since 1.10.0
*/
private function validate_scopes(): void {
$connection = Connection::get();
if ( ! $connection || ! $connection->is_configured() || ! Helpers::is_legacy() ) {
return;
}
$status = Helpers::is_license_ok() && Helpers::is_addon_active() ? 'valid' : 'invalid';
$connection->update_connection_status( $status );
}
/**
* Retrieve connect server URL.
*
* @since 1.10.0
*
* @return string
*/
public static function get_server_url(): string {
// Use a local server if constant set.
if ( defined( 'WPFORMS_PAYPAL_COMMERCE_LOCAL_CONNECT_SERVER' ) && WPFORMS_PAYPAL_COMMERCE_LOCAL_CONNECT_SERVER ) {
return home_url();
}
// Use a custom server if constant set.
if ( defined( 'WPFORMS_PAYPAL_COMMERCE_CONNECT_SERVER' ) && WPFORMS_PAYPAL_COMMERCE_CONNECT_SERVER ) {
return WPFORMS_PAYPAL_COMMERCE_CONNECT_SERVER;
}
/**
* Filter connect server URL.
*
* @since 1.10.0
*
* @param string $server_url Server URL.
*/
return (string) apply_filters( 'wpforms_paypal_commerce_connect_server_url', self::WPFORMS_URL ); // phpcs:ignore WPForms.PHP.ValidateHooks.InvalidHookName
}
}