Completed
Branch master (24c3eb)
by
unknown
34:49 queued 28:57
created
PaymentMethods/PayPalCommerce/domain/Domain.php 1 patch
Indentation   +177 added lines, -177 removed lines patch added patch discarded remove patch
@@ -17,181 +17,181 @@
 block discarded – undo
17 17
  */
18 18
 class Domain
19 19
 {
20
-    /**
21
-     * Name of the extra meta key that stores this PM options as one meta.
22
-     */
23
-    public const META_KEY_PAYPAL_DATA = 'paypal_data';
24
-    /**
25
-     * Name of the extra meta key that stores this PM options as one meta.
26
-     */
27
-    public const META_KEY_PAYPAL_DATA_SANDBOX = 'paypal_data_sandbox';
28
-
29
-    /**
30
-     * Name of the extra meta that stores whether the credentials were for the sandbox or live mode.
31
-     */
32
-    public const META_KEY_SANDBOX_MODE = 'sandbox_mode';
33
-
34
-    /**
35
-     * Name of the extra meta that stores the Access Token that is used to auth in API requests to PayPal.
36
-     */
37
-    public const META_KEY_ACCESS_TOKEN = 'access_token';
38
-
39
-    /**
40
-     * Name of the extra meta that stores the last request tracking ID.
41
-     */
42
-    public const META_KEY_TRACKING_ID = 'tracking_id';
43
-
44
-    /**
45
-     * Name of the extra meta that stores the Event Espresso PayPal Account's merchant id.
46
-     */
47
-    public const META_KEY_APP_ID = 'app_id';
48
-
49
-    /**
50
-     * Name of the extra meta that holds the seller client ID.
51
-     */
52
-    public const META_KEY_CLIENT_ID = 'client_id';
53
-
54
-    /**
55
-     * Name of the extra meta that holds the seller secret.
56
-     */
57
-    public const META_KEY_CLIENT_SECRET = 'client_secret';
58
-
59
-    /**
60
-     * Name of the extra meta that stores the expiration date of the Access Token.
61
-     */
62
-    public const META_KEY_TOKEN_EXPIRES_IN = 'expires_in';
63
-
64
-    /**
65
-     * Name of the extra meta that holds the partner client ID.
66
-     */
67
-    public const META_KEY_PARTNER_CLIENT_ID = 'partner_client_id';
68
-
69
-    /**
70
-     * Name of the extra meta that holds the partner merchant ID.
71
-     */
72
-    public const META_KEY_PARTNER_MERCHANT_ID = 'partner_merchant_id';
73
-
74
-    /**
75
-     * Name of the extra meta that holds the seller merchant ID.
76
-     */
77
-    public const META_KEY_SELLER_MERCHANT_ID = 'merchantIdInPayPal';
78
-
79
-    /**
80
-     * Name of the extra meta that holds the BN / request tracking code.
81
-     */
82
-    public const META_KEY_BN_CODE = 'bn_code';
83
-
84
-    /**
85
-     * Name of the extra meta that holds the last order details.
86
-     */
87
-    public const META_KEY_LAST_ORDER = 'last_order_details';
88
-
89
-    /**
90
-     * Name of the extra meta that holds the list of in progress orders.
91
-     */
92
-    public const META_KEY_PAYPAL_ORDERS = 'paypal_orders_list';
93
-
94
-    /**
95
-     * Name of the extra meta that stores the allowed PP checkout type selected by merchant while onboarding.
96
-     */
97
-    public const META_KEY_ALLOWED_CHECKOUT_TYPE = 'allowed_checkout_type';
98
-
99
-    /**
100
-     * Name of the extra meta that stores the merchant authorized scopes for our app to work within.
101
-     */
102
-    public const META_KEY_AUTHORIZED_SCOPES = 'authorized_scopes';
103
-
104
-    /**
105
-     * Name of the extra meta that stores the PP checkout type selected by merchant after onboarding.
106
-     */
107
-    public const META_KEY_CHECKOUT_TYPE = 'checkout_type';
108
-
109
-    /**
110
-     * Name of the extra meta that stores the selected PP function options.
111
-     */
112
-    public const META_KEY_FUNDING_OPTIONS = 'funding_options';
113
-
114
-    /**
115
-     * Name of the PayPal API parameter that holds the auth code.
116
-     */
117
-    public const API_KEY_AUTH_CODE = 'authCode';
118
-
119
-    /**
120
-     * Name of the PayPal API parameter that holds the client token.
121
-     */
122
-    public const API_KEY_CLIENT_TOKEN = 'client_token';
123
-
124
-     /**
125
-     * Name of the extra meta that holds the seller payer ID.
126
-     */
127
-    public const META_KEY_PAYER_ID = 'payer_id';
128
-
129
-    /**
130
-     * Name of the PayPal API parameter that holds the client token expiration time.
131
-     */
132
-    public const API_KEY_EXPIRES_IN = 'expires_in';
133
-
134
-    /**
135
-     * Name of the PayPal API parameter that holds the list of oAuth integrations related to the merchant.
136
-     */
137
-    public const API_PARAM_OAUTH_INTEGRATIONS = 'oauth_integrations';
138
-
139
-    /**
140
-     * Name of the PayPal API parameter that holds the list of third party permissions that were granted.
141
-     */
142
-    public const API_PARAM_PERMISSIONS_GRANTED = 'oauth_third_party';
143
-
144
-    /**
145
-     * Name of the PayPal API parameter that holds the bool of if the primary email was confirmed.
146
-     */
147
-    public const API_PARAM_PRIM_EMAIL_CONFIRMED = 'primary_email_confirmed';
148
-
149
-    /**
150
-     * Name of the PayPal API parameter that holds the bool of if email was confirmed.
151
-     */
152
-    public const API_PARAM_EMAIL_CONFIRMED = 'isEmailConfirmed';
153
-
154
-    /**
155
-     * Name of the PayPal API parameter that holds the partner ID.
156
-     */
157
-    public const API_PARAM_PARTNER_ID = 'merchantId';
158
-
159
-    /**
160
-     * Name of the PayPal API parameter that holds the merchant ID in the Track seller onboarding status request.
161
-     */
162
-    public const API_PARAM_TRACK_MERCHANT_ID = 'merchant_id';
163
-
164
-    /**
165
-     * Name of the PayPal API parameter that holds the payments_receivable status.
166
-     */
167
-    public const API_PARAM_PAYMENTS_RECEIVABLE = 'payments_receivable';
168
-
169
-    /**
170
-     * Name of the nonce used in the capture order request.
171
-     */
172
-    public const CAPTURE_ORDER_NONCE_NAME = 'eea_pp_commerce_capture_order_payment';
173
-
174
-    /**
175
-     * Name of the nonce used in the onboarding process.
176
-     */
177
-    public const NONCE_NAME_ONBOARDING_RETURN = 'eea_pp_commerce_onboarding_return';
178
-
179
-    /**
180
-     * Holds this payment method slug.
181
-     */
182
-    public const PM_SLUG = 'paypalcheckout';
183
-
184
-
185
-    /**
186
-     * Returns the base PayPal API URL.
187
-     *
188
-     * @param EE_Payment_Method $payment_method
189
-     * @return string
190
-     * @throws EE_Error
191
-     * @throws ReflectionException
192
-     */
193
-    public static function getPayPalApiUrl(EE_Payment_Method $payment_method): string
194
-    {
195
-        return $payment_method->debug_mode() ? 'https://api-m.sandbox.paypal.com' : 'https://api-m.paypal.com';
196
-    }
20
+	/**
21
+	 * Name of the extra meta key that stores this PM options as one meta.
22
+	 */
23
+	public const META_KEY_PAYPAL_DATA = 'paypal_data';
24
+	/**
25
+	 * Name of the extra meta key that stores this PM options as one meta.
26
+	 */
27
+	public const META_KEY_PAYPAL_DATA_SANDBOX = 'paypal_data_sandbox';
28
+
29
+	/**
30
+	 * Name of the extra meta that stores whether the credentials were for the sandbox or live mode.
31
+	 */
32
+	public const META_KEY_SANDBOX_MODE = 'sandbox_mode';
33
+
34
+	/**
35
+	 * Name of the extra meta that stores the Access Token that is used to auth in API requests to PayPal.
36
+	 */
37
+	public const META_KEY_ACCESS_TOKEN = 'access_token';
38
+
39
+	/**
40
+	 * Name of the extra meta that stores the last request tracking ID.
41
+	 */
42
+	public const META_KEY_TRACKING_ID = 'tracking_id';
43
+
44
+	/**
45
+	 * Name of the extra meta that stores the Event Espresso PayPal Account's merchant id.
46
+	 */
47
+	public const META_KEY_APP_ID = 'app_id';
48
+
49
+	/**
50
+	 * Name of the extra meta that holds the seller client ID.
51
+	 */
52
+	public const META_KEY_CLIENT_ID = 'client_id';
53
+
54
+	/**
55
+	 * Name of the extra meta that holds the seller secret.
56
+	 */
57
+	public const META_KEY_CLIENT_SECRET = 'client_secret';
58
+
59
+	/**
60
+	 * Name of the extra meta that stores the expiration date of the Access Token.
61
+	 */
62
+	public const META_KEY_TOKEN_EXPIRES_IN = 'expires_in';
63
+
64
+	/**
65
+	 * Name of the extra meta that holds the partner client ID.
66
+	 */
67
+	public const META_KEY_PARTNER_CLIENT_ID = 'partner_client_id';
68
+
69
+	/**
70
+	 * Name of the extra meta that holds the partner merchant ID.
71
+	 */
72
+	public const META_KEY_PARTNER_MERCHANT_ID = 'partner_merchant_id';
73
+
74
+	/**
75
+	 * Name of the extra meta that holds the seller merchant ID.
76
+	 */
77
+	public const META_KEY_SELLER_MERCHANT_ID = 'merchantIdInPayPal';
78
+
79
+	/**
80
+	 * Name of the extra meta that holds the BN / request tracking code.
81
+	 */
82
+	public const META_KEY_BN_CODE = 'bn_code';
83
+
84
+	/**
85
+	 * Name of the extra meta that holds the last order details.
86
+	 */
87
+	public const META_KEY_LAST_ORDER = 'last_order_details';
88
+
89
+	/**
90
+	 * Name of the extra meta that holds the list of in progress orders.
91
+	 */
92
+	public const META_KEY_PAYPAL_ORDERS = 'paypal_orders_list';
93
+
94
+	/**
95
+	 * Name of the extra meta that stores the allowed PP checkout type selected by merchant while onboarding.
96
+	 */
97
+	public const META_KEY_ALLOWED_CHECKOUT_TYPE = 'allowed_checkout_type';
98
+
99
+	/**
100
+	 * Name of the extra meta that stores the merchant authorized scopes for our app to work within.
101
+	 */
102
+	public const META_KEY_AUTHORIZED_SCOPES = 'authorized_scopes';
103
+
104
+	/**
105
+	 * Name of the extra meta that stores the PP checkout type selected by merchant after onboarding.
106
+	 */
107
+	public const META_KEY_CHECKOUT_TYPE = 'checkout_type';
108
+
109
+	/**
110
+	 * Name of the extra meta that stores the selected PP function options.
111
+	 */
112
+	public const META_KEY_FUNDING_OPTIONS = 'funding_options';
113
+
114
+	/**
115
+	 * Name of the PayPal API parameter that holds the auth code.
116
+	 */
117
+	public const API_KEY_AUTH_CODE = 'authCode';
118
+
119
+	/**
120
+	 * Name of the PayPal API parameter that holds the client token.
121
+	 */
122
+	public const API_KEY_CLIENT_TOKEN = 'client_token';
123
+
124
+	 /**
125
+	  * Name of the extra meta that holds the seller payer ID.
126
+	  */
127
+	public const META_KEY_PAYER_ID = 'payer_id';
128
+
129
+	/**
130
+	 * Name of the PayPal API parameter that holds the client token expiration time.
131
+	 */
132
+	public const API_KEY_EXPIRES_IN = 'expires_in';
133
+
134
+	/**
135
+	 * Name of the PayPal API parameter that holds the list of oAuth integrations related to the merchant.
136
+	 */
137
+	public const API_PARAM_OAUTH_INTEGRATIONS = 'oauth_integrations';
138
+
139
+	/**
140
+	 * Name of the PayPal API parameter that holds the list of third party permissions that were granted.
141
+	 */
142
+	public const API_PARAM_PERMISSIONS_GRANTED = 'oauth_third_party';
143
+
144
+	/**
145
+	 * Name of the PayPal API parameter that holds the bool of if the primary email was confirmed.
146
+	 */
147
+	public const API_PARAM_PRIM_EMAIL_CONFIRMED = 'primary_email_confirmed';
148
+
149
+	/**
150
+	 * Name of the PayPal API parameter that holds the bool of if email was confirmed.
151
+	 */
152
+	public const API_PARAM_EMAIL_CONFIRMED = 'isEmailConfirmed';
153
+
154
+	/**
155
+	 * Name of the PayPal API parameter that holds the partner ID.
156
+	 */
157
+	public const API_PARAM_PARTNER_ID = 'merchantId';
158
+
159
+	/**
160
+	 * Name of the PayPal API parameter that holds the merchant ID in the Track seller onboarding status request.
161
+	 */
162
+	public const API_PARAM_TRACK_MERCHANT_ID = 'merchant_id';
163
+
164
+	/**
165
+	 * Name of the PayPal API parameter that holds the payments_receivable status.
166
+	 */
167
+	public const API_PARAM_PAYMENTS_RECEIVABLE = 'payments_receivable';
168
+
169
+	/**
170
+	 * Name of the nonce used in the capture order request.
171
+	 */
172
+	public const CAPTURE_ORDER_NONCE_NAME = 'eea_pp_commerce_capture_order_payment';
173
+
174
+	/**
175
+	 * Name of the nonce used in the onboarding process.
176
+	 */
177
+	public const NONCE_NAME_ONBOARDING_RETURN = 'eea_pp_commerce_onboarding_return';
178
+
179
+	/**
180
+	 * Holds this payment method slug.
181
+	 */
182
+	public const PM_SLUG = 'paypalcheckout';
183
+
184
+
185
+	/**
186
+	 * Returns the base PayPal API URL.
187
+	 *
188
+	 * @param EE_Payment_Method $payment_method
189
+	 * @return string
190
+	 * @throws EE_Error
191
+	 * @throws ReflectionException
192
+	 */
193
+	public static function getPayPalApiUrl(EE_Payment_Method $payment_method): string
194
+	{
195
+		return $payment_method->debug_mode() ? 'https://api-m.sandbox.paypal.com' : 'https://api-m.paypal.com';
196
+	}
197 197
 }
Please login to merge, or discard this patch.
PaymentMethods/PayPalCommerce/modules/EED_PayPalCommerce.module.php 2 patches
Indentation   +490 added lines, -490 removed lines patch added patch discarded remove patch
@@ -22,494 +22,494 @@
 block discarded – undo
22 22
  */
23 23
 class EED_PayPalCommerce extends EED_Module
24 24
 {
25
-    /**
26
-     * @return EED_Module
27
-     * @throws EE_Error
28
-     * @throws ReflectionException
29
-     */
30
-    public static function instance(): EED_Module
31
-    {
32
-        return parent::get_instance(__CLASS__);
33
-    }
34
-
35
-
36
-    /**
37
-     * Run - initial module setup.
38
-     *
39
-     * @param WP $WP
40
-     * @return void
41
-     */
42
-    public function run($WP)
43
-    {
44
-    }
45
-
46
-
47
-    /**
48
-     * For hooking into EE Core and other modules.
49
-     *
50
-     * @return void
51
-     */
52
-    public static function set_hooks(): void
53
-    {
54
-        if (DbStatus::isOnline()) {
55
-            // Don't load PM on the front-end if not Connected.
56
-            add_filter(
57
-                'FHEE__EEM_Payment_Method__get_all_for_transaction__payment_methods',
58
-                [__CLASS__, 'filterPaymentMethods'],
59
-                100
60
-            );
61
-        }
62
-    }
63
-
64
-
65
-    /**
66
-     * For hooking into EE Core and other modules Admin.
67
-     *
68
-     * @return void
69
-     */
70
-    public static function set_hooks_admin(): void
71
-    {
72
-        if (DbStatus::isOnline()) {
73
-            // Create an Order.
74
-            add_action('wp_ajax_eeaPPCCreateOrder', [__CLASS__, 'createOrderRequest']);
75
-            add_action('wp_ajax_nopriv_eeaPPCCreateOrder', [__CLASS__, 'createOrderRequest']);
76
-            // Capture the Order.
77
-            add_action('wp_ajax_eeaPPCCaptureOrder', [__CLASS__, 'captureOrderRequest']);
78
-            add_action('wp_ajax_nopriv_eeaPPCCaptureOrder', [__CLASS__, 'captureOrderRequest']);
79
-            // Log errors from the JS side.
80
-            add_action('wp_ajax_eeaPPCommerceLogError', [__CLASS__, 'logJsError']);
81
-            add_action('wp_ajax_nopriv_eeaPPCommerceLogError', [__CLASS__, 'logJsError']);
82
-            // Don't load PM in the admin if not Connected.
83
-            add_filter(
84
-                'FHEE__EEM_Payment_Method__get_all_for_transaction__payment_methods',
85
-                [__CLASS__, 'filterPaymentMethods'],
86
-                100
87
-            );
88
-        }
89
-    }
90
-
91
-
92
-    /**
93
-     * Create the order and return its data as JSON.
94
-     * (AJAX)
95
-     *
96
-     * @return void
97
-     * @throws EE_Error
98
-     * @throws ReflectionException
99
-     */
100
-    public static function createOrderRequest(): void
101
-    {
102
-        $paypal_pm   = EED_PayPalCommerce::getPaymentMethod();
103
-        $post_params = EED_Module::getRequest()->postParams();
104
-        if (! $paypal_pm instanceof EE_Payment_Method) {
105
-            PayPalLogger::errorLogAndExit(
106
-                esc_html__('Related payment method not found (create Order).', 'event_espresso'),
107
-                $post_params
108
-            );
109
-        }
110
-        $transaction  = EED_PayPalCommerce::getTransaction();
111
-        $billing_info = $post_params['billing_info'] ?? [];
112
-        if ($billing_info) {
113
-            $billing_info_decoded = json_decode(stripslashes($billing_info), true);
114
-            $billing_info         = is_array($billing_info_decoded) ? $billing_info_decoded : [];
115
-        }
116
-        if (! $transaction) {
117
-            PayPalLogger::errorLogAndExit(
118
-                esc_html__('Transaction info not found.', 'event_espresso'),
119
-                $post_params,
120
-                $paypal_pm
121
-            );
122
-        }
123
-        $order_data = EED_PayPalCommerce::createOrder($transaction, $billing_info, $paypal_pm);
124
-        wp_send_json($order_data);
125
-    }
126
-
127
-
128
-    /**
129
-     * Capture the order and return status in JSON.
130
-     * (AJAX)
131
-     *
132
-     * @return void
133
-     */
134
-    public static function captureOrderRequest(): void
135
-    {
136
-        $error_message = false;
137
-        $paypal_pm     = EED_PayPalCommerce::getPaymentMethod();
138
-        if (! $paypal_pm instanceof EE_Payment_Method) {
139
-            $error_message = esc_html__(
140
-                'Payment method could not be found while trying to capture the Order.',
141
-                'event_espresso'
142
-            );
143
-        }
144
-        $transaction = EED_PayPalCommerce::getTransaction();
145
-        if (! $transaction) {
146
-            $error_message = esc_html__(
147
-                'Could not process this payment because it has no associated transaction.',
148
-                'event_espresso'
149
-            );
150
-        }
151
-        $order_id = EED_Module::getRequest()->getRequestParam('order_id');
152
-        if (! $order_id) {
153
-            $error_message = esc_html__('Order ID missing.', 'event_espresso');
154
-        }
155
-        // Check for the payment nonce.
156
-        // $request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
157
-        // $order_nonce = $request->getRequestParam('pp_order_nonce');
158
-        // if (empty($order_nonce) || ! wp_verify_nonce($order_nonce, Domain::CAPTURE_ORDER_NONCE_NAME)) {
159
-        //     $error_message = esc_html__('No or incorrect order capture nonce provided !', 'event_espresso');
160
-        //     return EEG_PayPalCheckout::updatePaymentStatus($payment, $failed_status, $request->postParams(), $error_message);
161
-        // }
162
-        $billing_info         = EED_Module::getRequest()->getRequestParam('billing_info');
163
-        $billing_info_decoded = json_decode(stripslashes($billing_info), true);
164
-        $billing_info         = is_array($billing_info_decoded) ? $billing_info_decoded : [];
165
-        if (! $billing_info) {
166
-            $error_message = esc_html__('Billing info missing.', 'event_espresso');
167
-        }
168
-        // We had an error. Log and EXIT.
169
-        if ($error_message) {
170
-            PayPalLogger::errorLogAndExit($error_message, EED_Module::getRequest()->postParams(), $paypal_pm);
171
-        }
172
-        try {
173
-            $capture_response = EED_PayPalCommerce::captureOrder($transaction, $paypal_pm, $order_id, $billing_info);
174
-        } catch (Exception $e) {
175
-            $capture_response = [
176
-                'error'   => 'CAPTURE_ORDER_ERROR',
177
-                'message' => $e->getMessage(),
178
-            ];
179
-        }
180
-        wp_send_json($capture_response);
181
-    }
182
-
183
-
184
-    /**
185
-     * Create a new Order using the PP API.
186
-     *
187
-     * @param EE_Transaction    $transaction
188
-     * @param array             $billing_info
189
-     * @param EE_Payment_Method $paypal_pm
190
-     * @return array
191
-     * @throws EE_Error
192
-     * @throws ReflectionException
193
-     */
194
-    public static function createOrder(
195
-        EE_Transaction $transaction,
196
-        array $billing_info,
197
-        EE_Payment_Method $paypal_pm
198
-    ): array {
199
-        $create_order_api = EED_PayPalCommerce::getCreateOrderApi($transaction, $billing_info, $paypal_pm);
200
-        if (! $create_order_api instanceof CreateOrder) {
201
-            return [
202
-                'error'   => 'CREATE_ORDER_API_FAULT',
203
-                'message' => esc_html__('The Create Order API request fault.', 'event_espresso'),
204
-            ];
205
-        }
206
-        $payment = EEG_PayPalCheckout::createPayment($transaction, $paypal_pm);
207
-        $order   = $create_order_api->create();
208
-        if (isset($order['error'])) {
209
-            EEG_PayPalCheckout::updatePaymentStatus($payment, EEM_Payment::status_id_failed, $order, $order['error']);
210
-            return [
211
-                'error'   => 'CREATE_ORDER_API_RESPONSE_ERROR',
212
-                'message' => $order['message'],
213
-            ];
214
-        }
215
-        return [
216
-            'pp_order_id' => $order['id'],
217
-        ];
218
-    }
219
-
220
-
221
-    /**
222
-     * Create a new Order using the PP API.
223
-     *
224
-     * @param EE_Transaction    $transaction
225
-     * @param EE_Payment_Method $paypal_pm
226
-     * @param string            $order_id
227
-     * @param array             $billing_info
228
-     * @return array
229
-     * @throws EE_Error
230
-     * @throws ReflectionException
231
-     */
232
-    public static function captureOrder(
233
-        EE_Transaction $transaction,
234
-        EE_Payment_Method $paypal_pm,
235
-        string $order_id,
236
-        array $billing_info
237
-    ): array {
238
-        $capture_order_api = EED_PayPalCommerce::getCaptureOrderApi($transaction, $paypal_pm, $order_id);
239
-        if (! $capture_order_api instanceof CaptureOrder) {
240
-            return [
241
-                'error'   => 'CAPTURE_ORDER_API_FAULT',
242
-                'message' => esc_html__('A capture Order API request fault.', 'event_espresso'),
243
-            ];
244
-        }
245
-        $payment = $transaction->last_payment() ?? EEG_PayPalCheckout::createPayment($transaction, $paypal_pm);
246
-        $order   = $capture_order_api->capture();
247
-        if (isset($order['error'])) {
248
-            EEG_PayPalCheckout::updatePaymentStatus($payment, EEM_Payment::status_id_failed, $order, $order['error']);
249
-            return $order;
250
-        }
251
-        // Attach the transaction ID to this order.
252
-        try {
253
-            $order['ee_txn_id'] = $transaction->ID();
254
-        } catch (Exception $e) {
255
-            // Just don't set the txn id.
256
-        }
257
-        $order_status = EEG_PayPalCheckout::isOrderCompleted($order);
258
-        if ($order_status['completed']) {
259
-            // Order captured, so payment was successful.
260
-            $update_message = esc_html__('Order captured successfully.', 'event_espresso');
261
-            EEG_PayPalCheckout::updatePaymentStatus($payment, EEM_Payment::status_id_approved, $order, $update_message);
262
-        } else {
263
-            EEG_PayPalCheckout::updatePaymentStatus(
264
-                $payment,
265
-                EEM_Payment::status_id_failed,
266
-                $order,
267
-                $order_status['message']
268
-            );
269
-        }
270
-        EEG_PayPalCheckout::saveBillingDetails($payment, $transaction, $order, $billing_info);
271
-        $nonce = wp_create_nonce(Domain::CAPTURE_ORDER_NONCE_NAME);
272
-        return [
273
-            'pp_order_nonce'  => $nonce,
274
-            'pp_order_id'     => $order['id'],
275
-            'pp_order_status' => $order['purchase_units'][0]['payments']['captures'][0]['status'] ?? 'ORDER_STATUS_UNKNOWN',
276
-            'pp_order_amount' => $order['purchase_units'][0]['payments']['captures'][0]['amount']['value'] ?? '',
277
-        ];
278
-    }
279
-
280
-
281
-    /**
282
-     * Create an Order for this transaction.
283
-     *
284
-     * @param EE_Transaction    $transaction
285
-     * @param array             $billing_info
286
-     * @param EE_Payment_Method $paypal_pm
287
-     * @return CreateOrder|null
288
-     * @throws EE_Error
289
-     * @throws ReflectionException
290
-     */
291
-    public static function getCreateOrderApi(
292
-        EE_Transaction $transaction,
293
-        array $billing_info,
294
-        EE_Payment_Method $paypal_pm
295
-    ): ?CreateOrder {
296
-        $paypal_api = EED_PayPalCommerce::getPayPalApi($paypal_pm);
297
-        if (! $paypal_api instanceof PayPalApi) {
298
-            return null;
299
-        }
300
-        return LoaderFactory::getNew(CreateOrder::class, [$paypal_api, $transaction, $billing_info]);
301
-    }
302
-
303
-
304
-    /**
305
-     * Create an Order for this transaction.
306
-     *
307
-     * @param EE_Transaction    $transaction
308
-     * @param EE_Payment_Method $paypal_pm
309
-     * @param string            $order_id
310
-     * @return CaptureOrder|null
311
-     * @throws EE_Error
312
-     * @throws ReflectionException
313
-     */
314
-    public static function getCaptureOrderApi(
315
-        EE_Transaction $transaction,
316
-        EE_Payment_Method $paypal_pm,
317
-        string $order_id
318
-    ): ?CaptureOrder {
319
-        $paypal_api = EED_PayPalCommerce::getPayPalApi($paypal_pm);
320
-        if (! $paypal_api instanceof PayPalApi) {
321
-            return null;
322
-        }
323
-        return LoaderFactory::getNew(CaptureOrder::class, [$paypal_api, $transaction, $order_id]);
324
-    }
325
-
326
-
327
-    /**
328
-     * Return a PayPal API object, or false on failure.
329
-     *
330
-     * @param EE_Payment_Method $paypal_pm
331
-     * @return PayPalApi|null
332
-     * @throws EE_Error
333
-     * @throws ReflectionException
334
-     */
335
-    public static function getPayPalApi(EE_Payment_Method $paypal_pm): ?PayPalApi
336
-    {
337
-        // Try getting the first party credentials to determine if this is a first party integration that's active.
338
-        $client_id     = PayPalExtraMetaManager::getPmOption($paypal_pm, Domain::META_KEY_CLIENT_ID);
339
-        $client_secret = PayPalExtraMetaManager::getPmOption($paypal_pm, Domain::META_KEY_CLIENT_SECRET);
340
-        $bn_code       = PayPalExtraMetaManager::getPmOption($paypal_pm, Domain::META_KEY_BN_CODE);
341
-        if ($client_id && $client_secret) {
342
-            return new FirstPartyPayPalApi($client_id, $client_secret, $bn_code, $paypal_pm->debug_mode());
343
-        }
344
-        // Third party integration credentials:
345
-        $access_token = EED_PayPalOnboard::getPartnerAccessToken($paypal_pm);
346
-        if (! $access_token || ! $bn_code) {
347
-            return null;
348
-        }
349
-        $partner_client_id = PayPalExtraMetaManager::getPmOption($paypal_pm, Domain::META_KEY_PARTNER_CLIENT_ID) ?: '';
350
-        $payer_id          = PayPalExtraMetaManager::getPmOption($paypal_pm, Domain::META_KEY_SELLER_MERCHANT_ID) ?: '';
351
-        return new ThirdPartyPayPalApi(
352
-            $access_token,
353
-            $bn_code,
354
-            $partner_client_id,
355
-            $payer_id,
356
-            $paypal_pm->debug_mode()
357
-        );
358
-    }
359
-
360
-
361
-    /**
362
-     * Requests a client token.
363
-     *
364
-     * @param EE_Payment_Method $paypal_pm
365
-     * @return array
366
-     * @throws EE_Error
367
-     * @throws ReflectionException
368
-     */
369
-    public static function requestClientToken(EE_Payment_Method $paypal_pm): array
370
-    {
371
-        $error      = ['error' => 'GET_CLIENT_TOKEN_FAULT'];
372
-        $paypal_api = EED_PayPalCommerce::getPayPalApi($paypal_pm);
373
-        if (! $paypal_api instanceof PayPalApi) {
374
-            $error['message'] = esc_html__('Got an error while trying to get the client token.', 'event_espresso');
375
-            return $error;
376
-        }
377
-        $client_token_api = new ClientToken($paypal_api, $paypal_pm->debug_mode());
378
-        $client_token     = $client_token_api->getToken();
379
-        if (isset($client_token['error'])) {
380
-            return $client_token;
381
-        }
382
-        if (empty($client_token)) {
383
-            $error['message'] = esc_html__('Client token not valid.', 'event_espresso');
384
-            return $error;
385
-        }
386
-        return $client_token;
387
-    }
388
-
389
-
390
-    /**
391
-     * Retrieve the payment method from the provided data.
392
-     *
393
-     * @return EE_Transaction|null
394
-     */
395
-    public static function getTransaction(): ?EE_Transaction
396
-    {
397
-        try {
398
-            $txn_id      = EED_Module::getRequest()->getRequestParam('txn_id', 0, DataType::INT);
399
-            $transaction = EEM_Transaction::instance()->get_one_by_ID($txn_id);
400
-            if (! $transaction instanceof EE_Transaction) {
401
-                PayPalLogger::errorLog(
402
-                    esc_html__('No transaction found by ID:', 'event_espresso'),
403
-                    EED_Module::getRequest()->postParams()
404
-                );
405
-                return null;
406
-            }
407
-        } catch (Exception $e) {
408
-            return null;
409
-        }
410
-        return $transaction;
411
-    }
412
-
413
-
414
-    /**
415
-     * Return a PayPal API object, or false on failure.
416
-     *
417
-     * @param EE_Payment_Method $paypal_pm
418
-     * @return bool
419
-     * @throws EE_Error
420
-     * @throws ReflectionException
421
-     */
422
-    public static function isThirdParty(EE_Payment_Method $paypal_pm): bool
423
-    {
424
-        $pp_meta_data = PayPalExtraMetaManager::getAllData($paypal_pm);
425
-        return ! empty($pp_meta_data[ Domain::META_KEY_SELLER_MERCHANT_ID ])
426
-            && ! empty($pp_meta_data[ Domain::META_KEY_ACCESS_TOKEN ]);
427
-    }
428
-
429
-
430
-    /**
431
-     * Retrieve the payment method from the provided data.
432
-     *
433
-     * @return EE_Payment_Method|null
434
-     */
435
-    public static function getPaymentMethod(): ?EE_Payment_Method
436
-    {
437
-        try {
438
-            // Check if all required parameters are present.
439
-            $pm_slug        = EED_Module::getRequest()->getRequestParam('payment_method');
440
-            $payment_method = EEM_Payment_Method::instance()->get_one_by_slug($pm_slug);
441
-            if ($payment_method instanceof EE_Payment_Method) {
442
-                return $payment_method;
443
-            }
444
-        } catch (Exception $e) {
445
-            return null;
446
-        }
447
-        return null;
448
-    }
449
-
450
-
451
-    /**
452
-     * Log JS error.
453
-     *
454
-     * @return void
455
-     */
456
-    public static function logJsError(): void
457
-    {
458
-        // Default to the "first" PayPal checkout PM.
459
-        $request        = EED_Module::getRequest();
460
-        $pm_slug        = $request->getRequestParam('pm_slug', Domain::PM_SLUG);
461
-        $payment_method = null;
462
-        $txn_id         = 'unknown';
463
-        try {
464
-            $payment_method = EEM_Payment_Method::instance()->get_one_of_type($pm_slug);
465
-            $txn_id         = sanitize_text_field($request->getRequestParam('txn_id', '-'));
466
-        } catch (Exception $e) {
467
-            // Don't throw out anything, log at least something.
468
-        }
469
-        PayPalLogger::errorLog("JS Error on transaction: $txn_id", $request->postParams(), $payment_method);
470
-    }
471
-
472
-
473
-    /**
474
-     * Filter the Payment Methods list.
475
-     * if needed, this filter can also supply the $transaction and $scope parameters.
476
-     *
477
-     * @param EE_Payment_Method[] $payment_methods
478
-     * @return array
479
-     * @throws EE_Error
480
-     * @throws ReflectionException
481
-     */
482
-    public static function filterPaymentMethods(array $payment_methods): array
483
-    {
484
-        // Don't allow this PM on the checkout page if not Connected.
485
-        foreach ($payment_methods as $key => $pm) {
486
-            // It is a PayPal Commerce payment method. Check if it's connected. If not - remove from the list.
487
-            if (str_contains($pm->slug(), Domain::PM_SLUG) && ! EED_PayPalOnboard::isOnboard($pm)) {
488
-                unset($payment_methods[ $key ]);
489
-            }
490
-        }
491
-        return $payment_methods;
492
-    }
493
-
494
-
495
-    /**
496
-     *  Get all active states.
497
-     *
498
-     * @return array
499
-     * @throws EE_Error
500
-     * @throws ReflectionException
501
-     */
502
-    public static function getActiveStates(): array
503
-    {
504
-        $state_options = [];
505
-        $states        = EEM_State::instance()->get_all_active_states();
506
-        if (! empty($states)) {
507
-            foreach ($states as $numeral => $state) {
508
-                if ($state instanceof EE_State) {
509
-                    $state_options[ $numeral ] = $state->abbrev();
510
-                }
511
-            }
512
-        }
513
-        return $state_options;
514
-    }
25
+	/**
26
+	 * @return EED_Module
27
+	 * @throws EE_Error
28
+	 * @throws ReflectionException
29
+	 */
30
+	public static function instance(): EED_Module
31
+	{
32
+		return parent::get_instance(__CLASS__);
33
+	}
34
+
35
+
36
+	/**
37
+	 * Run - initial module setup.
38
+	 *
39
+	 * @param WP $WP
40
+	 * @return void
41
+	 */
42
+	public function run($WP)
43
+	{
44
+	}
45
+
46
+
47
+	/**
48
+	 * For hooking into EE Core and other modules.
49
+	 *
50
+	 * @return void
51
+	 */
52
+	public static function set_hooks(): void
53
+	{
54
+		if (DbStatus::isOnline()) {
55
+			// Don't load PM on the front-end if not Connected.
56
+			add_filter(
57
+				'FHEE__EEM_Payment_Method__get_all_for_transaction__payment_methods',
58
+				[__CLASS__, 'filterPaymentMethods'],
59
+				100
60
+			);
61
+		}
62
+	}
63
+
64
+
65
+	/**
66
+	 * For hooking into EE Core and other modules Admin.
67
+	 *
68
+	 * @return void
69
+	 */
70
+	public static function set_hooks_admin(): void
71
+	{
72
+		if (DbStatus::isOnline()) {
73
+			// Create an Order.
74
+			add_action('wp_ajax_eeaPPCCreateOrder', [__CLASS__, 'createOrderRequest']);
75
+			add_action('wp_ajax_nopriv_eeaPPCCreateOrder', [__CLASS__, 'createOrderRequest']);
76
+			// Capture the Order.
77
+			add_action('wp_ajax_eeaPPCCaptureOrder', [__CLASS__, 'captureOrderRequest']);
78
+			add_action('wp_ajax_nopriv_eeaPPCCaptureOrder', [__CLASS__, 'captureOrderRequest']);
79
+			// Log errors from the JS side.
80
+			add_action('wp_ajax_eeaPPCommerceLogError', [__CLASS__, 'logJsError']);
81
+			add_action('wp_ajax_nopriv_eeaPPCommerceLogError', [__CLASS__, 'logJsError']);
82
+			// Don't load PM in the admin if not Connected.
83
+			add_filter(
84
+				'FHEE__EEM_Payment_Method__get_all_for_transaction__payment_methods',
85
+				[__CLASS__, 'filterPaymentMethods'],
86
+				100
87
+			);
88
+		}
89
+	}
90
+
91
+
92
+	/**
93
+	 * Create the order and return its data as JSON.
94
+	 * (AJAX)
95
+	 *
96
+	 * @return void
97
+	 * @throws EE_Error
98
+	 * @throws ReflectionException
99
+	 */
100
+	public static function createOrderRequest(): void
101
+	{
102
+		$paypal_pm   = EED_PayPalCommerce::getPaymentMethod();
103
+		$post_params = EED_Module::getRequest()->postParams();
104
+		if (! $paypal_pm instanceof EE_Payment_Method) {
105
+			PayPalLogger::errorLogAndExit(
106
+				esc_html__('Related payment method not found (create Order).', 'event_espresso'),
107
+				$post_params
108
+			);
109
+		}
110
+		$transaction  = EED_PayPalCommerce::getTransaction();
111
+		$billing_info = $post_params['billing_info'] ?? [];
112
+		if ($billing_info) {
113
+			$billing_info_decoded = json_decode(stripslashes($billing_info), true);
114
+			$billing_info         = is_array($billing_info_decoded) ? $billing_info_decoded : [];
115
+		}
116
+		if (! $transaction) {
117
+			PayPalLogger::errorLogAndExit(
118
+				esc_html__('Transaction info not found.', 'event_espresso'),
119
+				$post_params,
120
+				$paypal_pm
121
+			);
122
+		}
123
+		$order_data = EED_PayPalCommerce::createOrder($transaction, $billing_info, $paypal_pm);
124
+		wp_send_json($order_data);
125
+	}
126
+
127
+
128
+	/**
129
+	 * Capture the order and return status in JSON.
130
+	 * (AJAX)
131
+	 *
132
+	 * @return void
133
+	 */
134
+	public static function captureOrderRequest(): void
135
+	{
136
+		$error_message = false;
137
+		$paypal_pm     = EED_PayPalCommerce::getPaymentMethod();
138
+		if (! $paypal_pm instanceof EE_Payment_Method) {
139
+			$error_message = esc_html__(
140
+				'Payment method could not be found while trying to capture the Order.',
141
+				'event_espresso'
142
+			);
143
+		}
144
+		$transaction = EED_PayPalCommerce::getTransaction();
145
+		if (! $transaction) {
146
+			$error_message = esc_html__(
147
+				'Could not process this payment because it has no associated transaction.',
148
+				'event_espresso'
149
+			);
150
+		}
151
+		$order_id = EED_Module::getRequest()->getRequestParam('order_id');
152
+		if (! $order_id) {
153
+			$error_message = esc_html__('Order ID missing.', 'event_espresso');
154
+		}
155
+		// Check for the payment nonce.
156
+		// $request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
157
+		// $order_nonce = $request->getRequestParam('pp_order_nonce');
158
+		// if (empty($order_nonce) || ! wp_verify_nonce($order_nonce, Domain::CAPTURE_ORDER_NONCE_NAME)) {
159
+		//     $error_message = esc_html__('No or incorrect order capture nonce provided !', 'event_espresso');
160
+		//     return EEG_PayPalCheckout::updatePaymentStatus($payment, $failed_status, $request->postParams(), $error_message);
161
+		// }
162
+		$billing_info         = EED_Module::getRequest()->getRequestParam('billing_info');
163
+		$billing_info_decoded = json_decode(stripslashes($billing_info), true);
164
+		$billing_info         = is_array($billing_info_decoded) ? $billing_info_decoded : [];
165
+		if (! $billing_info) {
166
+			$error_message = esc_html__('Billing info missing.', 'event_espresso');
167
+		}
168
+		// We had an error. Log and EXIT.
169
+		if ($error_message) {
170
+			PayPalLogger::errorLogAndExit($error_message, EED_Module::getRequest()->postParams(), $paypal_pm);
171
+		}
172
+		try {
173
+			$capture_response = EED_PayPalCommerce::captureOrder($transaction, $paypal_pm, $order_id, $billing_info);
174
+		} catch (Exception $e) {
175
+			$capture_response = [
176
+				'error'   => 'CAPTURE_ORDER_ERROR',
177
+				'message' => $e->getMessage(),
178
+			];
179
+		}
180
+		wp_send_json($capture_response);
181
+	}
182
+
183
+
184
+	/**
185
+	 * Create a new Order using the PP API.
186
+	 *
187
+	 * @param EE_Transaction    $transaction
188
+	 * @param array             $billing_info
189
+	 * @param EE_Payment_Method $paypal_pm
190
+	 * @return array
191
+	 * @throws EE_Error
192
+	 * @throws ReflectionException
193
+	 */
194
+	public static function createOrder(
195
+		EE_Transaction $transaction,
196
+		array $billing_info,
197
+		EE_Payment_Method $paypal_pm
198
+	): array {
199
+		$create_order_api = EED_PayPalCommerce::getCreateOrderApi($transaction, $billing_info, $paypal_pm);
200
+		if (! $create_order_api instanceof CreateOrder) {
201
+			return [
202
+				'error'   => 'CREATE_ORDER_API_FAULT',
203
+				'message' => esc_html__('The Create Order API request fault.', 'event_espresso'),
204
+			];
205
+		}
206
+		$payment = EEG_PayPalCheckout::createPayment($transaction, $paypal_pm);
207
+		$order   = $create_order_api->create();
208
+		if (isset($order['error'])) {
209
+			EEG_PayPalCheckout::updatePaymentStatus($payment, EEM_Payment::status_id_failed, $order, $order['error']);
210
+			return [
211
+				'error'   => 'CREATE_ORDER_API_RESPONSE_ERROR',
212
+				'message' => $order['message'],
213
+			];
214
+		}
215
+		return [
216
+			'pp_order_id' => $order['id'],
217
+		];
218
+	}
219
+
220
+
221
+	/**
222
+	 * Create a new Order using the PP API.
223
+	 *
224
+	 * @param EE_Transaction    $transaction
225
+	 * @param EE_Payment_Method $paypal_pm
226
+	 * @param string            $order_id
227
+	 * @param array             $billing_info
228
+	 * @return array
229
+	 * @throws EE_Error
230
+	 * @throws ReflectionException
231
+	 */
232
+	public static function captureOrder(
233
+		EE_Transaction $transaction,
234
+		EE_Payment_Method $paypal_pm,
235
+		string $order_id,
236
+		array $billing_info
237
+	): array {
238
+		$capture_order_api = EED_PayPalCommerce::getCaptureOrderApi($transaction, $paypal_pm, $order_id);
239
+		if (! $capture_order_api instanceof CaptureOrder) {
240
+			return [
241
+				'error'   => 'CAPTURE_ORDER_API_FAULT',
242
+				'message' => esc_html__('A capture Order API request fault.', 'event_espresso'),
243
+			];
244
+		}
245
+		$payment = $transaction->last_payment() ?? EEG_PayPalCheckout::createPayment($transaction, $paypal_pm);
246
+		$order   = $capture_order_api->capture();
247
+		if (isset($order['error'])) {
248
+			EEG_PayPalCheckout::updatePaymentStatus($payment, EEM_Payment::status_id_failed, $order, $order['error']);
249
+			return $order;
250
+		}
251
+		// Attach the transaction ID to this order.
252
+		try {
253
+			$order['ee_txn_id'] = $transaction->ID();
254
+		} catch (Exception $e) {
255
+			// Just don't set the txn id.
256
+		}
257
+		$order_status = EEG_PayPalCheckout::isOrderCompleted($order);
258
+		if ($order_status['completed']) {
259
+			// Order captured, so payment was successful.
260
+			$update_message = esc_html__('Order captured successfully.', 'event_espresso');
261
+			EEG_PayPalCheckout::updatePaymentStatus($payment, EEM_Payment::status_id_approved, $order, $update_message);
262
+		} else {
263
+			EEG_PayPalCheckout::updatePaymentStatus(
264
+				$payment,
265
+				EEM_Payment::status_id_failed,
266
+				$order,
267
+				$order_status['message']
268
+			);
269
+		}
270
+		EEG_PayPalCheckout::saveBillingDetails($payment, $transaction, $order, $billing_info);
271
+		$nonce = wp_create_nonce(Domain::CAPTURE_ORDER_NONCE_NAME);
272
+		return [
273
+			'pp_order_nonce'  => $nonce,
274
+			'pp_order_id'     => $order['id'],
275
+			'pp_order_status' => $order['purchase_units'][0]['payments']['captures'][0]['status'] ?? 'ORDER_STATUS_UNKNOWN',
276
+			'pp_order_amount' => $order['purchase_units'][0]['payments']['captures'][0]['amount']['value'] ?? '',
277
+		];
278
+	}
279
+
280
+
281
+	/**
282
+	 * Create an Order for this transaction.
283
+	 *
284
+	 * @param EE_Transaction    $transaction
285
+	 * @param array             $billing_info
286
+	 * @param EE_Payment_Method $paypal_pm
287
+	 * @return CreateOrder|null
288
+	 * @throws EE_Error
289
+	 * @throws ReflectionException
290
+	 */
291
+	public static function getCreateOrderApi(
292
+		EE_Transaction $transaction,
293
+		array $billing_info,
294
+		EE_Payment_Method $paypal_pm
295
+	): ?CreateOrder {
296
+		$paypal_api = EED_PayPalCommerce::getPayPalApi($paypal_pm);
297
+		if (! $paypal_api instanceof PayPalApi) {
298
+			return null;
299
+		}
300
+		return LoaderFactory::getNew(CreateOrder::class, [$paypal_api, $transaction, $billing_info]);
301
+	}
302
+
303
+
304
+	/**
305
+	 * Create an Order for this transaction.
306
+	 *
307
+	 * @param EE_Transaction    $transaction
308
+	 * @param EE_Payment_Method $paypal_pm
309
+	 * @param string            $order_id
310
+	 * @return CaptureOrder|null
311
+	 * @throws EE_Error
312
+	 * @throws ReflectionException
313
+	 */
314
+	public static function getCaptureOrderApi(
315
+		EE_Transaction $transaction,
316
+		EE_Payment_Method $paypal_pm,
317
+		string $order_id
318
+	): ?CaptureOrder {
319
+		$paypal_api = EED_PayPalCommerce::getPayPalApi($paypal_pm);
320
+		if (! $paypal_api instanceof PayPalApi) {
321
+			return null;
322
+		}
323
+		return LoaderFactory::getNew(CaptureOrder::class, [$paypal_api, $transaction, $order_id]);
324
+	}
325
+
326
+
327
+	/**
328
+	 * Return a PayPal API object, or false on failure.
329
+	 *
330
+	 * @param EE_Payment_Method $paypal_pm
331
+	 * @return PayPalApi|null
332
+	 * @throws EE_Error
333
+	 * @throws ReflectionException
334
+	 */
335
+	public static function getPayPalApi(EE_Payment_Method $paypal_pm): ?PayPalApi
336
+	{
337
+		// Try getting the first party credentials to determine if this is a first party integration that's active.
338
+		$client_id     = PayPalExtraMetaManager::getPmOption($paypal_pm, Domain::META_KEY_CLIENT_ID);
339
+		$client_secret = PayPalExtraMetaManager::getPmOption($paypal_pm, Domain::META_KEY_CLIENT_SECRET);
340
+		$bn_code       = PayPalExtraMetaManager::getPmOption($paypal_pm, Domain::META_KEY_BN_CODE);
341
+		if ($client_id && $client_secret) {
342
+			return new FirstPartyPayPalApi($client_id, $client_secret, $bn_code, $paypal_pm->debug_mode());
343
+		}
344
+		// Third party integration credentials:
345
+		$access_token = EED_PayPalOnboard::getPartnerAccessToken($paypal_pm);
346
+		if (! $access_token || ! $bn_code) {
347
+			return null;
348
+		}
349
+		$partner_client_id = PayPalExtraMetaManager::getPmOption($paypal_pm, Domain::META_KEY_PARTNER_CLIENT_ID) ?: '';
350
+		$payer_id          = PayPalExtraMetaManager::getPmOption($paypal_pm, Domain::META_KEY_SELLER_MERCHANT_ID) ?: '';
351
+		return new ThirdPartyPayPalApi(
352
+			$access_token,
353
+			$bn_code,
354
+			$partner_client_id,
355
+			$payer_id,
356
+			$paypal_pm->debug_mode()
357
+		);
358
+	}
359
+
360
+
361
+	/**
362
+	 * Requests a client token.
363
+	 *
364
+	 * @param EE_Payment_Method $paypal_pm
365
+	 * @return array
366
+	 * @throws EE_Error
367
+	 * @throws ReflectionException
368
+	 */
369
+	public static function requestClientToken(EE_Payment_Method $paypal_pm): array
370
+	{
371
+		$error      = ['error' => 'GET_CLIENT_TOKEN_FAULT'];
372
+		$paypal_api = EED_PayPalCommerce::getPayPalApi($paypal_pm);
373
+		if (! $paypal_api instanceof PayPalApi) {
374
+			$error['message'] = esc_html__('Got an error while trying to get the client token.', 'event_espresso');
375
+			return $error;
376
+		}
377
+		$client_token_api = new ClientToken($paypal_api, $paypal_pm->debug_mode());
378
+		$client_token     = $client_token_api->getToken();
379
+		if (isset($client_token['error'])) {
380
+			return $client_token;
381
+		}
382
+		if (empty($client_token)) {
383
+			$error['message'] = esc_html__('Client token not valid.', 'event_espresso');
384
+			return $error;
385
+		}
386
+		return $client_token;
387
+	}
388
+
389
+
390
+	/**
391
+	 * Retrieve the payment method from the provided data.
392
+	 *
393
+	 * @return EE_Transaction|null
394
+	 */
395
+	public static function getTransaction(): ?EE_Transaction
396
+	{
397
+		try {
398
+			$txn_id      = EED_Module::getRequest()->getRequestParam('txn_id', 0, DataType::INT);
399
+			$transaction = EEM_Transaction::instance()->get_one_by_ID($txn_id);
400
+			if (! $transaction instanceof EE_Transaction) {
401
+				PayPalLogger::errorLog(
402
+					esc_html__('No transaction found by ID:', 'event_espresso'),
403
+					EED_Module::getRequest()->postParams()
404
+				);
405
+				return null;
406
+			}
407
+		} catch (Exception $e) {
408
+			return null;
409
+		}
410
+		return $transaction;
411
+	}
412
+
413
+
414
+	/**
415
+	 * Return a PayPal API object, or false on failure.
416
+	 *
417
+	 * @param EE_Payment_Method $paypal_pm
418
+	 * @return bool
419
+	 * @throws EE_Error
420
+	 * @throws ReflectionException
421
+	 */
422
+	public static function isThirdParty(EE_Payment_Method $paypal_pm): bool
423
+	{
424
+		$pp_meta_data = PayPalExtraMetaManager::getAllData($paypal_pm);
425
+		return ! empty($pp_meta_data[ Domain::META_KEY_SELLER_MERCHANT_ID ])
426
+			&& ! empty($pp_meta_data[ Domain::META_KEY_ACCESS_TOKEN ]);
427
+	}
428
+
429
+
430
+	/**
431
+	 * Retrieve the payment method from the provided data.
432
+	 *
433
+	 * @return EE_Payment_Method|null
434
+	 */
435
+	public static function getPaymentMethod(): ?EE_Payment_Method
436
+	{
437
+		try {
438
+			// Check if all required parameters are present.
439
+			$pm_slug        = EED_Module::getRequest()->getRequestParam('payment_method');
440
+			$payment_method = EEM_Payment_Method::instance()->get_one_by_slug($pm_slug);
441
+			if ($payment_method instanceof EE_Payment_Method) {
442
+				return $payment_method;
443
+			}
444
+		} catch (Exception $e) {
445
+			return null;
446
+		}
447
+		return null;
448
+	}
449
+
450
+
451
+	/**
452
+	 * Log JS error.
453
+	 *
454
+	 * @return void
455
+	 */
456
+	public static function logJsError(): void
457
+	{
458
+		// Default to the "first" PayPal checkout PM.
459
+		$request        = EED_Module::getRequest();
460
+		$pm_slug        = $request->getRequestParam('pm_slug', Domain::PM_SLUG);
461
+		$payment_method = null;
462
+		$txn_id         = 'unknown';
463
+		try {
464
+			$payment_method = EEM_Payment_Method::instance()->get_one_of_type($pm_slug);
465
+			$txn_id         = sanitize_text_field($request->getRequestParam('txn_id', '-'));
466
+		} catch (Exception $e) {
467
+			// Don't throw out anything, log at least something.
468
+		}
469
+		PayPalLogger::errorLog("JS Error on transaction: $txn_id", $request->postParams(), $payment_method);
470
+	}
471
+
472
+
473
+	/**
474
+	 * Filter the Payment Methods list.
475
+	 * if needed, this filter can also supply the $transaction and $scope parameters.
476
+	 *
477
+	 * @param EE_Payment_Method[] $payment_methods
478
+	 * @return array
479
+	 * @throws EE_Error
480
+	 * @throws ReflectionException
481
+	 */
482
+	public static function filterPaymentMethods(array $payment_methods): array
483
+	{
484
+		// Don't allow this PM on the checkout page if not Connected.
485
+		foreach ($payment_methods as $key => $pm) {
486
+			// It is a PayPal Commerce payment method. Check if it's connected. If not - remove from the list.
487
+			if (str_contains($pm->slug(), Domain::PM_SLUG) && ! EED_PayPalOnboard::isOnboard($pm)) {
488
+				unset($payment_methods[ $key ]);
489
+			}
490
+		}
491
+		return $payment_methods;
492
+	}
493
+
494
+
495
+	/**
496
+	 *  Get all active states.
497
+	 *
498
+	 * @return array
499
+	 * @throws EE_Error
500
+	 * @throws ReflectionException
501
+	 */
502
+	public static function getActiveStates(): array
503
+	{
504
+		$state_options = [];
505
+		$states        = EEM_State::instance()->get_all_active_states();
506
+		if (! empty($states)) {
507
+			foreach ($states as $numeral => $state) {
508
+				if ($state instanceof EE_State) {
509
+					$state_options[ $numeral ] = $state->abbrev();
510
+				}
511
+			}
512
+		}
513
+		return $state_options;
514
+	}
515 515
 }
Please login to merge, or discard this patch.
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -101,7 +101,7 @@  discard block
 block discarded – undo
101 101
     {
102 102
         $paypal_pm   = EED_PayPalCommerce::getPaymentMethod();
103 103
         $post_params = EED_Module::getRequest()->postParams();
104
-        if (! $paypal_pm instanceof EE_Payment_Method) {
104
+        if ( ! $paypal_pm instanceof EE_Payment_Method) {
105 105
             PayPalLogger::errorLogAndExit(
106 106
                 esc_html__('Related payment method not found (create Order).', 'event_espresso'),
107 107
                 $post_params
@@ -113,7 +113,7 @@  discard block
 block discarded – undo
113 113
             $billing_info_decoded = json_decode(stripslashes($billing_info), true);
114 114
             $billing_info         = is_array($billing_info_decoded) ? $billing_info_decoded : [];
115 115
         }
116
-        if (! $transaction) {
116
+        if ( ! $transaction) {
117 117
             PayPalLogger::errorLogAndExit(
118 118
                 esc_html__('Transaction info not found.', 'event_espresso'),
119 119
                 $post_params,
@@ -135,21 +135,21 @@  discard block
 block discarded – undo
135 135
     {
136 136
         $error_message = false;
137 137
         $paypal_pm     = EED_PayPalCommerce::getPaymentMethod();
138
-        if (! $paypal_pm instanceof EE_Payment_Method) {
138
+        if ( ! $paypal_pm instanceof EE_Payment_Method) {
139 139
             $error_message = esc_html__(
140 140
                 'Payment method could not be found while trying to capture the Order.',
141 141
                 'event_espresso'
142 142
             );
143 143
         }
144 144
         $transaction = EED_PayPalCommerce::getTransaction();
145
-        if (! $transaction) {
145
+        if ( ! $transaction) {
146 146
             $error_message = esc_html__(
147 147
                 'Could not process this payment because it has no associated transaction.',
148 148
                 'event_espresso'
149 149
             );
150 150
         }
151 151
         $order_id = EED_Module::getRequest()->getRequestParam('order_id');
152
-        if (! $order_id) {
152
+        if ( ! $order_id) {
153 153
             $error_message = esc_html__('Order ID missing.', 'event_espresso');
154 154
         }
155 155
         // Check for the payment nonce.
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
         $billing_info         = EED_Module::getRequest()->getRequestParam('billing_info');
163 163
         $billing_info_decoded = json_decode(stripslashes($billing_info), true);
164 164
         $billing_info         = is_array($billing_info_decoded) ? $billing_info_decoded : [];
165
-        if (! $billing_info) {
165
+        if ( ! $billing_info) {
166 166
             $error_message = esc_html__('Billing info missing.', 'event_espresso');
167 167
         }
168 168
         // We had an error. Log and EXIT.
@@ -197,7 +197,7 @@  discard block
 block discarded – undo
197 197
         EE_Payment_Method $paypal_pm
198 198
     ): array {
199 199
         $create_order_api = EED_PayPalCommerce::getCreateOrderApi($transaction, $billing_info, $paypal_pm);
200
-        if (! $create_order_api instanceof CreateOrder) {
200
+        if ( ! $create_order_api instanceof CreateOrder) {
201 201
             return [
202 202
                 'error'   => 'CREATE_ORDER_API_FAULT',
203 203
                 'message' => esc_html__('The Create Order API request fault.', 'event_espresso'),
@@ -236,7 +236,7 @@  discard block
 block discarded – undo
236 236
         array $billing_info
237 237
     ): array {
238 238
         $capture_order_api = EED_PayPalCommerce::getCaptureOrderApi($transaction, $paypal_pm, $order_id);
239
-        if (! $capture_order_api instanceof CaptureOrder) {
239
+        if ( ! $capture_order_api instanceof CaptureOrder) {
240 240
             return [
241 241
                 'error'   => 'CAPTURE_ORDER_API_FAULT',
242 242
                 'message' => esc_html__('A capture Order API request fault.', 'event_espresso'),
@@ -294,7 +294,7 @@  discard block
 block discarded – undo
294 294
         EE_Payment_Method $paypal_pm
295 295
     ): ?CreateOrder {
296 296
         $paypal_api = EED_PayPalCommerce::getPayPalApi($paypal_pm);
297
-        if (! $paypal_api instanceof PayPalApi) {
297
+        if ( ! $paypal_api instanceof PayPalApi) {
298 298
             return null;
299 299
         }
300 300
         return LoaderFactory::getNew(CreateOrder::class, [$paypal_api, $transaction, $billing_info]);
@@ -317,7 +317,7 @@  discard block
 block discarded – undo
317 317
         string $order_id
318 318
     ): ?CaptureOrder {
319 319
         $paypal_api = EED_PayPalCommerce::getPayPalApi($paypal_pm);
320
-        if (! $paypal_api instanceof PayPalApi) {
320
+        if ( ! $paypal_api instanceof PayPalApi) {
321 321
             return null;
322 322
         }
323 323
         return LoaderFactory::getNew(CaptureOrder::class, [$paypal_api, $transaction, $order_id]);
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
         }
344 344
         // Third party integration credentials:
345 345
         $access_token = EED_PayPalOnboard::getPartnerAccessToken($paypal_pm);
346
-        if (! $access_token || ! $bn_code) {
346
+        if ( ! $access_token || ! $bn_code) {
347 347
             return null;
348 348
         }
349 349
         $partner_client_id = PayPalExtraMetaManager::getPmOption($paypal_pm, Domain::META_KEY_PARTNER_CLIENT_ID) ?: '';
@@ -370,7 +370,7 @@  discard block
 block discarded – undo
370 370
     {
371 371
         $error      = ['error' => 'GET_CLIENT_TOKEN_FAULT'];
372 372
         $paypal_api = EED_PayPalCommerce::getPayPalApi($paypal_pm);
373
-        if (! $paypal_api instanceof PayPalApi) {
373
+        if ( ! $paypal_api instanceof PayPalApi) {
374 374
             $error['message'] = esc_html__('Got an error while trying to get the client token.', 'event_espresso');
375 375
             return $error;
376 376
         }
@@ -397,7 +397,7 @@  discard block
 block discarded – undo
397 397
         try {
398 398
             $txn_id      = EED_Module::getRequest()->getRequestParam('txn_id', 0, DataType::INT);
399 399
             $transaction = EEM_Transaction::instance()->get_one_by_ID($txn_id);
400
-            if (! $transaction instanceof EE_Transaction) {
400
+            if ( ! $transaction instanceof EE_Transaction) {
401 401
                 PayPalLogger::errorLog(
402 402
                     esc_html__('No transaction found by ID:', 'event_espresso'),
403 403
                     EED_Module::getRequest()->postParams()
@@ -422,8 +422,8 @@  discard block
 block discarded – undo
422 422
     public static function isThirdParty(EE_Payment_Method $paypal_pm): bool
423 423
     {
424 424
         $pp_meta_data = PayPalExtraMetaManager::getAllData($paypal_pm);
425
-        return ! empty($pp_meta_data[ Domain::META_KEY_SELLER_MERCHANT_ID ])
426
-            && ! empty($pp_meta_data[ Domain::META_KEY_ACCESS_TOKEN ]);
425
+        return ! empty($pp_meta_data[Domain::META_KEY_SELLER_MERCHANT_ID])
426
+            && ! empty($pp_meta_data[Domain::META_KEY_ACCESS_TOKEN]);
427 427
     }
428 428
 
429 429
 
@@ -485,7 +485,7 @@  discard block
 block discarded – undo
485 485
         foreach ($payment_methods as $key => $pm) {
486 486
             // It is a PayPal Commerce payment method. Check if it's connected. If not - remove from the list.
487 487
             if (str_contains($pm->slug(), Domain::PM_SLUG) && ! EED_PayPalOnboard::isOnboard($pm)) {
488
-                unset($payment_methods[ $key ]);
488
+                unset($payment_methods[$key]);
489 489
             }
490 490
         }
491 491
         return $payment_methods;
@@ -503,10 +503,10 @@  discard block
 block discarded – undo
503 503
     {
504 504
         $state_options = [];
505 505
         $states        = EEM_State::instance()->get_all_active_states();
506
-        if (! empty($states)) {
506
+        if ( ! empty($states)) {
507 507
             foreach ($states as $numeral => $state) {
508 508
                 if ($state instanceof EE_State) {
509
-                    $state_options[ $numeral ] = $state->abbrev();
509
+                    $state_options[$numeral] = $state->abbrev();
510 510
                 }
511 511
             }
512 512
         }
Please login to merge, or discard this patch.
PaymentMethods/PayPalCommerce/PayPalCheckout/EE_PMT_PayPalCheckout.pm.php 2 patches
Indentation   +169 added lines, -169 removed lines patch added patch discarded remove patch
@@ -16,186 +16,186 @@
 block discarded – undo
16 16
  */
17 17
 class EE_PMT_PayPalCheckout extends EE_PMT_Base
18 18
 {
19
-    /**
20
-     * @param EE_Payment_Method|null $pm_instance
21
-     * @throws ReflectionException
22
-     * @throws EE_Error
23
-     */
24
-    public function __construct($pm_instance = null)
25
-    {
26
-        $this->_template_path       = dirname(__FILE__) . DS . 'templates' . DS;
27
-        $this->_default_description = esc_html__('Please provide the following billing information.', 'event_espresso');
28
-        $this->_default_button_url  = $this->file_url() . 'lib/default-cc-logo.png';
29
-        $this->_pretty_name         = esc_html__('PayPal Commerce', 'event_espresso');
30
-        $this->_cache_billing_form  = true;
31
-        $this->_requires_https      = true;
19
+	/**
20
+	 * @param EE_Payment_Method|null $pm_instance
21
+	 * @throws ReflectionException
22
+	 * @throws EE_Error
23
+	 */
24
+	public function __construct($pm_instance = null)
25
+	{
26
+		$this->_template_path       = dirname(__FILE__) . DS . 'templates' . DS;
27
+		$this->_default_description = esc_html__('Please provide the following billing information.', 'event_espresso');
28
+		$this->_default_button_url  = $this->file_url() . 'lib/default-cc-logo.png';
29
+		$this->_pretty_name         = esc_html__('PayPal Commerce', 'event_espresso');
30
+		$this->_cache_billing_form  = true;
31
+		$this->_requires_https      = true;
32 32
 
33
-        // Load gateway.
34
-        require_once(
35
-            EEP_PAYPAL_COMMERCE_PATH . 'EEG_PayPalCheckout.gateway.php'
36
-        );
37
-        $this->_gateway = new EEG_PayPalCheckout();
33
+		// Load gateway.
34
+		require_once(
35
+			EEP_PAYPAL_COMMERCE_PATH . 'EEG_PayPalCheckout.gateway.php'
36
+		);
37
+		$this->_gateway = new EEG_PayPalCheckout();
38 38
 
39
-        // Display a refund message at transactions actions area.
40
-        add_action(
41
-            'AHEE__txn_admin_details_main_meta_box_txn_details__after_actions_buttons',
42
-            [__CLASS__, 'refundNotice']
43
-        );
39
+		// Display a refund message at transactions actions area.
40
+		add_action(
41
+			'AHEE__txn_admin_details_main_meta_box_txn_details__after_actions_buttons',
42
+			[__CLASS__, 'refundNotice']
43
+		);
44 44
 
45
-        parent::__construct($pm_instance);
46
-    }
45
+		parent::__construct($pm_instance);
46
+	}
47 47
 
48 48
 
49
-    /**
50
-     * Generate a new payment method settings form.
51
-     *
52
-     * @return EE_Payment_Method_Form
53
-     * @throws EE_Error
54
-     * @throws ReflectionException
55
-     */
56
-    public function generate_new_settings_form()
57
-    {
58
-        // Settings form.
59
-        $settings_form = new SettingsForm($this, $this->_pm_instance);
60
-        // Filter the form contents.
61
-        return apply_filters(
62
-            'FHEE__EE_PMT_PayPalCheckout__generate_new_settings_form__form_filtering',
63
-            $settings_form,
64
-            $this,
65
-            $this->_pm_instance
66
-        );
67
-    }
49
+	/**
50
+	 * Generate a new payment method settings form.
51
+	 *
52
+	 * @return EE_Payment_Method_Form
53
+	 * @throws EE_Error
54
+	 * @throws ReflectionException
55
+	 */
56
+	public function generate_new_settings_form()
57
+	{
58
+		// Settings form.
59
+		$settings_form = new SettingsForm($this, $this->_pm_instance);
60
+		// Filter the form contents.
61
+		return apply_filters(
62
+			'FHEE__EE_PMT_PayPalCheckout__generate_new_settings_form__form_filtering',
63
+			$settings_form,
64
+			$this,
65
+			$this->_pm_instance
66
+		);
67
+	}
68 68
 
69 69
 
70
-    /**
71
-     * Creates a billing form for this payment method type.
72
-     *
73
-     * @param EE_Transaction|null $transaction
74
-     * @param array|null          $extra_args
75
-     * @return EE_Billing_Info_Form|null
76
-     * @throws EE_Error
77
-     * @throws ReflectionException
78
-     */
79
-    public function generate_new_billing_form(EE_Transaction $transaction = null, ?array $extra_args = [])
80
-    {
81
-        $request        = LoaderFactory::getShared(Request::class);
82
-        $request_params = $request->requestParams();
83
-        // Return the default billing form for the postbox if this is a WP admin transaction info page.
84
-        if (! empty($request_params['page']) && $request_params['page'] === 'espresso_transactions') {
85
-            $default_form = new EE_Billing_Attendee_Info_Form($this->_pm_instance, $extra_args);
86
-            $default_form->add_subsections(['credit_card' => new EE_Credit_Card_Input()]);
87
-            return $default_form;
88
-        }
89
-        // Just in case this is used on other admin pages.
90
-        if (empty($transaction) && ! empty($request_params['TXN_ID'])) {
91
-            $txn_instance = EEM_Transaction::instance()->get_one_by_ID($request_params['TXN_ID']);
92
-            $transaction  = $txn_instance instanceof EE_Transaction ? $txn_instance : null;
93
-        }
94
-        $options = array_merge(
95
-            [
96
-                'transaction'   => $transaction,
97
-                'template_path' => $this->_template_path,
98
-            ],
99
-            $extra_args
100
-        );
101
-        return LoaderFactory::getNew(BillingForm::class, [$this->_pm_instance, $options]);
102
-    }
70
+	/**
71
+	 * Creates a billing form for this payment method type.
72
+	 *
73
+	 * @param EE_Transaction|null $transaction
74
+	 * @param array|null          $extra_args
75
+	 * @return EE_Billing_Info_Form|null
76
+	 * @throws EE_Error
77
+	 * @throws ReflectionException
78
+	 */
79
+	public function generate_new_billing_form(EE_Transaction $transaction = null, ?array $extra_args = [])
80
+	{
81
+		$request        = LoaderFactory::getShared(Request::class);
82
+		$request_params = $request->requestParams();
83
+		// Return the default billing form for the postbox if this is a WP admin transaction info page.
84
+		if (! empty($request_params['page']) && $request_params['page'] === 'espresso_transactions') {
85
+			$default_form = new EE_Billing_Attendee_Info_Form($this->_pm_instance, $extra_args);
86
+			$default_form->add_subsections(['credit_card' => new EE_Credit_Card_Input()]);
87
+			return $default_form;
88
+		}
89
+		// Just in case this is used on other admin pages.
90
+		if (empty($transaction) && ! empty($request_params['TXN_ID'])) {
91
+			$txn_instance = EEM_Transaction::instance()->get_one_by_ID($request_params['TXN_ID']);
92
+			$transaction  = $txn_instance instanceof EE_Transaction ? $txn_instance : null;
93
+		}
94
+		$options = array_merge(
95
+			[
96
+				'transaction'   => $transaction,
97
+				'template_path' => $this->_template_path,
98
+			],
99
+			$extra_args
100
+		);
101
+		return LoaderFactory::getNew(BillingForm::class, [$this->_pm_instance, $options]);
102
+	}
103 103
 
104 104
 
105
-    /**
106
-     * Adds PM info to the help tab.
107
-     *
108
-     * @return array
109
-     * @see EE_PMT_Base::help_tabs_config()
110
-     */
111
-    public function help_tabs_config(): array
112
-    {
113
-        return [
114
-            $this->get_help_tab_name() => [
115
-                'title'    => esc_html__('PayPal Commerce settings', 'event_espresso'),
116
-                'filename' => 'pp-commerce-overview',
117
-            ],
118
-        ];
119
-    }
105
+	/**
106
+	 * Adds PM info to the help tab.
107
+	 *
108
+	 * @return array
109
+	 * @see EE_PMT_Base::help_tabs_config()
110
+	 */
111
+	public function help_tabs_config(): array
112
+	{
113
+		return [
114
+			$this->get_help_tab_name() => [
115
+				'title'    => esc_html__('PayPal Commerce settings', 'event_espresso'),
116
+				'filename' => 'pp-commerce-overview',
117
+			],
118
+		];
119
+	}
120 120
 
121 121
 
122
-    /**
123
-     * Adds a refund related message section.
124
-     *
125
-     * @param bool $can_edit_payments Flag that tells if user can edit payments.
126
-     * @access public
127
-     * @return void
128
-     */
129
-    public static function refundNotice(bool $can_edit_payments)
130
-    {
131
-        if (! $can_edit_payments) {
132
-            return;
133
-        }
134
-        $request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
135
-        $txn_id  = $request->getRequestParam('TXN_ID', 0, DataType::INT);
136
-        try {
137
-            $transaction = EEM_Transaction::instance()->get_one_by_ID($txn_id);
138
-            if (! $transaction instanceof EE_Transaction) {
139
-                return;
140
-            }
141
-            // Was this transaction paid using PayPal ?
142
-            if (strpos((string) $transaction->payment_method(), 'PayPal Commerce') === false) {
143
-                return;
144
-            }
145
-            // Try loading the template.
146
-            EE_Registry::instance()->load_helper('Template');
147
-        } catch (EE_Error | ReflectionException $e) {
148
-            // Just return, adding nothing.
149
-            return;
150
-        }
151
-        $html = EEH_Template::locate_template(
152
-            apply_filters(
153
-                'FHEEA__EE_PMT_PayPalCheckout__refundNotice',
154
-                dirname(__FILE__) . DS . 'templates' . DS . 'apply-refund-notice.template.php'
155
-            )
156
-        );
157
-        echo $html;
158
-    }
122
+	/**
123
+	 * Adds a refund related message section.
124
+	 *
125
+	 * @param bool $can_edit_payments Flag that tells if user can edit payments.
126
+	 * @access public
127
+	 * @return void
128
+	 */
129
+	public static function refundNotice(bool $can_edit_payments)
130
+	{
131
+		if (! $can_edit_payments) {
132
+			return;
133
+		}
134
+		$request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
135
+		$txn_id  = $request->getRequestParam('TXN_ID', 0, DataType::INT);
136
+		try {
137
+			$transaction = EEM_Transaction::instance()->get_one_by_ID($txn_id);
138
+			if (! $transaction instanceof EE_Transaction) {
139
+				return;
140
+			}
141
+			// Was this transaction paid using PayPal ?
142
+			if (strpos((string) $transaction->payment_method(), 'PayPal Commerce') === false) {
143
+				return;
144
+			}
145
+			// Try loading the template.
146
+			EE_Registry::instance()->load_helper('Template');
147
+		} catch (EE_Error | ReflectionException $e) {
148
+			// Just return, adding nothing.
149
+			return;
150
+		}
151
+		$html = EEH_Template::locate_template(
152
+			apply_filters(
153
+				'FHEEA__EE_PMT_PayPalCheckout__refundNotice',
154
+				dirname(__FILE__) . DS . 'templates' . DS . 'apply-refund-notice.template.php'
155
+			)
156
+		);
157
+		echo $html;
158
+	}
159 159
 
160 160
 
161
-    /**
162
-     * Override the parent.
163
-     *
164
-     * @param EE_Transaction            $transaction
165
-     * @param float|null                $amount
166
-     * @param EE_Billing_Info_Form|null $billing_info
167
-     * @param string|null               $return_url
168
-     * @param string                    $fail_url
169
-     * @param string                    $method
170
-     * @param bool                      $by_admin
171
-     * @return EE_Payment
172
-     * @throws EE_Error
173
-     * @throws ReflectionException
174
-     */
175
-    public function process_payment(
176
-        EE_Transaction $transaction,
177
-        $amount = null,
178
-        $billing_info = null,
179
-        $return_url = null,
180
-        $fail_url = '',
181
-        $method = 'CART',
182
-        $by_admin = false
183
-    ): EE_Payment {
184
-        // This payment should have been processed in the background, while the Order was created and charged.
185
-        // So simply return the last payment. Unless it's somehow missing.
186
-        $payment = $transaction->last_payment();
187
-        if (empty($payment) || $payment->status() === EEM_Payment::status_id_failed) {
188
-            // Then we try processing the payment as usual.
189
-            return parent::process_payment(
190
-                $transaction,
191
-                $amount,
192
-                $billing_info,
193
-                $return_url,
194
-                $fail_url,
195
-                $method,
196
-                $by_admin
197
-            );
198
-        }
199
-        return $transaction->last_payment();
200
-    }
161
+	/**
162
+	 * Override the parent.
163
+	 *
164
+	 * @param EE_Transaction            $transaction
165
+	 * @param float|null                $amount
166
+	 * @param EE_Billing_Info_Form|null $billing_info
167
+	 * @param string|null               $return_url
168
+	 * @param string                    $fail_url
169
+	 * @param string                    $method
170
+	 * @param bool                      $by_admin
171
+	 * @return EE_Payment
172
+	 * @throws EE_Error
173
+	 * @throws ReflectionException
174
+	 */
175
+	public function process_payment(
176
+		EE_Transaction $transaction,
177
+		$amount = null,
178
+		$billing_info = null,
179
+		$return_url = null,
180
+		$fail_url = '',
181
+		$method = 'CART',
182
+		$by_admin = false
183
+	): EE_Payment {
184
+		// This payment should have been processed in the background, while the Order was created and charged.
185
+		// So simply return the last payment. Unless it's somehow missing.
186
+		$payment = $transaction->last_payment();
187
+		if (empty($payment) || $payment->status() === EEM_Payment::status_id_failed) {
188
+			// Then we try processing the payment as usual.
189
+			return parent::process_payment(
190
+				$transaction,
191
+				$amount,
192
+				$billing_info,
193
+				$return_url,
194
+				$fail_url,
195
+				$method,
196
+				$by_admin
197
+			);
198
+		}
199
+		return $transaction->last_payment();
200
+	}
201 201
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -23,16 +23,16 @@  discard block
 block discarded – undo
23 23
      */
24 24
     public function __construct($pm_instance = null)
25 25
     {
26
-        $this->_template_path       = dirname(__FILE__) . DS . 'templates' . DS;
26
+        $this->_template_path       = dirname(__FILE__).DS.'templates'.DS;
27 27
         $this->_default_description = esc_html__('Please provide the following billing information.', 'event_espresso');
28
-        $this->_default_button_url  = $this->file_url() . 'lib/default-cc-logo.png';
28
+        $this->_default_button_url  = $this->file_url().'lib/default-cc-logo.png';
29 29
         $this->_pretty_name         = esc_html__('PayPal Commerce', 'event_espresso');
30 30
         $this->_cache_billing_form  = true;
31 31
         $this->_requires_https      = true;
32 32
 
33 33
         // Load gateway.
34 34
         require_once(
35
-            EEP_PAYPAL_COMMERCE_PATH . 'EEG_PayPalCheckout.gateway.php'
35
+            EEP_PAYPAL_COMMERCE_PATH.'EEG_PayPalCheckout.gateway.php'
36 36
         );
37 37
         $this->_gateway = new EEG_PayPalCheckout();
38 38
 
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
         $request        = LoaderFactory::getShared(Request::class);
82 82
         $request_params = $request->requestParams();
83 83
         // Return the default billing form for the postbox if this is a WP admin transaction info page.
84
-        if (! empty($request_params['page']) && $request_params['page'] === 'espresso_transactions') {
84
+        if ( ! empty($request_params['page']) && $request_params['page'] === 'espresso_transactions') {
85 85
             $default_form = new EE_Billing_Attendee_Info_Form($this->_pm_instance, $extra_args);
86 86
             $default_form->add_subsections(['credit_card' => new EE_Credit_Card_Input()]);
87 87
             return $default_form;
@@ -128,14 +128,14 @@  discard block
 block discarded – undo
128 128
      */
129 129
     public static function refundNotice(bool $can_edit_payments)
130 130
     {
131
-        if (! $can_edit_payments) {
131
+        if ( ! $can_edit_payments) {
132 132
             return;
133 133
         }
134 134
         $request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
135 135
         $txn_id  = $request->getRequestParam('TXN_ID', 0, DataType::INT);
136 136
         try {
137 137
             $transaction = EEM_Transaction::instance()->get_one_by_ID($txn_id);
138
-            if (! $transaction instanceof EE_Transaction) {
138
+            if ( ! $transaction instanceof EE_Transaction) {
139 139
                 return;
140 140
             }
141 141
             // Was this transaction paid using PayPal ?
@@ -151,7 +151,7 @@  discard block
 block discarded – undo
151 151
         $html = EEH_Template::locate_template(
152 152
             apply_filters(
153 153
                 'FHEEA__EE_PMT_PayPalCheckout__refundNotice',
154
-                dirname(__FILE__) . DS . 'templates' . DS . 'apply-refund-notice.template.php'
154
+                dirname(__FILE__).DS.'templates'.DS.'apply-refund-notice.template.php'
155 155
             )
156 156
         );
157 157
         echo $html;
Please login to merge, or discard this patch.
PaymentMethods/PayPalCommerce/PayPalCheckout/forms/OnboardingFormHtml.php 2 patches
Indentation   +446 added lines, -446 removed lines patch added patch discarded remove patch
@@ -27,450 +27,450 @@
 block discarded – undo
27 27
  */
28 28
 class OnboardingFormHtml
29 29
 {
30
-    /**
31
-     *  Payment method.
32
-     *
33
-     * @var EE_PMT_Base
34
-     */
35
-    protected $payment_method = null;
36
-
37
-    /**
38
-     *  Payment method instance.
39
-     *
40
-     * @var EE_PMT_Base
41
-     */
42
-    protected $pm_instance = null;
43
-
44
-    /**
45
-     *  Payment method slug.
46
-     *
47
-     * @var EE_PMT_Base
48
-     */
49
-    protected $pm_slug = null;
50
-
51
-    /**
52
-     *  PayPal Onboarding button text.
53
-     *
54
-     * @var string
55
-     */
56
-    public $onboard_btn_text = '';
57
-
58
-    /**
59
-     *  PayPal Onboarding button in sandbox mode text.
60
-     *
61
-     * @var string
62
-     */
63
-    public $sandbox_btn_text = '';
64
-
65
-    /**
66
-     *  PayPal Onboarding section sandbox mode text.
67
-     *
68
-     * @var string
69
-     */
70
-    public $authed_sandbox_text = '';
71
-
72
-
73
-    /**
74
-     * Class constructor.
75
-     *
76
-     * @param EE_PMT_Base       $pmt
77
-     * @param EE_Payment_Method $payment_method
78
-     */
79
-    public function __construct(EE_PMT_Base $pmt, EE_Payment_Method $payment_method)
80
-    {
81
-        $this->payment_method      = $pmt;
82
-        $this->pm_instance         = $payment_method;
83
-        $this->pm_slug             = $this->pm_instance->slug();
84
-        $this->onboard_btn_text    = esc_html__('Connect with PayPal', 'event_espresso');
85
-        $this->sandbox_btn_text    = esc_html__('Connect with PayPal (sandbox)', 'event_espresso');
86
-        $this->authed_sandbox_text = esc_html__('(using sandbox credentials)', 'event_espresso');
87
-    }
88
-
89
-
90
-    /**
91
-     * Form a heading.
92
-     *
93
-     * @param string $text
94
-     * @return string
95
-     */
96
-    public function getHeader(string $text = ''): string
97
-    {
98
-        $text = $text ?: esc_html__('PayPal Onboarding: %1$s', 'event_espresso');
99
-        return EEH_HTML::th(
100
-            sprintf(
101
-                $text,
102
-                $this->payment_method->get_help_tab_link()
103
-            ),
104
-            'eea_paypal_onboard_heading_' . $this->pm_slug,
105
-            'eea-paypal-onboard-heading'
106
-        );
107
-    }
108
-
109
-
110
-    /**
111
-     * Add the onboarding button.
112
-     *
113
-     * @param array $subsections
114
-     * @param bool  $is_onboard
115
-     * @return array
116
-     */
117
-    public function addOnboardButton(array $subsections, bool $is_onboard): array
118
-    {
119
-        // Section to be displayed if not onboard.
120
-        $subsections['paypal_onboard_btn'] = new EE_Form_Section_HTML(
121
-            EEH_HTML::tr(
122
-                $this->getHeader() .
123
-                EEH_HTML::td(
124
-                    EEH_HTML::button(
125
-                        $this->onboard_btn_text,
126
-                        'eea-paypal-onboard-btn button button--primary',
127
-                        '',
128
-                        'eea_paypal_onboard_btn_' . $this->pm_slug,
129
-                    )
130
-                    . EEH_HTML::link(
131
-                        '#',
132
-                        '',
133
-                        '',
134
-                        'eea_paypal_onboard_trigger_btn_' . $this->pm_slug,
135
-                        'eea-paypal-onboard-trigger-btn',
136
-                        '',
137
-                        'data-ee-pm-slug="' . $this->pm_slug . '" data-paypal-button="true"'
138
-                    )
139
-                ),
140
-                'eea_paypal_onboard_section_' . $this->pm_slug,
141
-                'eea-onboard-section eea-onboard-section-' . $this->pm_slug,
142
-                // Are we onboard ?
143
-                $is_onboard ? 'display:none;' : ''
144
-            ),
145
-            ['required' => true]
146
-        );
147
-        return $subsections;
148
-    }
149
-
150
-
151
-    /**
152
-     * Add the offboarding (deauthorize) button.
153
-     *
154
-     * @param array $subsections
155
-     * @param bool  $is_onboard
156
-     * @return array
157
-     */
158
-    public function addOffboardButton(array $subsections, bool $is_onboard): array
159
-    {
160
-        $onboard_sandbox_section = $this->getOnboardSandboxSection();
161
-        // If we are connected, display the seller merchant ID.
162
-        $seller_id_section = $this->getSellerIdSection();
163
-        // Section to be displayed when onboard.
164
-        $subsections['paypal_offboard_btn'] = new EE_Form_Section_HTML(
165
-            EEH_HTML::tr(
166
-                $this->getHeader()
167
-                . EEH_HTML::td(
168
-                    EEH_HTML::img(
169
-                        EEP_PAYPAL_COMMERCE_URL . 'assets' . DS . 'lib' . DS . 'paypal-onboard.png',
170
-                        '',
171
-                        'eea_paypal_offboard_ico',
172
-                        'eea-paypal-offboard-ico'
173
-                    )
174
-                    . EEH_HTML::strong(
175
-                        esc_html__('Connected.', 'event_espresso'),
176
-                        'eea_paypal_offboard_txt_' . $this->pm_slug,
177
-                        'eea-paypal-offboard-txt'
178
-                    )
179
-                    . $onboard_sandbox_section
180
-                    . $seller_id_section
181
-                    . EEH_HTML::link(
182
-                        '#',
183
-                        EEH_HTML::span(esc_html__('Disconnect', 'event_espresso')),
184
-                        '',
185
-                        'eea_paypal_offboard_btn_' . $this->pm_slug,
186
-                        'eea-paypal-onboard-btn button button--primary'
187
-                    )
188
-                ),
189
-                'eea_paypal_offboard_section_' . $this->pm_slug,
190
-                'eea-offboard-section-' . $this->pm_slug,
191
-                // Are we onboard ?
192
-                ! $is_onboard ? 'display:none;' : ''
193
-            ),
194
-            ['required' => true]
195
-        );
196
-        return $subsections;
197
-    }
198
-
199
-
200
-    /**
201
-     * Get the sandbox onboarding section contents.
202
-     *
203
-     * @return string
204
-     */
205
-    public function getOnboardSandboxSection(): string
206
-    {
207
-        // Is this a test onboarding ?
208
-        $sandbox_mode_text = $this->pm_instance->debug_mode() ? $this->authed_sandbox_text : '';
209
-        return ' ' . EEH_HTML::strong(
210
-            $sandbox_mode_text,
211
-            'eea_paypal_onboard_test_txt_' . $this->pm_slug,
212
-            'eea-paypal-onboard-test-txt'
213
-        );
214
-    }
215
-
216
-
217
-    /**
218
-     * Get the seller merchant ID section contents.
219
-     *
220
-     * @return string
221
-     */
222
-    public function getSellerIdSection(): string
223
-    {
224
-        try {
225
-            $is_third_party = EED_PayPalCommerce::isThirdParty($this->pm_instance);
226
-            $meta_key       = $is_third_party ? Domain::META_KEY_SELLER_MERCHANT_ID : Domain::META_KEY_PAYER_ID;
227
-            $payer_id       = PayPalExtraMetaManager::getPmOption($this->pm_instance, $meta_key) ?: '--';
228
-        } catch (Exception $e) {
229
-            $payer_id = '--';
230
-        }
231
-        return ' ' . EEH_HTML::strong(
232
-            sprintf(esc_html__('Linked account ID: %1$s', 'event_espresso'), $payer_id),
233
-            'eea_paypal_seller_id_' . $this->pm_slug,
234
-            'eea-paypal-seller-id'
235
-        );
236
-    }
237
-
238
-
239
-    /**
240
-     * Add the PM slug holder.
241
-     *
242
-     * @param array $subsections
243
-     * @return array
244
-     */
245
-    public function addPmSlugHolder(array $subsections): array
246
-    {
247
-        $subsections['paypal_pm_slug_holder'] = new EE_Form_Section_HTML(
248
-            EEH_HTML::span(
249
-                '',
250
-                'eea_paypal_pm_slug',
251
-                'eea-paypal-pm-slug',
252
-                'display:none;'
253
-            )
254
-        );
255
-        return $subsections;
256
-    }
257
-
258
-
259
-    /**
260
-     * HTML for onboarding settings dialog.
261
-     *
262
-     * @return EE_Form_Section_Base
263
-     */
264
-    public function connectDialog(): EE_Form_Section_Base
265
-    {
266
-        return new EE_Form_Section_HTML(
267
-            EEH_HTML::div(
268
-                $this->countriesSelectHtml() .
269
-                $this->paymentOptionsHtml() .
270
-                EEH_HTML::div(
271
-                    EEH_HTML::link(
272
-                        '',
273
-                        'Cancel',
274
-                        'cancel, go back',
275
-                        'eea_ppc_connect_cancel_' . $this->pm_slug,
276
-                        'eea-ppc-connect-cancel button button--secondary'
277
-                    ) .
278
-                    EEH_HTML::link(
279
-                        '',
280
-                        'Continue',
281
-                        'ok, continue',
282
-                        'eea_ppc_connect_ok_' . $this->pm_slug,
283
-                        'eea-ppc-connect-ok button button--primary-alt'
284
-                    ),
285
-                    '',
286
-                    'eep-ppc-dialog-yes-no'
287
-                ),
288
-                'eea_paypal_connect_dialog_' . $this->pm_slug
289
-            )
290
-        );
291
-    }
292
-
293
-
294
-    /**
295
-     * Form a countries select and return as html.
296
-     *
297
-     * @return string
298
-     */
299
-    public function countriesSelectHtml(): string
300
-    {
301
-        $countries = [];
302
-        $countries_select = EEH_HTML::strong(
303
-            esc_html__('Please select a country where your PayPal account is registered:', 'event_espresso'),
304
-            'eep_ppc_country_txt_' . $this->pm_slug,
305
-            'eep-ppc-country-txt'
306
-        );
307
-        try {
308
-            // Get all countries list.
309
-            $countries_iso = EEM_Country::instance()->get_all_countries();
310
-            foreach ($countries_iso as $iso => $country) {
311
-                if ($country instanceof EE_Country) {
312
-                    $countries [ $iso ] = $country->get('CNT_name');
313
-                }
314
-            }
315
-            // Now build the select input.
316
-            $select_input = new EE_Select_Input(
317
-                $countries,
318
-                [
319
-                    'html_name'       => 'eep_ppc_country_' . $this->pm_slug,
320
-                    'html_id'         => 'eep_ppc_country_' . $this->pm_slug,
321
-                    'html_class'      => 'eep-ppc-country-' . $this->pm_slug,
322
-                    'html_label_text' => esc_html__('Select country', 'event_espresso'),
323
-                    'required'        => true,
324
-                    'default'         => EE_Config::instance()->organization->CNT_ISO ?? 'US'
325
-                ]
326
-            );
327
-            $countries_select .= $select_input->get_html_for_input();
328
-        } catch (Exception $e) {
329
-            // Countries list set at this point, so just continue.
330
-        }
331
-        return $countries_select;
332
-    }
333
-
334
-
335
-    /**
336
-     * Form the payment options checkboxes and return as html.
337
-     *
338
-     * @return string
339
-     */
340
-    public function paymentOptionsHtml(): string
341
-    {
342
-        $options_lbl = EEH_HTML::strong(
343
-            esc_html__('Select a product you\'d like to allow at checkout:', 'event_espresso'),
344
-            'eea_ppc_product_txt_' . $this->pm_slug,
345
-            'eea-ppc-product-txt'
346
-        );
347
-        $express_checkout_lbl = EEH_HTML::label(
348
-            esc_html__('Accept PayPal ', 'event_espresso')
349
-            . EEH_HTML::img(
350
-                'https://www.paypalobjects.com/webstatic/mktg/Logo/pp-logo-100px.png',
351
-                '',
352
-                'eea_ppc_express_checkout_img_' . $this->pm_slug,
353
-                'eea-ppc-express-checkout-img'
354
-            ),
355
-            '',
356
-            '',
357
-            '',
358
-            'for="' . 'eep_ppc_checkout_type_' . $this->pm_slug . '-express_checkout"'
359
-        );
360
-        $ppcp_lbl = EEH_HTML::label(
361
-            esc_html__('Accept credit and debit card payments with PayPal ', 'event_espresso')
362
-            . EEH_HTML::img(
363
-                'https://www.paypalobjects.com/digitalassets/c/website/marketing/apac/C2/logos-buttons/optimize/Full_Online_Tray_RGB.png',
364
-                '',
365
-                'eea_ppc_ppcp_img_' . $this->pm_slug,
366
-                'eea-ppc-ppcp-img'
367
-            ),
368
-            '',
369
-            '',
370
-            '',
371
-            'for="' . 'eep_ppc_checkout_type_' . $this->pm_slug . '-ppcp"'
372
-        );
373
-        $checkbox = new EE_Checkbox_Multi_Input(
374
-            [
375
-                'express_checkout' => $express_checkout_lbl,
376
-                'ppcp'             => $ppcp_lbl,
377
-            ],
378
-            [
379
-                'html_id'         => 'eep_ppc_checkout_type_' . $this->pm_slug,
380
-                'html_label_text' => esc_html__(
381
-                    'Select a product you\'d like to allow at checkout.',
382
-                    'event_espresso'
383
-                ),
384
-                'html_help_text'  => esc_html__(
385
-                    'Select a product you\'d like to allow at checkout.',
386
-                    'event_espresso'
387
-                ),
388
-                'default'         => ['express_checkout', 'ppcp']
389
-            ]
390
-        );
391
-        try {
392
-            return EEH_HTML::div(
393
-                $options_lbl
394
-                . $checkbox->get_html_for_input(),
395
-                'eep_ppc_checkout_types_' . $this->pm_slug,
396
-                'eep-ppc-checkout-types'
397
-            );
398
-        } catch (Exception $e) {
399
-            return '';
400
-        }
401
-    }
402
-
403
-
404
-    /**
405
-     * HTML for onboarding settings dialog.
406
-     *
407
-     * @return EE_Form_Section_Base
408
-     */
409
-    public function processingMask(): EE_Form_Section_Base
410
-    {
411
-        return new EE_Form_Section_HTML(
412
-            EEH_HTML::div(
413
-                EEH_HTML::div(' ', 'eep_ppc_processing_mask', 'eep-ppc-processing-mask') .
414
-                EEH_HTML::div(' ', 'eep_ppc_processing_spinner', 'ee-spinner ee-spin') .
415
-                EEH_HTML::div(
416
-                    esc_html__('The login window should be open. If you don\'t see a new PayPal login window you might need to enable pop-ups in your browser in order to continue.') .
417
-                    EEH_HTML::div(
418
-                        EEH_HTML::link(
419
-                            '#',
420
-                            esc_html__('Focus window'),
421
-                            esc_html__('Focus window'),
422
-                            'eep_ppc_window_focus_' . $this->pm_slug,
423
-                            'eep-ppc-window-focus'
424
-                        )
425
-                    ),
426
-                    'eep_ppc_processing_message',
427
-                    'eep-ppc-processing-message'
428
-                ),
429
-                'eep_ppc_processing_' . $this->pm_slug,
430
-                'eep-ppc-processing'
431
-            )
432
-        );
433
-    }
434
-
435
-
436
-    /**
437
-     * HTML for the disconnect warning dialog.
438
-     *
439
-     * @return EE_Form_Section_Base
440
-     */
441
-    public function disconnectDialog(): EE_Form_Section_Base
442
-    {
443
-        $message = esc_html__(
444
-            'Disconnecting your PayPal account will prevent you from offering PayPal services and products on your website.',
445
-            'event_espresso'
446
-        );
447
-        return new EE_Form_Section_HTML(
448
-            EEH_HTML::div(
449
-                EEH_HTML::strong(
450
-                    $message,
451
-                    'eep_ppc_disconnect_dialog_txt_' . $this->pm_slug,
452
-                    'eep-ppc-disconnect-dialog-txt'
453
-                ) .
454
-                EEH_HTML::div(
455
-                    EEH_HTML::link(
456
-                        '',
457
-                        'Cancel',
458
-                        'cancel, go back',
459
-                        'eep_ppc_disconnect_cancel_' . $this->pm_slug,
460
-                        'eep-ppc-disconnect-cancel button button--secondary'
461
-                    ) .
462
-                    EEH_HTML::link(
463
-                        '',
464
-                        'Disconnect',
465
-                        'ok, continue',
466
-                        'eep_ppc_disconnect_ok_' . $this->pm_slug,
467
-                        'eep-ppc-disconnect-ok button button--primary-alt'
468
-                    ),
469
-                    '',
470
-                    'eep-ppc-dialog-yes-no'
471
-                ),
472
-                'eep_paypal_disconnect_dialog_' . $this->pm_slug
473
-            )
474
-        );
475
-    }
30
+	/**
31
+	 *  Payment method.
32
+	 *
33
+	 * @var EE_PMT_Base
34
+	 */
35
+	protected $payment_method = null;
36
+
37
+	/**
38
+	 *  Payment method instance.
39
+	 *
40
+	 * @var EE_PMT_Base
41
+	 */
42
+	protected $pm_instance = null;
43
+
44
+	/**
45
+	 *  Payment method slug.
46
+	 *
47
+	 * @var EE_PMT_Base
48
+	 */
49
+	protected $pm_slug = null;
50
+
51
+	/**
52
+	 *  PayPal Onboarding button text.
53
+	 *
54
+	 * @var string
55
+	 */
56
+	public $onboard_btn_text = '';
57
+
58
+	/**
59
+	 *  PayPal Onboarding button in sandbox mode text.
60
+	 *
61
+	 * @var string
62
+	 */
63
+	public $sandbox_btn_text = '';
64
+
65
+	/**
66
+	 *  PayPal Onboarding section sandbox mode text.
67
+	 *
68
+	 * @var string
69
+	 */
70
+	public $authed_sandbox_text = '';
71
+
72
+
73
+	/**
74
+	 * Class constructor.
75
+	 *
76
+	 * @param EE_PMT_Base       $pmt
77
+	 * @param EE_Payment_Method $payment_method
78
+	 */
79
+	public function __construct(EE_PMT_Base $pmt, EE_Payment_Method $payment_method)
80
+	{
81
+		$this->payment_method      = $pmt;
82
+		$this->pm_instance         = $payment_method;
83
+		$this->pm_slug             = $this->pm_instance->slug();
84
+		$this->onboard_btn_text    = esc_html__('Connect with PayPal', 'event_espresso');
85
+		$this->sandbox_btn_text    = esc_html__('Connect with PayPal (sandbox)', 'event_espresso');
86
+		$this->authed_sandbox_text = esc_html__('(using sandbox credentials)', 'event_espresso');
87
+	}
88
+
89
+
90
+	/**
91
+	 * Form a heading.
92
+	 *
93
+	 * @param string $text
94
+	 * @return string
95
+	 */
96
+	public function getHeader(string $text = ''): string
97
+	{
98
+		$text = $text ?: esc_html__('PayPal Onboarding: %1$s', 'event_espresso');
99
+		return EEH_HTML::th(
100
+			sprintf(
101
+				$text,
102
+				$this->payment_method->get_help_tab_link()
103
+			),
104
+			'eea_paypal_onboard_heading_' . $this->pm_slug,
105
+			'eea-paypal-onboard-heading'
106
+		);
107
+	}
108
+
109
+
110
+	/**
111
+	 * Add the onboarding button.
112
+	 *
113
+	 * @param array $subsections
114
+	 * @param bool  $is_onboard
115
+	 * @return array
116
+	 */
117
+	public function addOnboardButton(array $subsections, bool $is_onboard): array
118
+	{
119
+		// Section to be displayed if not onboard.
120
+		$subsections['paypal_onboard_btn'] = new EE_Form_Section_HTML(
121
+			EEH_HTML::tr(
122
+				$this->getHeader() .
123
+				EEH_HTML::td(
124
+					EEH_HTML::button(
125
+						$this->onboard_btn_text,
126
+						'eea-paypal-onboard-btn button button--primary',
127
+						'',
128
+						'eea_paypal_onboard_btn_' . $this->pm_slug,
129
+					)
130
+					. EEH_HTML::link(
131
+						'#',
132
+						'',
133
+						'',
134
+						'eea_paypal_onboard_trigger_btn_' . $this->pm_slug,
135
+						'eea-paypal-onboard-trigger-btn',
136
+						'',
137
+						'data-ee-pm-slug="' . $this->pm_slug . '" data-paypal-button="true"'
138
+					)
139
+				),
140
+				'eea_paypal_onboard_section_' . $this->pm_slug,
141
+				'eea-onboard-section eea-onboard-section-' . $this->pm_slug,
142
+				// Are we onboard ?
143
+				$is_onboard ? 'display:none;' : ''
144
+			),
145
+			['required' => true]
146
+		);
147
+		return $subsections;
148
+	}
149
+
150
+
151
+	/**
152
+	 * Add the offboarding (deauthorize) button.
153
+	 *
154
+	 * @param array $subsections
155
+	 * @param bool  $is_onboard
156
+	 * @return array
157
+	 */
158
+	public function addOffboardButton(array $subsections, bool $is_onboard): array
159
+	{
160
+		$onboard_sandbox_section = $this->getOnboardSandboxSection();
161
+		// If we are connected, display the seller merchant ID.
162
+		$seller_id_section = $this->getSellerIdSection();
163
+		// Section to be displayed when onboard.
164
+		$subsections['paypal_offboard_btn'] = new EE_Form_Section_HTML(
165
+			EEH_HTML::tr(
166
+				$this->getHeader()
167
+				. EEH_HTML::td(
168
+					EEH_HTML::img(
169
+						EEP_PAYPAL_COMMERCE_URL . 'assets' . DS . 'lib' . DS . 'paypal-onboard.png',
170
+						'',
171
+						'eea_paypal_offboard_ico',
172
+						'eea-paypal-offboard-ico'
173
+					)
174
+					. EEH_HTML::strong(
175
+						esc_html__('Connected.', 'event_espresso'),
176
+						'eea_paypal_offboard_txt_' . $this->pm_slug,
177
+						'eea-paypal-offboard-txt'
178
+					)
179
+					. $onboard_sandbox_section
180
+					. $seller_id_section
181
+					. EEH_HTML::link(
182
+						'#',
183
+						EEH_HTML::span(esc_html__('Disconnect', 'event_espresso')),
184
+						'',
185
+						'eea_paypal_offboard_btn_' . $this->pm_slug,
186
+						'eea-paypal-onboard-btn button button--primary'
187
+					)
188
+				),
189
+				'eea_paypal_offboard_section_' . $this->pm_slug,
190
+				'eea-offboard-section-' . $this->pm_slug,
191
+				// Are we onboard ?
192
+				! $is_onboard ? 'display:none;' : ''
193
+			),
194
+			['required' => true]
195
+		);
196
+		return $subsections;
197
+	}
198
+
199
+
200
+	/**
201
+	 * Get the sandbox onboarding section contents.
202
+	 *
203
+	 * @return string
204
+	 */
205
+	public function getOnboardSandboxSection(): string
206
+	{
207
+		// Is this a test onboarding ?
208
+		$sandbox_mode_text = $this->pm_instance->debug_mode() ? $this->authed_sandbox_text : '';
209
+		return ' ' . EEH_HTML::strong(
210
+			$sandbox_mode_text,
211
+			'eea_paypal_onboard_test_txt_' . $this->pm_slug,
212
+			'eea-paypal-onboard-test-txt'
213
+		);
214
+	}
215
+
216
+
217
+	/**
218
+	 * Get the seller merchant ID section contents.
219
+	 *
220
+	 * @return string
221
+	 */
222
+	public function getSellerIdSection(): string
223
+	{
224
+		try {
225
+			$is_third_party = EED_PayPalCommerce::isThirdParty($this->pm_instance);
226
+			$meta_key       = $is_third_party ? Domain::META_KEY_SELLER_MERCHANT_ID : Domain::META_KEY_PAYER_ID;
227
+			$payer_id       = PayPalExtraMetaManager::getPmOption($this->pm_instance, $meta_key) ?: '--';
228
+		} catch (Exception $e) {
229
+			$payer_id = '--';
230
+		}
231
+		return ' ' . EEH_HTML::strong(
232
+			sprintf(esc_html__('Linked account ID: %1$s', 'event_espresso'), $payer_id),
233
+			'eea_paypal_seller_id_' . $this->pm_slug,
234
+			'eea-paypal-seller-id'
235
+		);
236
+	}
237
+
238
+
239
+	/**
240
+	 * Add the PM slug holder.
241
+	 *
242
+	 * @param array $subsections
243
+	 * @return array
244
+	 */
245
+	public function addPmSlugHolder(array $subsections): array
246
+	{
247
+		$subsections['paypal_pm_slug_holder'] = new EE_Form_Section_HTML(
248
+			EEH_HTML::span(
249
+				'',
250
+				'eea_paypal_pm_slug',
251
+				'eea-paypal-pm-slug',
252
+				'display:none;'
253
+			)
254
+		);
255
+		return $subsections;
256
+	}
257
+
258
+
259
+	/**
260
+	 * HTML for onboarding settings dialog.
261
+	 *
262
+	 * @return EE_Form_Section_Base
263
+	 */
264
+	public function connectDialog(): EE_Form_Section_Base
265
+	{
266
+		return new EE_Form_Section_HTML(
267
+			EEH_HTML::div(
268
+				$this->countriesSelectHtml() .
269
+				$this->paymentOptionsHtml() .
270
+				EEH_HTML::div(
271
+					EEH_HTML::link(
272
+						'',
273
+						'Cancel',
274
+						'cancel, go back',
275
+						'eea_ppc_connect_cancel_' . $this->pm_slug,
276
+						'eea-ppc-connect-cancel button button--secondary'
277
+					) .
278
+					EEH_HTML::link(
279
+						'',
280
+						'Continue',
281
+						'ok, continue',
282
+						'eea_ppc_connect_ok_' . $this->pm_slug,
283
+						'eea-ppc-connect-ok button button--primary-alt'
284
+					),
285
+					'',
286
+					'eep-ppc-dialog-yes-no'
287
+				),
288
+				'eea_paypal_connect_dialog_' . $this->pm_slug
289
+			)
290
+		);
291
+	}
292
+
293
+
294
+	/**
295
+	 * Form a countries select and return as html.
296
+	 *
297
+	 * @return string
298
+	 */
299
+	public function countriesSelectHtml(): string
300
+	{
301
+		$countries = [];
302
+		$countries_select = EEH_HTML::strong(
303
+			esc_html__('Please select a country where your PayPal account is registered:', 'event_espresso'),
304
+			'eep_ppc_country_txt_' . $this->pm_slug,
305
+			'eep-ppc-country-txt'
306
+		);
307
+		try {
308
+			// Get all countries list.
309
+			$countries_iso = EEM_Country::instance()->get_all_countries();
310
+			foreach ($countries_iso as $iso => $country) {
311
+				if ($country instanceof EE_Country) {
312
+					$countries [ $iso ] = $country->get('CNT_name');
313
+				}
314
+			}
315
+			// Now build the select input.
316
+			$select_input = new EE_Select_Input(
317
+				$countries,
318
+				[
319
+					'html_name'       => 'eep_ppc_country_' . $this->pm_slug,
320
+					'html_id'         => 'eep_ppc_country_' . $this->pm_slug,
321
+					'html_class'      => 'eep-ppc-country-' . $this->pm_slug,
322
+					'html_label_text' => esc_html__('Select country', 'event_espresso'),
323
+					'required'        => true,
324
+					'default'         => EE_Config::instance()->organization->CNT_ISO ?? 'US'
325
+				]
326
+			);
327
+			$countries_select .= $select_input->get_html_for_input();
328
+		} catch (Exception $e) {
329
+			// Countries list set at this point, so just continue.
330
+		}
331
+		return $countries_select;
332
+	}
333
+
334
+
335
+	/**
336
+	 * Form the payment options checkboxes and return as html.
337
+	 *
338
+	 * @return string
339
+	 */
340
+	public function paymentOptionsHtml(): string
341
+	{
342
+		$options_lbl = EEH_HTML::strong(
343
+			esc_html__('Select a product you\'d like to allow at checkout:', 'event_espresso'),
344
+			'eea_ppc_product_txt_' . $this->pm_slug,
345
+			'eea-ppc-product-txt'
346
+		);
347
+		$express_checkout_lbl = EEH_HTML::label(
348
+			esc_html__('Accept PayPal ', 'event_espresso')
349
+			. EEH_HTML::img(
350
+				'https://www.paypalobjects.com/webstatic/mktg/Logo/pp-logo-100px.png',
351
+				'',
352
+				'eea_ppc_express_checkout_img_' . $this->pm_slug,
353
+				'eea-ppc-express-checkout-img'
354
+			),
355
+			'',
356
+			'',
357
+			'',
358
+			'for="' . 'eep_ppc_checkout_type_' . $this->pm_slug . '-express_checkout"'
359
+		);
360
+		$ppcp_lbl = EEH_HTML::label(
361
+			esc_html__('Accept credit and debit card payments with PayPal ', 'event_espresso')
362
+			. EEH_HTML::img(
363
+				'https://www.paypalobjects.com/digitalassets/c/website/marketing/apac/C2/logos-buttons/optimize/Full_Online_Tray_RGB.png',
364
+				'',
365
+				'eea_ppc_ppcp_img_' . $this->pm_slug,
366
+				'eea-ppc-ppcp-img'
367
+			),
368
+			'',
369
+			'',
370
+			'',
371
+			'for="' . 'eep_ppc_checkout_type_' . $this->pm_slug . '-ppcp"'
372
+		);
373
+		$checkbox = new EE_Checkbox_Multi_Input(
374
+			[
375
+				'express_checkout' => $express_checkout_lbl,
376
+				'ppcp'             => $ppcp_lbl,
377
+			],
378
+			[
379
+				'html_id'         => 'eep_ppc_checkout_type_' . $this->pm_slug,
380
+				'html_label_text' => esc_html__(
381
+					'Select a product you\'d like to allow at checkout.',
382
+					'event_espresso'
383
+				),
384
+				'html_help_text'  => esc_html__(
385
+					'Select a product you\'d like to allow at checkout.',
386
+					'event_espresso'
387
+				),
388
+				'default'         => ['express_checkout', 'ppcp']
389
+			]
390
+		);
391
+		try {
392
+			return EEH_HTML::div(
393
+				$options_lbl
394
+				. $checkbox->get_html_for_input(),
395
+				'eep_ppc_checkout_types_' . $this->pm_slug,
396
+				'eep-ppc-checkout-types'
397
+			);
398
+		} catch (Exception $e) {
399
+			return '';
400
+		}
401
+	}
402
+
403
+
404
+	/**
405
+	 * HTML for onboarding settings dialog.
406
+	 *
407
+	 * @return EE_Form_Section_Base
408
+	 */
409
+	public function processingMask(): EE_Form_Section_Base
410
+	{
411
+		return new EE_Form_Section_HTML(
412
+			EEH_HTML::div(
413
+				EEH_HTML::div(' ', 'eep_ppc_processing_mask', 'eep-ppc-processing-mask') .
414
+				EEH_HTML::div(' ', 'eep_ppc_processing_spinner', 'ee-spinner ee-spin') .
415
+				EEH_HTML::div(
416
+					esc_html__('The login window should be open. If you don\'t see a new PayPal login window you might need to enable pop-ups in your browser in order to continue.') .
417
+					EEH_HTML::div(
418
+						EEH_HTML::link(
419
+							'#',
420
+							esc_html__('Focus window'),
421
+							esc_html__('Focus window'),
422
+							'eep_ppc_window_focus_' . $this->pm_slug,
423
+							'eep-ppc-window-focus'
424
+						)
425
+					),
426
+					'eep_ppc_processing_message',
427
+					'eep-ppc-processing-message'
428
+				),
429
+				'eep_ppc_processing_' . $this->pm_slug,
430
+				'eep-ppc-processing'
431
+			)
432
+		);
433
+	}
434
+
435
+
436
+	/**
437
+	 * HTML for the disconnect warning dialog.
438
+	 *
439
+	 * @return EE_Form_Section_Base
440
+	 */
441
+	public function disconnectDialog(): EE_Form_Section_Base
442
+	{
443
+		$message = esc_html__(
444
+			'Disconnecting your PayPal account will prevent you from offering PayPal services and products on your website.',
445
+			'event_espresso'
446
+		);
447
+		return new EE_Form_Section_HTML(
448
+			EEH_HTML::div(
449
+				EEH_HTML::strong(
450
+					$message,
451
+					'eep_ppc_disconnect_dialog_txt_' . $this->pm_slug,
452
+					'eep-ppc-disconnect-dialog-txt'
453
+				) .
454
+				EEH_HTML::div(
455
+					EEH_HTML::link(
456
+						'',
457
+						'Cancel',
458
+						'cancel, go back',
459
+						'eep_ppc_disconnect_cancel_' . $this->pm_slug,
460
+						'eep-ppc-disconnect-cancel button button--secondary'
461
+					) .
462
+					EEH_HTML::link(
463
+						'',
464
+						'Disconnect',
465
+						'ok, continue',
466
+						'eep_ppc_disconnect_ok_' . $this->pm_slug,
467
+						'eep-ppc-disconnect-ok button button--primary-alt'
468
+					),
469
+					'',
470
+					'eep-ppc-dialog-yes-no'
471
+				),
472
+				'eep_paypal_disconnect_dialog_' . $this->pm_slug
473
+			)
474
+		);
475
+	}
476 476
 }
Please login to merge, or discard this patch.
Spacing   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -101,7 +101,7 @@  discard block
 block discarded – undo
101 101
                 $text,
102 102
                 $this->payment_method->get_help_tab_link()
103 103
             ),
104
-            'eea_paypal_onboard_heading_' . $this->pm_slug,
104
+            'eea_paypal_onboard_heading_'.$this->pm_slug,
105 105
             'eea-paypal-onboard-heading'
106 106
         );
107 107
     }
@@ -119,26 +119,26 @@  discard block
 block discarded – undo
119 119
         // Section to be displayed if not onboard.
120 120
         $subsections['paypal_onboard_btn'] = new EE_Form_Section_HTML(
121 121
             EEH_HTML::tr(
122
-                $this->getHeader() .
122
+                $this->getHeader().
123 123
                 EEH_HTML::td(
124 124
                     EEH_HTML::button(
125 125
                         $this->onboard_btn_text,
126 126
                         'eea-paypal-onboard-btn button button--primary',
127 127
                         '',
128
-                        'eea_paypal_onboard_btn_' . $this->pm_slug,
128
+                        'eea_paypal_onboard_btn_'.$this->pm_slug,
129 129
                     )
130 130
                     . EEH_HTML::link(
131 131
                         '#',
132 132
                         '',
133 133
                         '',
134
-                        'eea_paypal_onboard_trigger_btn_' . $this->pm_slug,
134
+                        'eea_paypal_onboard_trigger_btn_'.$this->pm_slug,
135 135
                         'eea-paypal-onboard-trigger-btn',
136 136
                         '',
137
-                        'data-ee-pm-slug="' . $this->pm_slug . '" data-paypal-button="true"'
137
+                        'data-ee-pm-slug="'.$this->pm_slug.'" data-paypal-button="true"'
138 138
                     )
139 139
                 ),
140
-                'eea_paypal_onboard_section_' . $this->pm_slug,
141
-                'eea-onboard-section eea-onboard-section-' . $this->pm_slug,
140
+                'eea_paypal_onboard_section_'.$this->pm_slug,
141
+                'eea-onboard-section eea-onboard-section-'.$this->pm_slug,
142 142
                 // Are we onboard ?
143 143
                 $is_onboard ? 'display:none;' : ''
144 144
             ),
@@ -166,14 +166,14 @@  discard block
 block discarded – undo
166 166
                 $this->getHeader()
167 167
                 . EEH_HTML::td(
168 168
                     EEH_HTML::img(
169
-                        EEP_PAYPAL_COMMERCE_URL . 'assets' . DS . 'lib' . DS . 'paypal-onboard.png',
169
+                        EEP_PAYPAL_COMMERCE_URL.'assets'.DS.'lib'.DS.'paypal-onboard.png',
170 170
                         '',
171 171
                         'eea_paypal_offboard_ico',
172 172
                         'eea-paypal-offboard-ico'
173 173
                     )
174 174
                     . EEH_HTML::strong(
175 175
                         esc_html__('Connected.', 'event_espresso'),
176
-                        'eea_paypal_offboard_txt_' . $this->pm_slug,
176
+                        'eea_paypal_offboard_txt_'.$this->pm_slug,
177 177
                         'eea-paypal-offboard-txt'
178 178
                     )
179 179
                     . $onboard_sandbox_section
@@ -182,12 +182,12 @@  discard block
 block discarded – undo
182 182
                         '#',
183 183
                         EEH_HTML::span(esc_html__('Disconnect', 'event_espresso')),
184 184
                         '',
185
-                        'eea_paypal_offboard_btn_' . $this->pm_slug,
185
+                        'eea_paypal_offboard_btn_'.$this->pm_slug,
186 186
                         'eea-paypal-onboard-btn button button--primary'
187 187
                     )
188 188
                 ),
189
-                'eea_paypal_offboard_section_' . $this->pm_slug,
190
-                'eea-offboard-section-' . $this->pm_slug,
189
+                'eea_paypal_offboard_section_'.$this->pm_slug,
190
+                'eea-offboard-section-'.$this->pm_slug,
191 191
                 // Are we onboard ?
192 192
                 ! $is_onboard ? 'display:none;' : ''
193 193
             ),
@@ -206,9 +206,9 @@  discard block
 block discarded – undo
206 206
     {
207 207
         // Is this a test onboarding ?
208 208
         $sandbox_mode_text = $this->pm_instance->debug_mode() ? $this->authed_sandbox_text : '';
209
-        return ' ' . EEH_HTML::strong(
209
+        return ' '.EEH_HTML::strong(
210 210
             $sandbox_mode_text,
211
-            'eea_paypal_onboard_test_txt_' . $this->pm_slug,
211
+            'eea_paypal_onboard_test_txt_'.$this->pm_slug,
212 212
             'eea-paypal-onboard-test-txt'
213 213
         );
214 214
     }
@@ -228,9 +228,9 @@  discard block
 block discarded – undo
228 228
         } catch (Exception $e) {
229 229
             $payer_id = '--';
230 230
         }
231
-        return ' ' . EEH_HTML::strong(
231
+        return ' '.EEH_HTML::strong(
232 232
             sprintf(esc_html__('Linked account ID: %1$s', 'event_espresso'), $payer_id),
233
-            'eea_paypal_seller_id_' . $this->pm_slug,
233
+            'eea_paypal_seller_id_'.$this->pm_slug,
234 234
             'eea-paypal-seller-id'
235 235
         );
236 236
     }
@@ -265,27 +265,27 @@  discard block
 block discarded – undo
265 265
     {
266 266
         return new EE_Form_Section_HTML(
267 267
             EEH_HTML::div(
268
-                $this->countriesSelectHtml() .
269
-                $this->paymentOptionsHtml() .
268
+                $this->countriesSelectHtml().
269
+                $this->paymentOptionsHtml().
270 270
                 EEH_HTML::div(
271 271
                     EEH_HTML::link(
272 272
                         '',
273 273
                         'Cancel',
274 274
                         'cancel, go back',
275
-                        'eea_ppc_connect_cancel_' . $this->pm_slug,
275
+                        'eea_ppc_connect_cancel_'.$this->pm_slug,
276 276
                         'eea-ppc-connect-cancel button button--secondary'
277
-                    ) .
277
+                    ).
278 278
                     EEH_HTML::link(
279 279
                         '',
280 280
                         'Continue',
281 281
                         'ok, continue',
282
-                        'eea_ppc_connect_ok_' . $this->pm_slug,
282
+                        'eea_ppc_connect_ok_'.$this->pm_slug,
283 283
                         'eea-ppc-connect-ok button button--primary-alt'
284 284
                     ),
285 285
                     '',
286 286
                     'eep-ppc-dialog-yes-no'
287 287
                 ),
288
-                'eea_paypal_connect_dialog_' . $this->pm_slug
288
+                'eea_paypal_connect_dialog_'.$this->pm_slug
289 289
             )
290 290
         );
291 291
     }
@@ -301,7 +301,7 @@  discard block
 block discarded – undo
301 301
         $countries = [];
302 302
         $countries_select = EEH_HTML::strong(
303 303
             esc_html__('Please select a country where your PayPal account is registered:', 'event_espresso'),
304
-            'eep_ppc_country_txt_' . $this->pm_slug,
304
+            'eep_ppc_country_txt_'.$this->pm_slug,
305 305
             'eep-ppc-country-txt'
306 306
         );
307 307
         try {
@@ -309,16 +309,16 @@  discard block
 block discarded – undo
309 309
             $countries_iso = EEM_Country::instance()->get_all_countries();
310 310
             foreach ($countries_iso as $iso => $country) {
311 311
                 if ($country instanceof EE_Country) {
312
-                    $countries [ $iso ] = $country->get('CNT_name');
312
+                    $countries [$iso] = $country->get('CNT_name');
313 313
                 }
314 314
             }
315 315
             // Now build the select input.
316 316
             $select_input = new EE_Select_Input(
317 317
                 $countries,
318 318
                 [
319
-                    'html_name'       => 'eep_ppc_country_' . $this->pm_slug,
320
-                    'html_id'         => 'eep_ppc_country_' . $this->pm_slug,
321
-                    'html_class'      => 'eep-ppc-country-' . $this->pm_slug,
319
+                    'html_name'       => 'eep_ppc_country_'.$this->pm_slug,
320
+                    'html_id'         => 'eep_ppc_country_'.$this->pm_slug,
321
+                    'html_class'      => 'eep-ppc-country-'.$this->pm_slug,
322 322
                     'html_label_text' => esc_html__('Select country', 'event_espresso'),
323 323
                     'required'        => true,
324 324
                     'default'         => EE_Config::instance()->organization->CNT_ISO ?? 'US'
@@ -341,7 +341,7 @@  discard block
 block discarded – undo
341 341
     {
342 342
         $options_lbl = EEH_HTML::strong(
343 343
             esc_html__('Select a product you\'d like to allow at checkout:', 'event_espresso'),
344
-            'eea_ppc_product_txt_' . $this->pm_slug,
344
+            'eea_ppc_product_txt_'.$this->pm_slug,
345 345
             'eea-ppc-product-txt'
346 346
         );
347 347
         $express_checkout_lbl = EEH_HTML::label(
@@ -349,26 +349,26 @@  discard block
 block discarded – undo
349 349
             . EEH_HTML::img(
350 350
                 'https://www.paypalobjects.com/webstatic/mktg/Logo/pp-logo-100px.png',
351 351
                 '',
352
-                'eea_ppc_express_checkout_img_' . $this->pm_slug,
352
+                'eea_ppc_express_checkout_img_'.$this->pm_slug,
353 353
                 'eea-ppc-express-checkout-img'
354 354
             ),
355 355
             '',
356 356
             '',
357 357
             '',
358
-            'for="' . 'eep_ppc_checkout_type_' . $this->pm_slug . '-express_checkout"'
358
+            'for="'.'eep_ppc_checkout_type_'.$this->pm_slug.'-express_checkout"'
359 359
         );
360 360
         $ppcp_lbl = EEH_HTML::label(
361 361
             esc_html__('Accept credit and debit card payments with PayPal ', 'event_espresso')
362 362
             . EEH_HTML::img(
363 363
                 'https://www.paypalobjects.com/digitalassets/c/website/marketing/apac/C2/logos-buttons/optimize/Full_Online_Tray_RGB.png',
364 364
                 '',
365
-                'eea_ppc_ppcp_img_' . $this->pm_slug,
365
+                'eea_ppc_ppcp_img_'.$this->pm_slug,
366 366
                 'eea-ppc-ppcp-img'
367 367
             ),
368 368
             '',
369 369
             '',
370 370
             '',
371
-            'for="' . 'eep_ppc_checkout_type_' . $this->pm_slug . '-ppcp"'
371
+            'for="'.'eep_ppc_checkout_type_'.$this->pm_slug.'-ppcp"'
372 372
         );
373 373
         $checkbox = new EE_Checkbox_Multi_Input(
374 374
             [
@@ -376,7 +376,7 @@  discard block
 block discarded – undo
376 376
                 'ppcp'             => $ppcp_lbl,
377 377
             ],
378 378
             [
379
-                'html_id'         => 'eep_ppc_checkout_type_' . $this->pm_slug,
379
+                'html_id'         => 'eep_ppc_checkout_type_'.$this->pm_slug,
380 380
                 'html_label_text' => esc_html__(
381 381
                     'Select a product you\'d like to allow at checkout.',
382 382
                     'event_espresso'
@@ -392,7 +392,7 @@  discard block
 block discarded – undo
392 392
             return EEH_HTML::div(
393 393
                 $options_lbl
394 394
                 . $checkbox->get_html_for_input(),
395
-                'eep_ppc_checkout_types_' . $this->pm_slug,
395
+                'eep_ppc_checkout_types_'.$this->pm_slug,
396 396
                 'eep-ppc-checkout-types'
397 397
             );
398 398
         } catch (Exception $e) {
@@ -410,23 +410,23 @@  discard block
 block discarded – undo
410 410
     {
411 411
         return new EE_Form_Section_HTML(
412 412
             EEH_HTML::div(
413
-                EEH_HTML::div(' ', 'eep_ppc_processing_mask', 'eep-ppc-processing-mask') .
414
-                EEH_HTML::div(' ', 'eep_ppc_processing_spinner', 'ee-spinner ee-spin') .
413
+                EEH_HTML::div(' ', 'eep_ppc_processing_mask', 'eep-ppc-processing-mask').
414
+                EEH_HTML::div(' ', 'eep_ppc_processing_spinner', 'ee-spinner ee-spin').
415 415
                 EEH_HTML::div(
416
-                    esc_html__('The login window should be open. If you don\'t see a new PayPal login window you might need to enable pop-ups in your browser in order to continue.') .
416
+                    esc_html__('The login window should be open. If you don\'t see a new PayPal login window you might need to enable pop-ups in your browser in order to continue.').
417 417
                     EEH_HTML::div(
418 418
                         EEH_HTML::link(
419 419
                             '#',
420 420
                             esc_html__('Focus window'),
421 421
                             esc_html__('Focus window'),
422
-                            'eep_ppc_window_focus_' . $this->pm_slug,
422
+                            'eep_ppc_window_focus_'.$this->pm_slug,
423 423
                             'eep-ppc-window-focus'
424 424
                         )
425 425
                     ),
426 426
                     'eep_ppc_processing_message',
427 427
                     'eep-ppc-processing-message'
428 428
                 ),
429
-                'eep_ppc_processing_' . $this->pm_slug,
429
+                'eep_ppc_processing_'.$this->pm_slug,
430 430
                 'eep-ppc-processing'
431 431
             )
432 432
         );
@@ -448,28 +448,28 @@  discard block
 block discarded – undo
448 448
             EEH_HTML::div(
449 449
                 EEH_HTML::strong(
450 450
                     $message,
451
-                    'eep_ppc_disconnect_dialog_txt_' . $this->pm_slug,
451
+                    'eep_ppc_disconnect_dialog_txt_'.$this->pm_slug,
452 452
                     'eep-ppc-disconnect-dialog-txt'
453
-                ) .
453
+                ).
454 454
                 EEH_HTML::div(
455 455
                     EEH_HTML::link(
456 456
                         '',
457 457
                         'Cancel',
458 458
                         'cancel, go back',
459
-                        'eep_ppc_disconnect_cancel_' . $this->pm_slug,
459
+                        'eep_ppc_disconnect_cancel_'.$this->pm_slug,
460 460
                         'eep-ppc-disconnect-cancel button button--secondary'
461
-                    ) .
461
+                    ).
462 462
                     EEH_HTML::link(
463 463
                         '',
464 464
                         'Disconnect',
465 465
                         'ok, continue',
466
-                        'eep_ppc_disconnect_ok_' . $this->pm_slug,
466
+                        'eep_ppc_disconnect_ok_'.$this->pm_slug,
467 467
                         'eep-ppc-disconnect-ok button button--primary-alt'
468 468
                     ),
469 469
                     '',
470 470
                     'eep-ppc-dialog-yes-no'
471 471
                 ),
472
-                'eep_paypal_disconnect_dialog_' . $this->pm_slug
472
+                'eep_paypal_disconnect_dialog_'.$this->pm_slug
473 473
             )
474 474
         );
475 475
     }
Please login to merge, or discard this patch.
PaymentMethods/PayPalCommerce/PayPalCheckout/forms/SettingsForm.php 2 patches
Indentation   +233 added lines, -233 removed lines patch added patch discarded remove patch
@@ -25,252 +25,252 @@
 block discarded – undo
25 25
  */
26 26
 class SettingsForm extends EE_Payment_Method_Form
27 27
 {
28
-    /**
29
-     *  Payment method.
30
-     *
31
-     * @var EE_PMT_Base|null
32
-     */
33
-    protected $payment_method = null;
28
+	/**
29
+	 *  Payment method.
30
+	 *
31
+	 * @var EE_PMT_Base|null
32
+	 */
33
+	protected $payment_method = null;
34 34
 
35
-    /**
36
-     *  Payment method instance.
37
-     *
38
-     * @var EE_PMT_Base|null
39
-     */
40
-    protected $pm_instance = null;
35
+	/**
36
+	 *  Payment method instance.
37
+	 *
38
+	 * @var EE_PMT_Base|null
39
+	 */
40
+	protected $pm_instance = null;
41 41
 
42 42
 
43
-    /**
44
-     * Class constructor.
45
-     *
46
-     * @param EE_PMT_PayPalCheckout $payment_method
47
-     * @param EE_Payment_Method     $pm_instance
48
-     * @throws EE_Error
49
-     * @throws ReflectionException
50
-     */
51
-    public function __construct(EE_PMT_PayPalCheckout $payment_method, EE_Payment_Method $pm_instance)
52
-    {
53
-        $form_parameters      = [];
54
-        $this->payment_method = $payment_method;
55
-        $this->pm_instance    = $pm_instance;
56
-        // Allow Advanced Card Checkout if PPCP checkout type was possible and selected.
57
-        $allowed_type = PayPalExtraMetaManager::getPmOption($pm_instance, Domain::META_KEY_ALLOWED_CHECKOUT_TYPE);
58
-        $is_onboard   = EED_PayPalOnboard::isOnboard($pm_instance);
59
-        if ($is_onboard && ($allowed_type === 'ppcp' || $allowed_type === 'all')) {
60
-            $form_parameters = $this->addCheckoutTypeSelect($form_parameters);
61
-            $form_parameters = $this->addFundingOptions($form_parameters);
62
-        }
63
-        // Build the PM form.
64
-        parent::__construct($form_parameters);
65
-        // Add a form for PayPal Onboard.
66
-        $this->addOnboardingForm($payment_method, $pm_instance);
67
-        // Add a form for PayPal Onboard.
68
-        $this->addFeesNotice();
69
-        // Add the clear data button.
70
-        $this->clearMetadataButton($pm_instance);
71
-        // Disable inputs if needed.
72
-        $this->toggleSubsections($pm_instance);
73
-    }
43
+	/**
44
+	 * Class constructor.
45
+	 *
46
+	 * @param EE_PMT_PayPalCheckout $payment_method
47
+	 * @param EE_Payment_Method     $pm_instance
48
+	 * @throws EE_Error
49
+	 * @throws ReflectionException
50
+	 */
51
+	public function __construct(EE_PMT_PayPalCheckout $payment_method, EE_Payment_Method $pm_instance)
52
+	{
53
+		$form_parameters      = [];
54
+		$this->payment_method = $payment_method;
55
+		$this->pm_instance    = $pm_instance;
56
+		// Allow Advanced Card Checkout if PPCP checkout type was possible and selected.
57
+		$allowed_type = PayPalExtraMetaManager::getPmOption($pm_instance, Domain::META_KEY_ALLOWED_CHECKOUT_TYPE);
58
+		$is_onboard   = EED_PayPalOnboard::isOnboard($pm_instance);
59
+		if ($is_onboard && ($allowed_type === 'ppcp' || $allowed_type === 'all')) {
60
+			$form_parameters = $this->addCheckoutTypeSelect($form_parameters);
61
+			$form_parameters = $this->addFundingOptions($form_parameters);
62
+		}
63
+		// Build the PM form.
64
+		parent::__construct($form_parameters);
65
+		// Add a form for PayPal Onboard.
66
+		$this->addOnboardingForm($payment_method, $pm_instance);
67
+		// Add a form for PayPal Onboard.
68
+		$this->addFeesNotice();
69
+		// Add the clear data button.
70
+		$this->clearMetadataButton($pm_instance);
71
+		// Disable inputs if needed.
72
+		$this->toggleSubsections($pm_instance);
73
+	}
74 74
 
75 75
 
76
-    /**
77
-     * Adds an onboarding form as a subsection.
78
-     *
79
-     * @param EE_PMT_PayPalCheckout $payment_method
80
-     * @param EE_Payment_Method     $pm_instance
81
-     * @return void
82
-     */
83
-    public function addOnboardingForm(EE_PMT_PayPalCheckout $payment_method, EE_Payment_Method $pm_instance): void
84
-    {
85
-        // Add the connect button before the app id field.
86
-        try {
87
-            $this->add_subsections(
88
-                [
89
-                    'paypal_onboard' => new OnboardingForm($payment_method, $pm_instance),
90
-                ],
91
-                'PMD_debug_mode',
92
-                false
93
-            );
94
-        } catch (EE_Error $e) {
95
-            // Simply don't add the form.
96
-        }
97
-    }
76
+	/**
77
+	 * Adds an onboarding form as a subsection.
78
+	 *
79
+	 * @param EE_PMT_PayPalCheckout $payment_method
80
+	 * @param EE_Payment_Method     $pm_instance
81
+	 * @return void
82
+	 */
83
+	public function addOnboardingForm(EE_PMT_PayPalCheckout $payment_method, EE_Payment_Method $pm_instance): void
84
+	{
85
+		// Add the connect button before the app id field.
86
+		try {
87
+			$this->add_subsections(
88
+				[
89
+					'paypal_onboard' => new OnboardingForm($payment_method, $pm_instance),
90
+				],
91
+				'PMD_debug_mode',
92
+				false
93
+			);
94
+		} catch (EE_Error $e) {
95
+			// Simply don't add the form.
96
+		}
97
+	}
98 98
 
99 99
 
100
-    /**
101
-     * Add fees notice.
102
-     *
103
-     * @return void
104
-     */
105
-    public function addFeesNotice(): void
106
-    {
107
-        if (defined('EE_PPC_USE_PAYMENT_FEES') && ! EE_PPC_USE_PAYMENT_FEES) {
108
-            // We want to be able to disable fees.
109
-            return;
110
-        }
111
-        try {
112
-            $this->add_subsections(
113
-                [
114
-                    'partner_fees_notice' => new EE_Form_Section_HTML(
115
-                        EEH_HTML::tr(
116
-                            EEH_HTML::th()
117
-                            . EEH_HTML::thx()
118
-                            . EEH_HTML::td(
119
-                                EEH_HTML::div(
120
-                                    EEH_HTML::strong(
121
-                                        esc_html__(
122
-                                            'PayPal Partner Commission Fees are based upon the status of your Support License:',
123
-                                            'event_espresso'
124
-                                        )
125
-                                    )
126
-                                    . EEH_HTML::ul()
127
-                                    . EEH_HTML::li(
128
-                                        esc_html__('- Active licenses commission fees: 0%', 'event_espresso')
129
-                                    )
130
-                                    . EEH_HTML::li(
131
-                                        esc_html__('- Expired license commission fees: 3%', 'event_espresso')
132
-                                    )
133
-                                    . EEH_HTML::ulx()
134
-                                    . esc_html__(
135
-                                        'Keep your support license active for: lower fees, up-to-date software and have access to our support team. By connecting and processing payments you agree to these terms.',
136
-                                        'event_espresso'
137
-                                    ),
138
-                                    '',
139
-                                    'ee-status-outline ee-status-bg--info'
140
-                                )
141
-                            )
142
-                        )
143
-                    ),
144
-                ],
145
-                'paypal_onboard'
146
-            );
147
-        } catch (EE_Error $e) {
148
-            // Don't add this subsection then.
149
-        }
150
-    }
100
+	/**
101
+	 * Add fees notice.
102
+	 *
103
+	 * @return void
104
+	 */
105
+	public function addFeesNotice(): void
106
+	{
107
+		if (defined('EE_PPC_USE_PAYMENT_FEES') && ! EE_PPC_USE_PAYMENT_FEES) {
108
+			// We want to be able to disable fees.
109
+			return;
110
+		}
111
+		try {
112
+			$this->add_subsections(
113
+				[
114
+					'partner_fees_notice' => new EE_Form_Section_HTML(
115
+						EEH_HTML::tr(
116
+							EEH_HTML::th()
117
+							. EEH_HTML::thx()
118
+							. EEH_HTML::td(
119
+								EEH_HTML::div(
120
+									EEH_HTML::strong(
121
+										esc_html__(
122
+											'PayPal Partner Commission Fees are based upon the status of your Support License:',
123
+											'event_espresso'
124
+										)
125
+									)
126
+									. EEH_HTML::ul()
127
+									. EEH_HTML::li(
128
+										esc_html__('- Active licenses commission fees: 0%', 'event_espresso')
129
+									)
130
+									. EEH_HTML::li(
131
+										esc_html__('- Expired license commission fees: 3%', 'event_espresso')
132
+									)
133
+									. EEH_HTML::ulx()
134
+									. esc_html__(
135
+										'Keep your support license active for: lower fees, up-to-date software and have access to our support team. By connecting and processing payments you agree to these terms.',
136
+										'event_espresso'
137
+									),
138
+									'',
139
+									'ee-status-outline ee-status-bg--info'
140
+								)
141
+							)
142
+						)
143
+					),
144
+				],
145
+				'paypal_onboard'
146
+			);
147
+		} catch (EE_Error $e) {
148
+			// Don't add this subsection then.
149
+		}
150
+	}
151 151
 
152 152
 
153
-    /**
154
-     * Add a checkout type select.
155
-     *
156
-     * @param array $form_parameters
157
-     * @return array
158
-     * @throws EE_Error
159
-     * @throws ReflectionException
160
-     */
161
-    public function addCheckoutTypeSelect(array $form_parameters): array
162
-    {
163
-        $pm_slug               = $this->pm_instance->slug();
164
-        // Section to be displayed if onboard.
165
-        $form_parameters['extra_meta_inputs'][Domain::META_KEY_CHECKOUT_TYPE] = new EE_Select_Input(
166
-            [
167
-                'express_checkout' => esc_html__('Express Checkout', 'event_espresso'),
168
-                'ppcp'             => esc_html__('Advanced Credit and Debit Card payments', 'event_espresso'),
169
-                'all'              => esc_html__('Both, ACDC and Express Checkout', 'event_espresso'),
170
-            ],
171
-            [
172
-                'html_name'  => "eep_checkout_type_option_$pm_slug",
173
-                'html_id'    => "eep_checkout_type_option_$pm_slug",
174
-                'html_class' => "eep-checkout-type-option-$pm_slug",
175
-                'required'   => true,
176
-                'default'    => PayPalExtraMetaManager::getPmOption(
177
-                    $this->pm_instance,
178
-                    Domain::META_KEY_ALLOWED_CHECKOUT_TYPE
179
-                ),
180
-            ]
181
-        );
182
-        return $form_parameters;
183
-    }
153
+	/**
154
+	 * Add a checkout type select.
155
+	 *
156
+	 * @param array $form_parameters
157
+	 * @return array
158
+	 * @throws EE_Error
159
+	 * @throws ReflectionException
160
+	 */
161
+	public function addCheckoutTypeSelect(array $form_parameters): array
162
+	{
163
+		$pm_slug               = $this->pm_instance->slug();
164
+		// Section to be displayed if onboard.
165
+		$form_parameters['extra_meta_inputs'][Domain::META_KEY_CHECKOUT_TYPE] = new EE_Select_Input(
166
+			[
167
+				'express_checkout' => esc_html__('Express Checkout', 'event_espresso'),
168
+				'ppcp'             => esc_html__('Advanced Credit and Debit Card payments', 'event_espresso'),
169
+				'all'              => esc_html__('Both, ACDC and Express Checkout', 'event_espresso'),
170
+			],
171
+			[
172
+				'html_name'  => "eep_checkout_type_option_$pm_slug",
173
+				'html_id'    => "eep_checkout_type_option_$pm_slug",
174
+				'html_class' => "eep-checkout-type-option-$pm_slug",
175
+				'required'   => true,
176
+				'default'    => PayPalExtraMetaManager::getPmOption(
177
+					$this->pm_instance,
178
+					Domain::META_KEY_ALLOWED_CHECKOUT_TYPE
179
+				),
180
+			]
181
+		);
182
+		return $form_parameters;
183
+	}
184 184
 
185 185
 
186
-    /**
187
-     * Add a checkout type select.
188
-     *
189
-     * @param array $form_parameters
190
-     * @return array
191
-     * @throws EE_Error
192
-     * @throws ReflectionException
193
-     */
194
-    public function addFundingOptions(array $form_parameters): array
195
-    {
196
-        $pm_slug               = $this->pm_instance->slug();
197
-        // Section to be displayed if onboard.
198
-        $form_parameters['extra_meta_inputs'][Domain::META_KEY_FUNDING_OPTIONS] = new EE_Checkbox_Multi_Input(
199
-            [
200
-                'venmo'    => esc_html__('Venmo', 'event_espresso'),
201
-                'paylater' => esc_html__('PayLater', 'event_espresso'),
202
-            ],
203
-            [
204
-                'html_name'       => "eep_checkout_funding_options_$pm_slug",
205
-                'html_id'         => "eep_checkout_funding_options_$pm_slug",
206
-                'html_class'      => "eep-checkout-funding-options-$pm_slug",
207
-                'html_label_text' => esc_html__('Enable PayPal funding options:', 'event_espresso'),
208
-                'default'         => ['venmo', 'paylater'],
209
-            ]
210
-        );
211
-        return $form_parameters;
212
-    }
186
+	/**
187
+	 * Add a checkout type select.
188
+	 *
189
+	 * @param array $form_parameters
190
+	 * @return array
191
+	 * @throws EE_Error
192
+	 * @throws ReflectionException
193
+	 */
194
+	public function addFundingOptions(array $form_parameters): array
195
+	{
196
+		$pm_slug               = $this->pm_instance->slug();
197
+		// Section to be displayed if onboard.
198
+		$form_parameters['extra_meta_inputs'][Domain::META_KEY_FUNDING_OPTIONS] = new EE_Checkbox_Multi_Input(
199
+			[
200
+				'venmo'    => esc_html__('Venmo', 'event_espresso'),
201
+				'paylater' => esc_html__('PayLater', 'event_espresso'),
202
+			],
203
+			[
204
+				'html_name'       => "eep_checkout_funding_options_$pm_slug",
205
+				'html_id'         => "eep_checkout_funding_options_$pm_slug",
206
+				'html_class'      => "eep-checkout-funding-options-$pm_slug",
207
+				'html_label_text' => esc_html__('Enable PayPal funding options:', 'event_espresso'),
208
+				'default'         => ['venmo', 'paylater'],
209
+			]
210
+		);
211
+		return $form_parameters;
212
+	}
213 213
 
214 214
 
215
-    /**
216
-     * Adds a button for clearing the PM metadata.
217
-     *
218
-     * @param EE_Payment_Method $pm_instance
219
-     * @return void
220
-     */
221
-    public function clearMetadataButton(EE_Payment_Method $pm_instance): void
222
-    {
223
-        try {
224
-            $is_onboard = EED_PayPalOnboard::isOnboard($pm_instance);
225
-            if ($is_onboard) {
226
-                return;
227
-            }
228
-            $button_text = sprintf(
229
-                esc_html__('Clear %1$s metadata', 'event_espresso'),
230
-                $pm_instance->admin_name()
231
-            );
232
-            $this->add_subsections(
233
-                [
234
-                    'clear_pm_metadata' => new EE_Form_Section_HTML(
235
-                        EEH_HTML::tr(
236
-                            EEH_HTML::th(esc_html__('Clear PM metadata ?', 'event_espresso')) .
237
-                            EEH_HTML::td(
238
-                                EEH_HTML::link(
239
-                                    '',
240
-                                    $button_text,
241
-                                    $button_text,
242
-                                    'eea_clear_metadata_' . $pm_instance->slug(),
243
-                                    'espresso-button button button--secondary'
244
-                                )
245
-                            )
246
-                        )
247
-                    ),
248
-                ],
249
-                'PMD_order',
250
-                false
251
-            );
252
-        } catch (EE_Error $e) {
253
-            // Don't add the button if there's some error.
254
-        }
255
-    }
215
+	/**
216
+	 * Adds a button for clearing the PM metadata.
217
+	 *
218
+	 * @param EE_Payment_Method $pm_instance
219
+	 * @return void
220
+	 */
221
+	public function clearMetadataButton(EE_Payment_Method $pm_instance): void
222
+	{
223
+		try {
224
+			$is_onboard = EED_PayPalOnboard::isOnboard($pm_instance);
225
+			if ($is_onboard) {
226
+				return;
227
+			}
228
+			$button_text = sprintf(
229
+				esc_html__('Clear %1$s metadata', 'event_espresso'),
230
+				$pm_instance->admin_name()
231
+			);
232
+			$this->add_subsections(
233
+				[
234
+					'clear_pm_metadata' => new EE_Form_Section_HTML(
235
+						EEH_HTML::tr(
236
+							EEH_HTML::th(esc_html__('Clear PM metadata ?', 'event_espresso')) .
237
+							EEH_HTML::td(
238
+								EEH_HTML::link(
239
+									'',
240
+									$button_text,
241
+									$button_text,
242
+									'eea_clear_metadata_' . $pm_instance->slug(),
243
+									'espresso-button button button--secondary'
244
+								)
245
+							)
246
+						)
247
+					),
248
+				],
249
+				'PMD_order',
250
+				false
251
+			);
252
+		} catch (EE_Error $e) {
253
+			// Don't add the button if there's some error.
254
+		}
255
+	}
256 256
 
257 257
 
258
-    /**
259
-     * Toggles subsections depending on the OAuth status etc.
260
-     *
261
-     * @param EE_Payment_Method $pm_instance
262
-     * @return void
263
-     * @throws EE_Error
264
-     */
265
-    private function toggleSubsections(EE_Payment_Method $pm_instance): void
266
-    {
267
-        $onboard = EED_PayPalOnboard::isOnboard($pm_instance);
268
-        // Don't allow changing the debug mode setting while connected.
269
-        if ($onboard) {
270
-            $debug_mode_input = $this->get_input('PMD_debug_mode', false);
271
-            if (method_exists($debug_mode_input, 'isDisabled')) {
272
-                $debug_mode_input->disable();
273
-            }
274
-        }
275
-    }
258
+	/**
259
+	 * Toggles subsections depending on the OAuth status etc.
260
+	 *
261
+	 * @param EE_Payment_Method $pm_instance
262
+	 * @return void
263
+	 * @throws EE_Error
264
+	 */
265
+	private function toggleSubsections(EE_Payment_Method $pm_instance): void
266
+	{
267
+		$onboard = EED_PayPalOnboard::isOnboard($pm_instance);
268
+		// Don't allow changing the debug mode setting while connected.
269
+		if ($onboard) {
270
+			$debug_mode_input = $this->get_input('PMD_debug_mode', false);
271
+			if (method_exists($debug_mode_input, 'isDisabled')) {
272
+				$debug_mode_input->disable();
273
+			}
274
+		}
275
+	}
276 276
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
      */
161 161
     public function addCheckoutTypeSelect(array $form_parameters): array
162 162
     {
163
-        $pm_slug               = $this->pm_instance->slug();
163
+        $pm_slug = $this->pm_instance->slug();
164 164
         // Section to be displayed if onboard.
165 165
         $form_parameters['extra_meta_inputs'][Domain::META_KEY_CHECKOUT_TYPE] = new EE_Select_Input(
166 166
             [
@@ -193,7 +193,7 @@  discard block
 block discarded – undo
193 193
      */
194 194
     public function addFundingOptions(array $form_parameters): array
195 195
     {
196
-        $pm_slug               = $this->pm_instance->slug();
196
+        $pm_slug = $this->pm_instance->slug();
197 197
         // Section to be displayed if onboard.
198 198
         $form_parameters['extra_meta_inputs'][Domain::META_KEY_FUNDING_OPTIONS] = new EE_Checkbox_Multi_Input(
199 199
             [
@@ -233,13 +233,13 @@  discard block
 block discarded – undo
233 233
                 [
234 234
                     'clear_pm_metadata' => new EE_Form_Section_HTML(
235 235
                         EEH_HTML::tr(
236
-                            EEH_HTML::th(esc_html__('Clear PM metadata ?', 'event_espresso')) .
236
+                            EEH_HTML::th(esc_html__('Clear PM metadata ?', 'event_espresso')).
237 237
                             EEH_HTML::td(
238 238
                                 EEH_HTML::link(
239 239
                                     '',
240 240
                                     $button_text,
241 241
                                     $button_text,
242
-                                    'eea_clear_metadata_' . $pm_instance->slug(),
242
+                                    'eea_clear_metadata_'.$pm_instance->slug(),
243 243
                                     'espresso-button button button--secondary'
244 244
                                 )
245 245
                             )
Please login to merge, or discard this patch.
PaymentMethods/PayPalCommerce/PayPalCheckout/forms/BillingForm.php 2 patches
Indentation   +567 added lines, -567 removed lines patch added patch discarded remove patch
@@ -38,571 +38,571 @@
 block discarded – undo
38 38
  */
39 39
 class BillingForm extends EE_Billing_Attendee_Info_Form
40 40
 {
41
-    protected EE_Payment_Method $paypal_pmt;
42
-
43
-    protected ?EE_Transaction $transaction = null;
44
-
45
-    protected string $checkout_type;
46
-
47
-    /**
48
-     * Filepath to template files
49
-     *
50
-     * @var string $template_path
51
-     */
52
-    protected string $template_path;
53
-
54
-
55
-    /**
56
-     * Class constructor.
57
-     *
58
-     * @param EE_Payment_Method    $payment_method
59
-     * @param array                $options
60
-     * @throws EE_Error
61
-     * @throws ReflectionException
62
-     */
63
-    public function __construct(EE_Payment_Method $payment_method, array $options)
64
-    {
65
-        $this->paypal_pmt    = $payment_method;
66
-        // Can't be too careful.
67
-        $this->transaction   = $options['transaction'] ?? null;
68
-        $this->template_path = $options['template_path'] ?? '';
69
-        $this->checkout_type = $payment_method->get_extra_meta(Domain::META_KEY_CHECKOUT_TYPE, true, '');
70
-        $pm_slug             = $payment_method->slug();
71
-        $parameters          = array_replace_recursive(
72
-            $options,
73
-            [
74
-                'name'        => 'PayPalCommerceBillingForm',
75
-                'html_id'     => 'pp-' . $pm_slug . '-billing-form',
76
-                'html_class'  => 'pp_commerce_billing_form',
77
-                'subsections' => [
78
-                    'eea_paypal_commerce_token' => new EE_Hidden_Input(
79
-                        [
80
-                            'html_id'   => 'eea-paypal-commerce-token',
81
-                            'html_name' => 'EEA_paymentToken',
82
-                            'default'   => '',
83
-                        ]
84
-                    ),
85
-                    'pp_order_nonce'            => new EE_Hidden_Input(
86
-                        [
87
-                            'html_id'   => 'eea-' . $pm_slug . '-order-nonce',
88
-                            'html_name' => 'pp_order_nonce',
89
-                            'default'   => '',
90
-                        ]
91
-                    ),
92
-                    'pp_order_id'               => new EE_Hidden_Input(
93
-                        [
94
-                            'html_id'   => 'eea-' . $pm_slug . '-order-id',
95
-                            'html_name' => 'pp_order_id',
96
-                            'default'   => '',
97
-                        ]
98
-                    ),
99
-                    'pp_order_status'           => new EE_Hidden_Input(
100
-                        [
101
-                            'html_id'   => 'eea-' . $pm_slug . '-order-status',
102
-                            'html_name' => 'pp_order_status',
103
-                            'default'   => '',
104
-                        ]
105
-                    ),
106
-                    'pp_order_amount'           => new EE_Hidden_Input(
107
-                        [
108
-                            'html_id'   => 'eea-' . $pm_slug . '-order-amount',
109
-                            'html_name' => 'pp_order_amount',
110
-                            'default'   => '',
111
-                        ]
112
-                    ),
113
-                ],
114
-            ]
115
-        );
116
-        // Add data tags to the PP script.
117
-        add_filter('script_loader_tag', [$this, 'addDataTagsToScript'], 10, 2);
118
-        parent::__construct($payment_method, $parameters);
119
-        // Add and exclude other sections.
120
-        $this->addPaymentSections();
121
-        // Additional actions and/or filters.
122
-        $this->loadActionsAndFilters();
123
-    }
124
-
125
-
126
-    /**
127
-     * Add PayPal payment sections.
128
-     *
129
-     * @return void
130
-     * @throws EE_Error
131
-     * @throws ReflectionException
132
-     */
133
-    public function addPaymentSections(): void
134
-    {
135
-        // Exclude the default billing form fields.
136
-        $this->exclude(
137
-            [
138
-                'first_name',
139
-                'last_name',
140
-                'email',
141
-            ]
142
-        );
143
-        // Add PayPal Hosted Fields.
144
-        if ($this->checkout_type !== 'express_checkout') {
145
-            $this->addAdvancedCardFields();
146
-        }
147
-        // Add payment types separator, if both are enabled.
148
-        if ($this->checkout_type === 'all') {
149
-            $this->addTypesSeparator();
150
-        }
151
-        // Add PayPal Buttons section.
152
-        if ($this->checkout_type !== 'ppcp') {
153
-            $this->add_subsections(
154
-                [
155
-                    'paypal_commerce_pm_form' => $this->addPayPalCheckout(),
156
-                ]
157
-            );
158
-        }
159
-        // Exclude the rest billing form fields if the payment type is express checkout.
160
-        if ($this->checkout_type === 'express_checkout') {
161
-            $this->exclude(
162
-                [
163
-                    'address',
164
-                    'address2',
165
-                    'state',
166
-                    'phone',
167
-                    'city',
168
-                    'country',
169
-                    'zip',
170
-                ]
171
-            );
172
-            // Remove the Info subsection.
173
-            add_filter('FHEE__EE_Form_Section_Proper___construct__options_array', [$this, 'excludeInfoSubsection']);
174
-        }
175
-        $this->add_subsections(
176
-            [
177
-                'debug_content' => $this->addDebugContent($this->paypal_pmt),
178
-            ]
179
-        );
180
-    }
181
-
182
-
183
-    /**
184
-     * Additional actions and/or filters.
185
-     *
186
-     * @return void
187
-     */
188
-    public function loadActionsAndFilters(): void
189
-    {
190
-        add_filter(
191
-            'FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
192
-            [__CLASS__, 'excludeBillingFormFields'],
193
-            10,
194
-            2
195
-        );
196
-    }
197
-
198
-
199
-    /**
200
-     * Filter out billing form fields if pay button was used.
201
-     *
202
-     * @param EE_Billing_Info_Form $billing_form
203
-     * @param EE_Payment_Method    $payment_method
204
-     * @return EE_Billing_Info_Form
205
-     */
206
-    public static function excludeBillingFormFields(
207
-        EE_Billing_Info_Form $billing_form,
208
-        EE_Payment_Method $payment_method
209
-    ): EE_Billing_Info_Form {
210
-        $request        = LoaderFactory::getShared(Request::class);
211
-        $request_params = $request->requestParams();
212
-        // Only the PPC billing form.
213
-        if (! $billing_form instanceof BillingForm) {
214
-            return $billing_form;
215
-        }
216
-        // Make sure the billing form subsections have correct names.
217
-        $inputs = $billing_form->inputs_in_subsections();
218
-        if (
219
-            ! empty($request_params['process_form_submission'])
220
-            && $request_params['process_form_submission'] === '1'
221
-            && ! empty($request_params['eep_ppc_skip_form_validation'])
222
-        ) {
223
-            // Hide card info fields.
224
-            $billing_form->exclude(
225
-                [
226
-                    'pp_name_on_card',
227
-                    'address',
228
-                    'address2',
229
-                    'state',
230
-                    'phone',
231
-                    'city',
232
-                    'country',
233
-                    'zip',
234
-                ]
235
-            );
236
-        }
237
-        return $billing_form;
238
-    }
239
-
240
-
241
-    /**
242
-     * Add advanced card & debit card fields.
243
-     *
244
-     * @return void
245
-     * @throws EE_Error|ReflectionException
246
-     */
247
-    public function addAdvancedCardFields(): void
248
-    {
249
-        $pm_slug = $this->paypal_pmt->slug();
250
-        $this->add_subsections(
251
-            [
252
-                'pp_card_number'     => new EE_Form_Section_HTML(
253
-                    EEH_HTML::label(
254
-                        esc_html__('Card Number', 'event_espresso'),
255
-                        "$pm_slug-card-number-lbl",
256
-                        "$pm_slug-card-fields",
257
-                        "",
258
-                        'for="' . $pm_slug . '-card-number"'
259
-                    ) .
260
-                    EEH_HTML::p(
261
-                        "",
262
-                        "$pm_slug-card-number",
263
-                        "card_field $pm_slug-card-fields"
264
-                    )
265
-                ),
266
-                'pp_expiration_date' => new EE_Form_Section_HTML(
267
-                    EEH_HTML::label(
268
-                        esc_html__('Expiration Date', 'event_espresso'),
269
-                        "$pm_slug-expiration-date-lbl",
270
-                        "$pm_slug-card-fields",
271
-                        "",
272
-                        'for="' . $pm_slug . '-expiration-date"'
273
-                    ) .
274
-                    EEH_HTML::p(
275
-                        "",
276
-                        "$pm_slug-expiration-date",
277
-                        "card_field $pm_slug-card-fields"
278
-                    )
279
-                ),
280
-                'pp_card_cvv'        => new EE_Form_Section_HTML(
281
-                    EEH_HTML::label(
282
-                        esc_html__('CVV', 'event_espresso'),
283
-                        "$pm_slug-cvv-lbl",
284
-                        "$pm_slug-card-fields",
285
-                        "",
286
-                        'for="' . $pm_slug . '-cvv"'
287
-                    ) .
288
-                    EEH_HTML::p(
289
-                        "",
290
-                        "$pm_slug-cvv",
291
-                        "card_field $pm_slug-card-fields"
292
-                    )
293
-                ),
294
-                'pp_name_on_card'    => new EE_Text_Input(
295
-                    [
296
-                        'html_label_text' => esc_html__('Name On Card', 'event_espresso'),
297
-                        'html_id'         => $pm_slug . '-card-holder-name',
298
-                        'html_name'       => 'card-holder-name',
299
-                        'html_class'      => '',
300
-                        'required'        => true,
301
-                    ]
302
-                ),
303
-            ]
304
-        );
305
-        // Add the submit button at the end.
306
-        $this->add_subsections(
307
-            [
308
-                'pp_cc_submit' => new EE_Submit_Input(
309
-                    [
310
-                        'html_label_text' => esc_html__('Submit', 'event_espresso'),
311
-                        'html_id'         => $pm_slug,
312
-                        'html_class'      => 'eep-ppc-btn',
313
-                    ]
314
-                ),
315
-            ],
316
-            'phone',
317
-            false
318
-        );
319
-    }
320
-
321
-
322
-    /**
323
-     * Add advanced card & debit card fields.
324
-     *
325
-     * @return void
326
-     * @throws EE_Error|ReflectionException
327
-     */
328
-    public function addTypesSeparator(): void
329
-    {
330
-        $this->add_subsections(
331
-            [
332
-                'pp_payment_types_separator' => new EE_Form_Section_HTML(
333
-                    EEH_HTML::div(
334
-                        EEH_HTML::div(
335
-                            ' ',
336
-                            'eep-' . $this->paypal_pmt->slug() . '-payments-separator',
337
-                            'eep-ppc-separator-line eep-left-floating'
338
-                        ) .
339
-                        EEH_HTML::div(
340
-                            esc_html__(' or ', 'event_espresso'),
341
-                            'eep-' . $this->paypal_pmt->slug() . '-separator-text',
342
-                            'eep-ppc-separator-text1 eep-mid-floating'
343
-                        ) . EEH_HTML::div(
344
-                            ' ',
345
-                            'eep-' . $this->paypal_pmt->slug() . '-payments-separator',
346
-                            'eep-ppc-separator-line eep-right-floating'
347
-                        ),
348
-                        'eep-ppc-separator-holder',
349
-                        'eep-ppc-separator-holder'
350
-                    )
351
-                ),
352
-            ]
353
-        );
354
-    }
355
-
356
-
357
-    /**
358
-     * Exclude the info subsection from the PPC checkout form.
359
-     *
360
-     * @param array $options_array
361
-     * @return array
362
-     * @throws EE_Error
363
-     * @throws ReflectionException
364
-     */
365
-    public function excludeInfoSubsection(array $options_array): array
366
-    {
367
-        if (
368
-            ! empty($options_array['html_id'])
369
-            && $options_array['html_id'] === 'spco-payment-method-info-' . $this->paypal_pmt->slug()
370
-        ) {
371
-            if (! empty($options_array['subsections']) && isset($options_array['subsections']['info'])) {
372
-                unset($options_array['subsections']['info']);
373
-            }
374
-        }
375
-        return $options_array;
376
-    }
377
-
378
-
379
-    /**
380
-     * Possibly adds debug content to PayPal commerce billing form.
381
-     *
382
-     * @param EE_Payment_Method $paypal_pm
383
-     * @return EE_Form_Section_Base
384
-     * @throws EE_Error|ReflectionException
385
-     */
386
-    public function addDebugContent(EE_Payment_Method $paypal_pm): EE_Form_Section_Base
387
-    {
388
-        if ($paypal_pm->debug_mode()) {
389
-            return new EE_Form_Section_Proper(
390
-                [
391
-                    'layout_strategy' => new EE_Template_Layout(
392
-                        [
393
-                            'layout_template_file' => $this->template_path . 'debugInfo.template.php',
394
-                            'template_args'        => [],
395
-                        ]
396
-                    ),
397
-                ]
398
-            );
399
-        }
400
-        return new EE_Form_Section_HTML();
401
-    }
402
-
403
-
404
-    /**
405
-     * Add PayPal checkout buttons.
406
-     *
407
-     * @return EE_Form_Section_Proper
408
-     * @throws EE_Error
409
-     * @throws ReflectionException
410
-     * @throws Exception
411
-     */
412
-    public function addPayPalCheckout(): EE_Form_Section_Proper
413
-    {
414
-        $template_args['pm_slug']     = $this->paypal_pmt->slug();
415
-        return new EE_Form_Section_Proper(
416
-            [
417
-                'layout_strategy' => new EE_Template_Layout(
418
-                    [
419
-                        'layout_template_file' => $this->template_path . 'paymentButtons.template.php',
420
-                        'template_args'        => $template_args,
421
-                    ]
422
-                ),
423
-            ]
424
-        );
425
-    }
426
-
427
-
428
-    /**
429
-     * Load scripts and localize data needed for this form.
430
-     *
431
-     * @param $tag
432
-     * @param $handle
433
-     * @return string
434
-     * @throws EE_Error
435
-     * @throws ReflectionException
436
-     */
437
-    public function addDataTagsToScript($tag, $handle): string
438
-    {
439
-        if ($handle === 'eea_paypal_commerce_js_lib') {
440
-            $bn_code  = PayPalExtraMetaManager::getPmOption($this->_pm_instance, Domain::META_KEY_BN_CODE);
441
-            $response = EED_PayPalCommerce::requestClientToken($this->paypal_pmt);
442
-            if (empty($response['client_token'])) {
443
-                return $tag;
444
-            }
445
-            $client_token = $response['client_token'];
446
-            $attributes   = " data-partner-attribution-id=\"$bn_code\" data-client-token=\"$client_token\"";
447
-            $tag          = str_replace('></script>', $attributes . '></script>', $tag);
448
-        }
449
-        return $tag;
450
-    }
451
-
452
-
453
-    /**
454
-     * Load scripts and localize data needed for this form.
455
-     *
456
-     * @return void
457
-     * @throws EE_Error
458
-     * @throws ReflectionException
459
-     * @throws Exception
460
-     */
461
-    public function enqueue_js(): void
462
-    {
463
-        // Setup default values
464
-        $client_id_key = Domain::META_KEY_CLIENT_ID;
465
-        $merchant_id   = false;
466
-        $funding_options = ['venmo', 'paylater'];
467
-
468
-        // Override the above if thrid party integration
469
-        if (EED_PayPalCommerce::isThirdParty($this->_pm_instance)) {
470
-            $client_id_key = Domain::META_KEY_PARTNER_CLIENT_ID;
471
-            $merchant_id   = PayPalExtraMetaManager::getPmOption(
472
-                $this->_pm_instance,
473
-                Domain::META_KEY_SELLER_MERCHANT_ID
474
-            );
475
-        }
476
-
477
-        // Setup query args
478
-        $url_params            = [
479
-            'client-id'        => PayPalExtraMetaManager::getPmOption($this->_pm_instance, $client_id_key),
480
-            'currency'         => CurrencyManager::currencyCode(),
481
-            'components'       => implode(',', ['buttons','hosted-fields']),
482
-            'intent'           => 'capture',
483
-            'merchant-id'      => $merchant_id,
484
-        ];
485
-
486
-        // Which funding methods are active?
487
-        $enabled_funding = $this->_pm_instance->get_extra_meta(Domain::META_KEY_FUNDING_OPTIONS, true, $funding_options);
488
-
489
-        // Any funding method not enabled should be disabled.
490
-        $disabled_funding = array_diff(
491
-            $funding_options,
492
-            $enabled_funding
493
-        );
494
-
495
-        // Any funding options enabled?
496
-        if (count($enabled_funding) > 0) {
497
-            $url_params['enable-funding'] = implode(',', $enabled_funding);
498
-        }
499
-
500
-        // Any funding options disabled?
501
-        if (count($disabled_funding) > 0) {
502
-            $url_params['disable-funding'] = implode(',', $disabled_funding);
503
-        }
504
-
505
-        // Enqueue the PayPal JS
506
-        wp_enqueue_script(
507
-            'eea_paypal_commerce_js_lib',
508
-            add_query_arg($url_params, 'https://www.paypal.com/sdk/js'),
509
-            [],
510
-            null
511
-        );
512
-
513
-        wp_enqueue_script(
514
-            'eea_paypal_commerce_js',
515
-            EEP_PAYPAL_COMMERCE_URL . 'assets/js/paypal-commerce-payments.js',
516
-            ['eea_paypal_commerce_js_lib'],
517
-            EVENT_ESPRESSO_VERSION,
518
-            true
519
-        );
520
-        // Styles.
521
-        wp_enqueue_style(
522
-            'eea_paypal_checkout_form_styles',
523
-            EEP_PAYPAL_COMMERCE_URL . 'assets' . DS . 'css' . DS . 'eea-paypal-checkout.css',
524
-            [],
525
-            EVENT_ESPRESSO_VERSION
526
-        );
527
-        // Localize the script with our transaction data.
528
-        $parameters = $this->localizeParameters();
529
-        wp_localize_script('eea_paypal_commerce_js', 'eeaPPCommerceParameters', $parameters);
530
-        parent::enqueue_js();
531
-    }
532
-
533
-
534
-    /**
535
-     * Form and return PayPal commerce parameters for script localization.
536
-     *
537
-     * @return array
538
-     * @throws EE_Error
539
-     * @throws ReflectionException
540
-     * @throws Exception
541
-     */
542
-    public function localizeParameters(): array
543
-    {
544
-        // Also tell the script about each instance of this PM.
545
-        $pm_versions            = [];
546
-        $active_payment_methods = EEM_Payment_Method::instance()->get_all_active(
547
-            EEM_Payment_Method::scope_cart,
548
-            [['PMD_slug' => ['LIKE', '%paypalcheckout%']]]
549
-        );
550
-        foreach ($active_payment_methods as $payment_method) {
551
-            $pm_versions[ $payment_method->slug() ] = [
552
-                'pm_slug' => $payment_method->slug(),
553
-            ];
554
-        }
555
-        // Convert money for a display format.
556
-        $decimal_places = CurrencyManager::getDecimalPlaces();
557
-        $org_country    = isset(EE_Registry::instance()->CFG->organization)
558
-        && EE_Registry::instance()->CFG->organization instanceof EE_Organization_Config
559
-            ? EE_Registry::instance()->CFG->organization->CNT_ISO
560
-            : 'US';
561
-        $transaction_id = $this->transaction instanceof EE_Transaction ? $this->transaction->ID() : 0;
562
-        $currency_code  = CurrencyManager::currencyCode();
563
-        return [
564
-            'pm_versions'            => $pm_versions,
565
-            'payment_currency'       => $currency_code,
566
-            'checkout_type'          => $this->checkout_type,
567
-            'currency_sign'          => EE_Registry::instance()->CFG->currency->sign,
568
-            'pp_order_nonce'         => wp_create_nonce(Domain::CAPTURE_ORDER_NONCE_NAME),
569
-            // The transaction ID is only used for logging errors.
570
-            'txn_id'                 => $transaction_id,
571
-            'org_country'            => $org_country,
572
-            'decimal_places'         => $decimal_places,
573
-            'site_name'              => get_bloginfo('name'),
574
-            'active_states'          => EED_PayPalCommerce::getActiveStates(),
575
-            'no_spco_error'          => esc_html__(
576
-                'It appears the SDK script was not loaded properly! Please refresh the page and try again or contact support.',
577
-                'event_espresso'
578
-            ),
579
-            'no_pm_error'            => esc_html__(
580
-                'It appears that PayPal Commerce checkout JavaScript was not loaded properly! Please refresh the page and try again or contact support. PayPal Commerce payments can\'t be processed.',
581
-                'event_espresso'
582
-            ),
583
-            'browser_not_supported'  => esc_html__(
584
-                'It appears that this browser is not supported by PayPal scripts. We apologize, but PayPal payments won\'t work in this browser version.',
585
-                'event_espresso'
586
-            ),
587
-            'get_token_error'        => esc_html__(
588
-                'There was an error while trying to get the payment token. Please refresh the page and try again or contact support.',
589
-                'event_espresso'
590
-            ),
591
-            'form_validation_notice' => esc_html__('Billing form information not valid.', 'event_espresso'),
592
-            'no_verification_token'  => esc_html__('Missing the Verification token.', 'event_espresso'),
593
-            'error_response'         => esc_html__('Error response received', 'event_espresso'),
594
-            'payment_error'          => esc_html__(
595
-                'There was an error with this payment. See the logs for details.',
596
-                'event_espresso'
597
-            ),
598
-            'no_order_id'            => esc_html__('No Order ID found.', 'event_espresso'),
599
-            'general_pp_error'       => esc_html__('PayPal form threw an error.', 'event_espresso'),
600
-            'hf_render_error'        => esc_html__('Hosted fields could not be rendered!', 'event_espresso'),
601
-            'pm_capture_error'       => esc_html__('Payment could not be captured!', 'event_espresso'),
602
-            'not_acdc_eligible'      => esc_html__(
603
-                'This merchant is not eligible for Advanced Card Fields checkout type.',
604
-                'event_espresso'
605
-            ),
606
-        ];
607
-    }
41
+	protected EE_Payment_Method $paypal_pmt;
42
+
43
+	protected ?EE_Transaction $transaction = null;
44
+
45
+	protected string $checkout_type;
46
+
47
+	/**
48
+	 * Filepath to template files
49
+	 *
50
+	 * @var string $template_path
51
+	 */
52
+	protected string $template_path;
53
+
54
+
55
+	/**
56
+	 * Class constructor.
57
+	 *
58
+	 * @param EE_Payment_Method    $payment_method
59
+	 * @param array                $options
60
+	 * @throws EE_Error
61
+	 * @throws ReflectionException
62
+	 */
63
+	public function __construct(EE_Payment_Method $payment_method, array $options)
64
+	{
65
+		$this->paypal_pmt    = $payment_method;
66
+		// Can't be too careful.
67
+		$this->transaction   = $options['transaction'] ?? null;
68
+		$this->template_path = $options['template_path'] ?? '';
69
+		$this->checkout_type = $payment_method->get_extra_meta(Domain::META_KEY_CHECKOUT_TYPE, true, '');
70
+		$pm_slug             = $payment_method->slug();
71
+		$parameters          = array_replace_recursive(
72
+			$options,
73
+			[
74
+				'name'        => 'PayPalCommerceBillingForm',
75
+				'html_id'     => 'pp-' . $pm_slug . '-billing-form',
76
+				'html_class'  => 'pp_commerce_billing_form',
77
+				'subsections' => [
78
+					'eea_paypal_commerce_token' => new EE_Hidden_Input(
79
+						[
80
+							'html_id'   => 'eea-paypal-commerce-token',
81
+							'html_name' => 'EEA_paymentToken',
82
+							'default'   => '',
83
+						]
84
+					),
85
+					'pp_order_nonce'            => new EE_Hidden_Input(
86
+						[
87
+							'html_id'   => 'eea-' . $pm_slug . '-order-nonce',
88
+							'html_name' => 'pp_order_nonce',
89
+							'default'   => '',
90
+						]
91
+					),
92
+					'pp_order_id'               => new EE_Hidden_Input(
93
+						[
94
+							'html_id'   => 'eea-' . $pm_slug . '-order-id',
95
+							'html_name' => 'pp_order_id',
96
+							'default'   => '',
97
+						]
98
+					),
99
+					'pp_order_status'           => new EE_Hidden_Input(
100
+						[
101
+							'html_id'   => 'eea-' . $pm_slug . '-order-status',
102
+							'html_name' => 'pp_order_status',
103
+							'default'   => '',
104
+						]
105
+					),
106
+					'pp_order_amount'           => new EE_Hidden_Input(
107
+						[
108
+							'html_id'   => 'eea-' . $pm_slug . '-order-amount',
109
+							'html_name' => 'pp_order_amount',
110
+							'default'   => '',
111
+						]
112
+					),
113
+				],
114
+			]
115
+		);
116
+		// Add data tags to the PP script.
117
+		add_filter('script_loader_tag', [$this, 'addDataTagsToScript'], 10, 2);
118
+		parent::__construct($payment_method, $parameters);
119
+		// Add and exclude other sections.
120
+		$this->addPaymentSections();
121
+		// Additional actions and/or filters.
122
+		$this->loadActionsAndFilters();
123
+	}
124
+
125
+
126
+	/**
127
+	 * Add PayPal payment sections.
128
+	 *
129
+	 * @return void
130
+	 * @throws EE_Error
131
+	 * @throws ReflectionException
132
+	 */
133
+	public function addPaymentSections(): void
134
+	{
135
+		// Exclude the default billing form fields.
136
+		$this->exclude(
137
+			[
138
+				'first_name',
139
+				'last_name',
140
+				'email',
141
+			]
142
+		);
143
+		// Add PayPal Hosted Fields.
144
+		if ($this->checkout_type !== 'express_checkout') {
145
+			$this->addAdvancedCardFields();
146
+		}
147
+		// Add payment types separator, if both are enabled.
148
+		if ($this->checkout_type === 'all') {
149
+			$this->addTypesSeparator();
150
+		}
151
+		// Add PayPal Buttons section.
152
+		if ($this->checkout_type !== 'ppcp') {
153
+			$this->add_subsections(
154
+				[
155
+					'paypal_commerce_pm_form' => $this->addPayPalCheckout(),
156
+				]
157
+			);
158
+		}
159
+		// Exclude the rest billing form fields if the payment type is express checkout.
160
+		if ($this->checkout_type === 'express_checkout') {
161
+			$this->exclude(
162
+				[
163
+					'address',
164
+					'address2',
165
+					'state',
166
+					'phone',
167
+					'city',
168
+					'country',
169
+					'zip',
170
+				]
171
+			);
172
+			// Remove the Info subsection.
173
+			add_filter('FHEE__EE_Form_Section_Proper___construct__options_array', [$this, 'excludeInfoSubsection']);
174
+		}
175
+		$this->add_subsections(
176
+			[
177
+				'debug_content' => $this->addDebugContent($this->paypal_pmt),
178
+			]
179
+		);
180
+	}
181
+
182
+
183
+	/**
184
+	 * Additional actions and/or filters.
185
+	 *
186
+	 * @return void
187
+	 */
188
+	public function loadActionsAndFilters(): void
189
+	{
190
+		add_filter(
191
+			'FHEE__EE_SPCO_Reg_Step_Payment_Options___get_billing_form_for_payment_method__billing_form',
192
+			[__CLASS__, 'excludeBillingFormFields'],
193
+			10,
194
+			2
195
+		);
196
+	}
197
+
198
+
199
+	/**
200
+	 * Filter out billing form fields if pay button was used.
201
+	 *
202
+	 * @param EE_Billing_Info_Form $billing_form
203
+	 * @param EE_Payment_Method    $payment_method
204
+	 * @return EE_Billing_Info_Form
205
+	 */
206
+	public static function excludeBillingFormFields(
207
+		EE_Billing_Info_Form $billing_form,
208
+		EE_Payment_Method $payment_method
209
+	): EE_Billing_Info_Form {
210
+		$request        = LoaderFactory::getShared(Request::class);
211
+		$request_params = $request->requestParams();
212
+		// Only the PPC billing form.
213
+		if (! $billing_form instanceof BillingForm) {
214
+			return $billing_form;
215
+		}
216
+		// Make sure the billing form subsections have correct names.
217
+		$inputs = $billing_form->inputs_in_subsections();
218
+		if (
219
+			! empty($request_params['process_form_submission'])
220
+			&& $request_params['process_form_submission'] === '1'
221
+			&& ! empty($request_params['eep_ppc_skip_form_validation'])
222
+		) {
223
+			// Hide card info fields.
224
+			$billing_form->exclude(
225
+				[
226
+					'pp_name_on_card',
227
+					'address',
228
+					'address2',
229
+					'state',
230
+					'phone',
231
+					'city',
232
+					'country',
233
+					'zip',
234
+				]
235
+			);
236
+		}
237
+		return $billing_form;
238
+	}
239
+
240
+
241
+	/**
242
+	 * Add advanced card & debit card fields.
243
+	 *
244
+	 * @return void
245
+	 * @throws EE_Error|ReflectionException
246
+	 */
247
+	public function addAdvancedCardFields(): void
248
+	{
249
+		$pm_slug = $this->paypal_pmt->slug();
250
+		$this->add_subsections(
251
+			[
252
+				'pp_card_number'     => new EE_Form_Section_HTML(
253
+					EEH_HTML::label(
254
+						esc_html__('Card Number', 'event_espresso'),
255
+						"$pm_slug-card-number-lbl",
256
+						"$pm_slug-card-fields",
257
+						"",
258
+						'for="' . $pm_slug . '-card-number"'
259
+					) .
260
+					EEH_HTML::p(
261
+						"",
262
+						"$pm_slug-card-number",
263
+						"card_field $pm_slug-card-fields"
264
+					)
265
+				),
266
+				'pp_expiration_date' => new EE_Form_Section_HTML(
267
+					EEH_HTML::label(
268
+						esc_html__('Expiration Date', 'event_espresso'),
269
+						"$pm_slug-expiration-date-lbl",
270
+						"$pm_slug-card-fields",
271
+						"",
272
+						'for="' . $pm_slug . '-expiration-date"'
273
+					) .
274
+					EEH_HTML::p(
275
+						"",
276
+						"$pm_slug-expiration-date",
277
+						"card_field $pm_slug-card-fields"
278
+					)
279
+				),
280
+				'pp_card_cvv'        => new EE_Form_Section_HTML(
281
+					EEH_HTML::label(
282
+						esc_html__('CVV', 'event_espresso'),
283
+						"$pm_slug-cvv-lbl",
284
+						"$pm_slug-card-fields",
285
+						"",
286
+						'for="' . $pm_slug . '-cvv"'
287
+					) .
288
+					EEH_HTML::p(
289
+						"",
290
+						"$pm_slug-cvv",
291
+						"card_field $pm_slug-card-fields"
292
+					)
293
+				),
294
+				'pp_name_on_card'    => new EE_Text_Input(
295
+					[
296
+						'html_label_text' => esc_html__('Name On Card', 'event_espresso'),
297
+						'html_id'         => $pm_slug . '-card-holder-name',
298
+						'html_name'       => 'card-holder-name',
299
+						'html_class'      => '',
300
+						'required'        => true,
301
+					]
302
+				),
303
+			]
304
+		);
305
+		// Add the submit button at the end.
306
+		$this->add_subsections(
307
+			[
308
+				'pp_cc_submit' => new EE_Submit_Input(
309
+					[
310
+						'html_label_text' => esc_html__('Submit', 'event_espresso'),
311
+						'html_id'         => $pm_slug,
312
+						'html_class'      => 'eep-ppc-btn',
313
+					]
314
+				),
315
+			],
316
+			'phone',
317
+			false
318
+		);
319
+	}
320
+
321
+
322
+	/**
323
+	 * Add advanced card & debit card fields.
324
+	 *
325
+	 * @return void
326
+	 * @throws EE_Error|ReflectionException
327
+	 */
328
+	public function addTypesSeparator(): void
329
+	{
330
+		$this->add_subsections(
331
+			[
332
+				'pp_payment_types_separator' => new EE_Form_Section_HTML(
333
+					EEH_HTML::div(
334
+						EEH_HTML::div(
335
+							' ',
336
+							'eep-' . $this->paypal_pmt->slug() . '-payments-separator',
337
+							'eep-ppc-separator-line eep-left-floating'
338
+						) .
339
+						EEH_HTML::div(
340
+							esc_html__(' or ', 'event_espresso'),
341
+							'eep-' . $this->paypal_pmt->slug() . '-separator-text',
342
+							'eep-ppc-separator-text1 eep-mid-floating'
343
+						) . EEH_HTML::div(
344
+							' ',
345
+							'eep-' . $this->paypal_pmt->slug() . '-payments-separator',
346
+							'eep-ppc-separator-line eep-right-floating'
347
+						),
348
+						'eep-ppc-separator-holder',
349
+						'eep-ppc-separator-holder'
350
+					)
351
+				),
352
+			]
353
+		);
354
+	}
355
+
356
+
357
+	/**
358
+	 * Exclude the info subsection from the PPC checkout form.
359
+	 *
360
+	 * @param array $options_array
361
+	 * @return array
362
+	 * @throws EE_Error
363
+	 * @throws ReflectionException
364
+	 */
365
+	public function excludeInfoSubsection(array $options_array): array
366
+	{
367
+		if (
368
+			! empty($options_array['html_id'])
369
+			&& $options_array['html_id'] === 'spco-payment-method-info-' . $this->paypal_pmt->slug()
370
+		) {
371
+			if (! empty($options_array['subsections']) && isset($options_array['subsections']['info'])) {
372
+				unset($options_array['subsections']['info']);
373
+			}
374
+		}
375
+		return $options_array;
376
+	}
377
+
378
+
379
+	/**
380
+	 * Possibly adds debug content to PayPal commerce billing form.
381
+	 *
382
+	 * @param EE_Payment_Method $paypal_pm
383
+	 * @return EE_Form_Section_Base
384
+	 * @throws EE_Error|ReflectionException
385
+	 */
386
+	public function addDebugContent(EE_Payment_Method $paypal_pm): EE_Form_Section_Base
387
+	{
388
+		if ($paypal_pm->debug_mode()) {
389
+			return new EE_Form_Section_Proper(
390
+				[
391
+					'layout_strategy' => new EE_Template_Layout(
392
+						[
393
+							'layout_template_file' => $this->template_path . 'debugInfo.template.php',
394
+							'template_args'        => [],
395
+						]
396
+					),
397
+				]
398
+			);
399
+		}
400
+		return new EE_Form_Section_HTML();
401
+	}
402
+
403
+
404
+	/**
405
+	 * Add PayPal checkout buttons.
406
+	 *
407
+	 * @return EE_Form_Section_Proper
408
+	 * @throws EE_Error
409
+	 * @throws ReflectionException
410
+	 * @throws Exception
411
+	 */
412
+	public function addPayPalCheckout(): EE_Form_Section_Proper
413
+	{
414
+		$template_args['pm_slug']     = $this->paypal_pmt->slug();
415
+		return new EE_Form_Section_Proper(
416
+			[
417
+				'layout_strategy' => new EE_Template_Layout(
418
+					[
419
+						'layout_template_file' => $this->template_path . 'paymentButtons.template.php',
420
+						'template_args'        => $template_args,
421
+					]
422
+				),
423
+			]
424
+		);
425
+	}
426
+
427
+
428
+	/**
429
+	 * Load scripts and localize data needed for this form.
430
+	 *
431
+	 * @param $tag
432
+	 * @param $handle
433
+	 * @return string
434
+	 * @throws EE_Error
435
+	 * @throws ReflectionException
436
+	 */
437
+	public function addDataTagsToScript($tag, $handle): string
438
+	{
439
+		if ($handle === 'eea_paypal_commerce_js_lib') {
440
+			$bn_code  = PayPalExtraMetaManager::getPmOption($this->_pm_instance, Domain::META_KEY_BN_CODE);
441
+			$response = EED_PayPalCommerce::requestClientToken($this->paypal_pmt);
442
+			if (empty($response['client_token'])) {
443
+				return $tag;
444
+			}
445
+			$client_token = $response['client_token'];
446
+			$attributes   = " data-partner-attribution-id=\"$bn_code\" data-client-token=\"$client_token\"";
447
+			$tag          = str_replace('></script>', $attributes . '></script>', $tag);
448
+		}
449
+		return $tag;
450
+	}
451
+
452
+
453
+	/**
454
+	 * Load scripts and localize data needed for this form.
455
+	 *
456
+	 * @return void
457
+	 * @throws EE_Error
458
+	 * @throws ReflectionException
459
+	 * @throws Exception
460
+	 */
461
+	public function enqueue_js(): void
462
+	{
463
+		// Setup default values
464
+		$client_id_key = Domain::META_KEY_CLIENT_ID;
465
+		$merchant_id   = false;
466
+		$funding_options = ['venmo', 'paylater'];
467
+
468
+		// Override the above if thrid party integration
469
+		if (EED_PayPalCommerce::isThirdParty($this->_pm_instance)) {
470
+			$client_id_key = Domain::META_KEY_PARTNER_CLIENT_ID;
471
+			$merchant_id   = PayPalExtraMetaManager::getPmOption(
472
+				$this->_pm_instance,
473
+				Domain::META_KEY_SELLER_MERCHANT_ID
474
+			);
475
+		}
476
+
477
+		// Setup query args
478
+		$url_params            = [
479
+			'client-id'        => PayPalExtraMetaManager::getPmOption($this->_pm_instance, $client_id_key),
480
+			'currency'         => CurrencyManager::currencyCode(),
481
+			'components'       => implode(',', ['buttons','hosted-fields']),
482
+			'intent'           => 'capture',
483
+			'merchant-id'      => $merchant_id,
484
+		];
485
+
486
+		// Which funding methods are active?
487
+		$enabled_funding = $this->_pm_instance->get_extra_meta(Domain::META_KEY_FUNDING_OPTIONS, true, $funding_options);
488
+
489
+		// Any funding method not enabled should be disabled.
490
+		$disabled_funding = array_diff(
491
+			$funding_options,
492
+			$enabled_funding
493
+		);
494
+
495
+		// Any funding options enabled?
496
+		if (count($enabled_funding) > 0) {
497
+			$url_params['enable-funding'] = implode(',', $enabled_funding);
498
+		}
499
+
500
+		// Any funding options disabled?
501
+		if (count($disabled_funding) > 0) {
502
+			$url_params['disable-funding'] = implode(',', $disabled_funding);
503
+		}
504
+
505
+		// Enqueue the PayPal JS
506
+		wp_enqueue_script(
507
+			'eea_paypal_commerce_js_lib',
508
+			add_query_arg($url_params, 'https://www.paypal.com/sdk/js'),
509
+			[],
510
+			null
511
+		);
512
+
513
+		wp_enqueue_script(
514
+			'eea_paypal_commerce_js',
515
+			EEP_PAYPAL_COMMERCE_URL . 'assets/js/paypal-commerce-payments.js',
516
+			['eea_paypal_commerce_js_lib'],
517
+			EVENT_ESPRESSO_VERSION,
518
+			true
519
+		);
520
+		// Styles.
521
+		wp_enqueue_style(
522
+			'eea_paypal_checkout_form_styles',
523
+			EEP_PAYPAL_COMMERCE_URL . 'assets' . DS . 'css' . DS . 'eea-paypal-checkout.css',
524
+			[],
525
+			EVENT_ESPRESSO_VERSION
526
+		);
527
+		// Localize the script with our transaction data.
528
+		$parameters = $this->localizeParameters();
529
+		wp_localize_script('eea_paypal_commerce_js', 'eeaPPCommerceParameters', $parameters);
530
+		parent::enqueue_js();
531
+	}
532
+
533
+
534
+	/**
535
+	 * Form and return PayPal commerce parameters for script localization.
536
+	 *
537
+	 * @return array
538
+	 * @throws EE_Error
539
+	 * @throws ReflectionException
540
+	 * @throws Exception
541
+	 */
542
+	public function localizeParameters(): array
543
+	{
544
+		// Also tell the script about each instance of this PM.
545
+		$pm_versions            = [];
546
+		$active_payment_methods = EEM_Payment_Method::instance()->get_all_active(
547
+			EEM_Payment_Method::scope_cart,
548
+			[['PMD_slug' => ['LIKE', '%paypalcheckout%']]]
549
+		);
550
+		foreach ($active_payment_methods as $payment_method) {
551
+			$pm_versions[ $payment_method->slug() ] = [
552
+				'pm_slug' => $payment_method->slug(),
553
+			];
554
+		}
555
+		// Convert money for a display format.
556
+		$decimal_places = CurrencyManager::getDecimalPlaces();
557
+		$org_country    = isset(EE_Registry::instance()->CFG->organization)
558
+		&& EE_Registry::instance()->CFG->organization instanceof EE_Organization_Config
559
+			? EE_Registry::instance()->CFG->organization->CNT_ISO
560
+			: 'US';
561
+		$transaction_id = $this->transaction instanceof EE_Transaction ? $this->transaction->ID() : 0;
562
+		$currency_code  = CurrencyManager::currencyCode();
563
+		return [
564
+			'pm_versions'            => $pm_versions,
565
+			'payment_currency'       => $currency_code,
566
+			'checkout_type'          => $this->checkout_type,
567
+			'currency_sign'          => EE_Registry::instance()->CFG->currency->sign,
568
+			'pp_order_nonce'         => wp_create_nonce(Domain::CAPTURE_ORDER_NONCE_NAME),
569
+			// The transaction ID is only used for logging errors.
570
+			'txn_id'                 => $transaction_id,
571
+			'org_country'            => $org_country,
572
+			'decimal_places'         => $decimal_places,
573
+			'site_name'              => get_bloginfo('name'),
574
+			'active_states'          => EED_PayPalCommerce::getActiveStates(),
575
+			'no_spco_error'          => esc_html__(
576
+				'It appears the SDK script was not loaded properly! Please refresh the page and try again or contact support.',
577
+				'event_espresso'
578
+			),
579
+			'no_pm_error'            => esc_html__(
580
+				'It appears that PayPal Commerce checkout JavaScript was not loaded properly! Please refresh the page and try again or contact support. PayPal Commerce payments can\'t be processed.',
581
+				'event_espresso'
582
+			),
583
+			'browser_not_supported'  => esc_html__(
584
+				'It appears that this browser is not supported by PayPal scripts. We apologize, but PayPal payments won\'t work in this browser version.',
585
+				'event_espresso'
586
+			),
587
+			'get_token_error'        => esc_html__(
588
+				'There was an error while trying to get the payment token. Please refresh the page and try again or contact support.',
589
+				'event_espresso'
590
+			),
591
+			'form_validation_notice' => esc_html__('Billing form information not valid.', 'event_espresso'),
592
+			'no_verification_token'  => esc_html__('Missing the Verification token.', 'event_espresso'),
593
+			'error_response'         => esc_html__('Error response received', 'event_espresso'),
594
+			'payment_error'          => esc_html__(
595
+				'There was an error with this payment. See the logs for details.',
596
+				'event_espresso'
597
+			),
598
+			'no_order_id'            => esc_html__('No Order ID found.', 'event_espresso'),
599
+			'general_pp_error'       => esc_html__('PayPal form threw an error.', 'event_espresso'),
600
+			'hf_render_error'        => esc_html__('Hosted fields could not be rendered!', 'event_espresso'),
601
+			'pm_capture_error'       => esc_html__('Payment could not be captured!', 'event_espresso'),
602
+			'not_acdc_eligible'      => esc_html__(
603
+				'This merchant is not eligible for Advanced Card Fields checkout type.',
604
+				'event_espresso'
605
+			),
606
+		];
607
+	}
608 608
 }
Please login to merge, or discard this patch.
Spacing   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -72,7 +72,7 @@  discard block
 block discarded – undo
72 72
             $options,
73 73
             [
74 74
                 'name'        => 'PayPalCommerceBillingForm',
75
-                'html_id'     => 'pp-' . $pm_slug . '-billing-form',
75
+                'html_id'     => 'pp-'.$pm_slug.'-billing-form',
76 76
                 'html_class'  => 'pp_commerce_billing_form',
77 77
                 'subsections' => [
78 78
                     'eea_paypal_commerce_token' => new EE_Hidden_Input(
@@ -84,28 +84,28 @@  discard block
 block discarded – undo
84 84
                     ),
85 85
                     'pp_order_nonce'            => new EE_Hidden_Input(
86 86
                         [
87
-                            'html_id'   => 'eea-' . $pm_slug . '-order-nonce',
87
+                            'html_id'   => 'eea-'.$pm_slug.'-order-nonce',
88 88
                             'html_name' => 'pp_order_nonce',
89 89
                             'default'   => '',
90 90
                         ]
91 91
                     ),
92 92
                     'pp_order_id'               => new EE_Hidden_Input(
93 93
                         [
94
-                            'html_id'   => 'eea-' . $pm_slug . '-order-id',
94
+                            'html_id'   => 'eea-'.$pm_slug.'-order-id',
95 95
                             'html_name' => 'pp_order_id',
96 96
                             'default'   => '',
97 97
                         ]
98 98
                     ),
99 99
                     'pp_order_status'           => new EE_Hidden_Input(
100 100
                         [
101
-                            'html_id'   => 'eea-' . $pm_slug . '-order-status',
101
+                            'html_id'   => 'eea-'.$pm_slug.'-order-status',
102 102
                             'html_name' => 'pp_order_status',
103 103
                             'default'   => '',
104 104
                         ]
105 105
                     ),
106 106
                     'pp_order_amount'           => new EE_Hidden_Input(
107 107
                         [
108
-                            'html_id'   => 'eea-' . $pm_slug . '-order-amount',
108
+                            'html_id'   => 'eea-'.$pm_slug.'-order-amount',
109 109
                             'html_name' => 'pp_order_amount',
110 110
                             'default'   => '',
111 111
                         ]
@@ -210,7 +210,7 @@  discard block
 block discarded – undo
210 210
         $request        = LoaderFactory::getShared(Request::class);
211 211
         $request_params = $request->requestParams();
212 212
         // Only the PPC billing form.
213
-        if (! $billing_form instanceof BillingForm) {
213
+        if ( ! $billing_form instanceof BillingForm) {
214 214
             return $billing_form;
215 215
         }
216 216
         // Make sure the billing form subsections have correct names.
@@ -255,8 +255,8 @@  discard block
 block discarded – undo
255 255
                         "$pm_slug-card-number-lbl",
256 256
                         "$pm_slug-card-fields",
257 257
                         "",
258
-                        'for="' . $pm_slug . '-card-number"'
259
-                    ) .
258
+                        'for="'.$pm_slug.'-card-number"'
259
+                    ).
260 260
                     EEH_HTML::p(
261 261
                         "",
262 262
                         "$pm_slug-card-number",
@@ -269,8 +269,8 @@  discard block
 block discarded – undo
269 269
                         "$pm_slug-expiration-date-lbl",
270 270
                         "$pm_slug-card-fields",
271 271
                         "",
272
-                        'for="' . $pm_slug . '-expiration-date"'
273
-                    ) .
272
+                        'for="'.$pm_slug.'-expiration-date"'
273
+                    ).
274 274
                     EEH_HTML::p(
275 275
                         "",
276 276
                         "$pm_slug-expiration-date",
@@ -283,8 +283,8 @@  discard block
 block discarded – undo
283 283
                         "$pm_slug-cvv-lbl",
284 284
                         "$pm_slug-card-fields",
285 285
                         "",
286
-                        'for="' . $pm_slug . '-cvv"'
287
-                    ) .
286
+                        'for="'.$pm_slug.'-cvv"'
287
+                    ).
288 288
                     EEH_HTML::p(
289 289
                         "",
290 290
                         "$pm_slug-cvv",
@@ -294,7 +294,7 @@  discard block
 block discarded – undo
294 294
                 'pp_name_on_card'    => new EE_Text_Input(
295 295
                     [
296 296
                         'html_label_text' => esc_html__('Name On Card', 'event_espresso'),
297
-                        'html_id'         => $pm_slug . '-card-holder-name',
297
+                        'html_id'         => $pm_slug.'-card-holder-name',
298 298
                         'html_name'       => 'card-holder-name',
299 299
                         'html_class'      => '',
300 300
                         'required'        => true,
@@ -333,16 +333,16 @@  discard block
 block discarded – undo
333 333
                     EEH_HTML::div(
334 334
                         EEH_HTML::div(
335 335
                             ' ',
336
-                            'eep-' . $this->paypal_pmt->slug() . '-payments-separator',
336
+                            'eep-'.$this->paypal_pmt->slug().'-payments-separator',
337 337
                             'eep-ppc-separator-line eep-left-floating'
338
-                        ) .
338
+                        ).
339 339
                         EEH_HTML::div(
340 340
                             esc_html__(' or ', 'event_espresso'),
341
-                            'eep-' . $this->paypal_pmt->slug() . '-separator-text',
341
+                            'eep-'.$this->paypal_pmt->slug().'-separator-text',
342 342
                             'eep-ppc-separator-text1 eep-mid-floating'
343
-                        ) . EEH_HTML::div(
343
+                        ).EEH_HTML::div(
344 344
                             ' ',
345
-                            'eep-' . $this->paypal_pmt->slug() . '-payments-separator',
345
+                            'eep-'.$this->paypal_pmt->slug().'-payments-separator',
346 346
                             'eep-ppc-separator-line eep-right-floating'
347 347
                         ),
348 348
                         'eep-ppc-separator-holder',
@@ -366,9 +366,9 @@  discard block
 block discarded – undo
366 366
     {
367 367
         if (
368 368
             ! empty($options_array['html_id'])
369
-            && $options_array['html_id'] === 'spco-payment-method-info-' . $this->paypal_pmt->slug()
369
+            && $options_array['html_id'] === 'spco-payment-method-info-'.$this->paypal_pmt->slug()
370 370
         ) {
371
-            if (! empty($options_array['subsections']) && isset($options_array['subsections']['info'])) {
371
+            if ( ! empty($options_array['subsections']) && isset($options_array['subsections']['info'])) {
372 372
                 unset($options_array['subsections']['info']);
373 373
             }
374 374
         }
@@ -390,7 +390,7 @@  discard block
 block discarded – undo
390 390
                 [
391 391
                     'layout_strategy' => new EE_Template_Layout(
392 392
                         [
393
-                            'layout_template_file' => $this->template_path . 'debugInfo.template.php',
393
+                            'layout_template_file' => $this->template_path.'debugInfo.template.php',
394 394
                             'template_args'        => [],
395 395
                         ]
396 396
                     ),
@@ -411,12 +411,12 @@  discard block
 block discarded – undo
411 411
      */
412 412
     public function addPayPalCheckout(): EE_Form_Section_Proper
413 413
     {
414
-        $template_args['pm_slug']     = $this->paypal_pmt->slug();
414
+        $template_args['pm_slug'] = $this->paypal_pmt->slug();
415 415
         return new EE_Form_Section_Proper(
416 416
             [
417 417
                 'layout_strategy' => new EE_Template_Layout(
418 418
                     [
419
-                        'layout_template_file' => $this->template_path . 'paymentButtons.template.php',
419
+                        'layout_template_file' => $this->template_path.'paymentButtons.template.php',
420 420
                         'template_args'        => $template_args,
421 421
                     ]
422 422
                 ),
@@ -444,7 +444,7 @@  discard block
 block discarded – undo
444 444
             }
445 445
             $client_token = $response['client_token'];
446 446
             $attributes   = " data-partner-attribution-id=\"$bn_code\" data-client-token=\"$client_token\"";
447
-            $tag          = str_replace('></script>', $attributes . '></script>', $tag);
447
+            $tag          = str_replace('></script>', $attributes.'></script>', $tag);
448 448
         }
449 449
         return $tag;
450 450
     }
@@ -475,10 +475,10 @@  discard block
 block discarded – undo
475 475
         }
476 476
 
477 477
         // Setup query args
478
-        $url_params            = [
478
+        $url_params = [
479 479
             'client-id'        => PayPalExtraMetaManager::getPmOption($this->_pm_instance, $client_id_key),
480 480
             'currency'         => CurrencyManager::currencyCode(),
481
-            'components'       => implode(',', ['buttons','hosted-fields']),
481
+            'components'       => implode(',', ['buttons', 'hosted-fields']),
482 482
             'intent'           => 'capture',
483 483
             'merchant-id'      => $merchant_id,
484 484
         ];
@@ -512,7 +512,7 @@  discard block
 block discarded – undo
512 512
 
513 513
         wp_enqueue_script(
514 514
             'eea_paypal_commerce_js',
515
-            EEP_PAYPAL_COMMERCE_URL . 'assets/js/paypal-commerce-payments.js',
515
+            EEP_PAYPAL_COMMERCE_URL.'assets/js/paypal-commerce-payments.js',
516 516
             ['eea_paypal_commerce_js_lib'],
517 517
             EVENT_ESPRESSO_VERSION,
518 518
             true
@@ -520,7 +520,7 @@  discard block
 block discarded – undo
520 520
         // Styles.
521 521
         wp_enqueue_style(
522 522
             'eea_paypal_checkout_form_styles',
523
-            EEP_PAYPAL_COMMERCE_URL . 'assets' . DS . 'css' . DS . 'eea-paypal-checkout.css',
523
+            EEP_PAYPAL_COMMERCE_URL.'assets'.DS.'css'.DS.'eea-paypal-checkout.css',
524 524
             [],
525 525
             EVENT_ESPRESSO_VERSION
526 526
         );
@@ -548,7 +548,7 @@  discard block
 block discarded – undo
548 548
             [['PMD_slug' => ['LIKE', '%paypalcheckout%']]]
549 549
         );
550 550
         foreach ($active_payment_methods as $payment_method) {
551
-            $pm_versions[ $payment_method->slug() ] = [
551
+            $pm_versions[$payment_method->slug()] = [
552 552
                 'pm_slug' => $payment_method->slug(),
553 553
             ];
554 554
         }
Please login to merge, or discard this patch.
PaymentMethods/PayPalCommerce/PayPalCheckout/EEG_PayPalCheckout.gateway.php 1 patch
Indentation   +224 added lines, -224 removed lines patch added patch discarded remove patch
@@ -13,238 +13,238 @@
 block discarded – undo
13 13
  */
14 14
 class EEG_PayPalCheckout extends EE_Onsite_Gateway
15 15
 {
16
-    /**
17
-     * Currencies supported by this gateway.
18
-     *
19
-     * @var array
20
-     */
21
-    protected $_currencies_supported = [
22
-        'AUD',
23
-        'BRL',
24
-        'CAD',
25
-        'CNY',
26
-        'CZK',
27
-        'DKK',
28
-        'EUR',
29
-        'HKD',
30
-        'HUF',
31
-        'ILS',
32
-        'JPY',
33
-        'MYR',
34
-        'MXN',
35
-        'TWD',
36
-        'NZD',
37
-        'NOK',
38
-        'PHP',
39
-        'PLN',
40
-        'GBP',
41
-        'RUB',
42
-        'SGD',
43
-        'SEK',
44
-        'CHF',
45
-        'THB',
46
-        'USD',
47
-    ];
16
+	/**
17
+	 * Currencies supported by this gateway.
18
+	 *
19
+	 * @var array
20
+	 */
21
+	protected $_currencies_supported = [
22
+		'AUD',
23
+		'BRL',
24
+		'CAD',
25
+		'CNY',
26
+		'CZK',
27
+		'DKK',
28
+		'EUR',
29
+		'HKD',
30
+		'HUF',
31
+		'ILS',
32
+		'JPY',
33
+		'MYR',
34
+		'MXN',
35
+		'TWD',
36
+		'NZD',
37
+		'NOK',
38
+		'PHP',
39
+		'PLN',
40
+		'GBP',
41
+		'RUB',
42
+		'SGD',
43
+		'SEK',
44
+		'CHF',
45
+		'THB',
46
+		'USD',
47
+	];
48 48
 
49 49
 
50
-    /**
51
-     * Override the parent.
52
-     *
53
-     * @param EE_Payment|null $payment
54
-     * @param array|null      $billing_info
55
-     * @return EE_Payment
56
-     */
57
-    public function do_direct_payment($payment, $billing_info = null)
58
-    {
59
-        // Normally we shouldn't be getting here because the payment should have been processed
60
-        // along with the PP Order Charge.
61
-        return $payment;
62
-    }
50
+	/**
51
+	 * Override the parent.
52
+	 *
53
+	 * @param EE_Payment|null $payment
54
+	 * @param array|null      $billing_info
55
+	 * @return EE_Payment
56
+	 */
57
+	public function do_direct_payment($payment, $billing_info = null)
58
+	{
59
+		// Normally we shouldn't be getting here because the payment should have been processed
60
+		// along with the PP Order Charge.
61
+		return $payment;
62
+	}
63 63
 
64 64
 
65
-    /**
66
-     * Validate the Order.
67
-     *
68
-     * @param      $order
69
-     * @param null $provided_order_id
70
-     * @return array ['completed' => {boolean}, 'message' => {string}]
71
-     */
72
-    public static function isOrderCompleted($order, $provided_order_id = null): array
73
-    {
74
-        $conclusion = [
75
-            'completed' => false,
76
-            'message'   => esc_html__('Could not validate this Order.', 'event_espresso'),
77
-        ];
78
-        if (! empty($order) && ! empty($provided_order_id) && $order['id'] !== $provided_order_id) {
79
-            $conclusion['message'] = esc_html__('Order ID mismatch.', 'event_espresso');
80
-        }
81
-        if (! $order || ! is_array($order)) {
82
-            $conclusion['message'] = esc_html__('The Order data is incorrectly formatted.', 'event_espresso');
83
-        } elseif (empty($order['status'])) {
84
-            $conclusion['message'] = esc_html__(
85
-                'There was an error with this payment. The status of the Order could not be determined.',
86
-                'event_espresso'
87
-            );
88
-        } elseif ($order['status'] !== 'COMPLETED') {
89
-            $conclusion['message'] = esc_html__(
90
-                'There was an error with this payment. Order was not approved.',
91
-                'event_espresso'
92
-            );
93
-        } elseif (empty($order['purchase_units'][0]['payments']['captures'][0]['status'])) {
94
-            $conclusion['message'] = esc_html__(
95
-                'There was an error with this payment. The status of the Payment could not be determined.',
96
-                'event_espresso'
97
-            );
98
-        } elseif ($order['purchase_units'][0]['payments']['captures'][0]['status'] !== 'COMPLETED') {
99
-            $conclusion['message'] = esc_html__(
100
-                'This payment was declined or failed validation. Please check the billing information you provided.',
101
-                'event_espresso'
102
-            );
103
-        } else {
104
-            // If we didn't fail on the above, the Order should be considered valid.
105
-            $conclusion['completed'] = true;
106
-        }
107
-        return $conclusion;
108
-    }
65
+	/**
66
+	 * Validate the Order.
67
+	 *
68
+	 * @param      $order
69
+	 * @param null $provided_order_id
70
+	 * @return array ['completed' => {boolean}, 'message' => {string}]
71
+	 */
72
+	public static function isOrderCompleted($order, $provided_order_id = null): array
73
+	{
74
+		$conclusion = [
75
+			'completed' => false,
76
+			'message'   => esc_html__('Could not validate this Order.', 'event_espresso'),
77
+		];
78
+		if (! empty($order) && ! empty($provided_order_id) && $order['id'] !== $provided_order_id) {
79
+			$conclusion['message'] = esc_html__('Order ID mismatch.', 'event_espresso');
80
+		}
81
+		if (! $order || ! is_array($order)) {
82
+			$conclusion['message'] = esc_html__('The Order data is incorrectly formatted.', 'event_espresso');
83
+		} elseif (empty($order['status'])) {
84
+			$conclusion['message'] = esc_html__(
85
+				'There was an error with this payment. The status of the Order could not be determined.',
86
+				'event_espresso'
87
+			);
88
+		} elseif ($order['status'] !== 'COMPLETED') {
89
+			$conclusion['message'] = esc_html__(
90
+				'There was an error with this payment. Order was not approved.',
91
+				'event_espresso'
92
+			);
93
+		} elseif (empty($order['purchase_units'][0]['payments']['captures'][0]['status'])) {
94
+			$conclusion['message'] = esc_html__(
95
+				'There was an error with this payment. The status of the Payment could not be determined.',
96
+				'event_espresso'
97
+			);
98
+		} elseif ($order['purchase_units'][0]['payments']['captures'][0]['status'] !== 'COMPLETED') {
99
+			$conclusion['message'] = esc_html__(
100
+				'This payment was declined or failed validation. Please check the billing information you provided.',
101
+				'event_espresso'
102
+			);
103
+		} else {
104
+			// If we didn't fail on the above, the Order should be considered valid.
105
+			$conclusion['completed'] = true;
106
+		}
107
+		return $conclusion;
108
+	}
109 109
 
110 110
 
111
-    /**
112
-     * Create an EE Payment.
113
-     *
114
-     * @param EE_Transaction    $transaction
115
-     * @param EE_Payment_Method $payment_method
116
-     * @return EE_Payment
117
-     * @throws EE_Error
118
-     * @throws ReflectionException
119
-     */
120
-    public static function createPayment(EE_Transaction $transaction, EE_Payment_Method $payment_method): EE_Payment
121
-    {
122
-        // No payment for this transaction was created at this point.
123
-        $payment = EE_Payment::new_instance([
124
-            'PAY_timestamp'     => time(),
125
-            'TXN_ID'            => $transaction->ID(),
126
-            'PMD_ID'            => $payment_method->ID(),
127
-            'PAY_po_number'     => null,
128
-            'PAY_extra_accntng' => null,
129
-            'PAY_details'       => null,
130
-        ]);
131
-        $payment->save();
132
-        return $payment;
133
-    }
111
+	/**
112
+	 * Create an EE Payment.
113
+	 *
114
+	 * @param EE_Transaction    $transaction
115
+	 * @param EE_Payment_Method $payment_method
116
+	 * @return EE_Payment
117
+	 * @throws EE_Error
118
+	 * @throws ReflectionException
119
+	 */
120
+	public static function createPayment(EE_Transaction $transaction, EE_Payment_Method $payment_method): EE_Payment
121
+	{
122
+		// No payment for this transaction was created at this point.
123
+		$payment = EE_Payment::new_instance([
124
+			'PAY_timestamp'     => time(),
125
+			'TXN_ID'            => $transaction->ID(),
126
+			'PMD_ID'            => $payment_method->ID(),
127
+			'PAY_po_number'     => null,
128
+			'PAY_extra_accntng' => null,
129
+			'PAY_details'       => null,
130
+		]);
131
+		$payment->save();
132
+		return $payment;
133
+	}
134 134
 
135 135
 
136
-    /**
137
-     * Set a payment error and log the data.
138
-     *
139
-     * @param EE_Payment   $payment
140
-     * @param string       $status
141
-     * @param array|string $response_data
142
-     * @param string       $update_message
143
-     * @return EE_Payment
144
-     * @throws EE_Error|ReflectionException
145
-     */
146
-    public static function updatePaymentStatus(
147
-        EE_Payment $payment,
148
-        string $status,
149
-        $response_data,
150
-        string $update_message = ''
151
-    ): EE_Payment {
152
-        $paypal_pm = ! empty($payment->payment_method())
153
-            ? EEM_Payment_Method::instance()->get_one_by_slug($payment->payment_method()->name())
154
-            : null;
155
-        // Is this a successful payment ?
156
-        if ($status === EEM_Payment::status_id_approved) {
157
-            $default_message = esc_html__('Successful payment.', 'event_espresso');
158
-            $amount          = $response_data['purchase_units'][0]['payments']['captures'][0]['amount']['value'] ?? 0;
159
-            // Don't set the amount if there is no info on that with this order.
160
-            if (! empty($amount)) {
161
-                $payment->set_amount((float) $amount);
162
-            }
163
-            $payment->set_txn_id_chq_nmbr(
164
-                $order['purchase_units'][0]['payments']['captures'][0]['id'] ?? $response_data['id']
165
-            );
166
-        } else {
167
-            $default_message = sprintf(
168
-                esc_html__(
169
-                    'Your payment could not be processed successfully due to a technical issue.%1$sPlease try again or contact%2$s for assistance.',
170
-                    'event_espresso'
171
-                ),
172
-                '<br/>',
173
-                EE_Registry::instance()->CFG->organization->get_pretty('email')
174
-            );
175
-        }
176
-        $log_message = $update_message ?: $default_message;
177
-        PayPalLogger::errorLog($log_message, $response_data, $paypal_pm, false, $payment->transaction());
178
-        $payment->set_status($status);
179
-        $payment->set_details($log_message);
180
-        $payment->set_gateway_response($log_message);
181
-        $payment->save();
182
-        return $payment;
183
-    }
136
+	/**
137
+	 * Set a payment error and log the data.
138
+	 *
139
+	 * @param EE_Payment   $payment
140
+	 * @param string       $status
141
+	 * @param array|string $response_data
142
+	 * @param string       $update_message
143
+	 * @return EE_Payment
144
+	 * @throws EE_Error|ReflectionException
145
+	 */
146
+	public static function updatePaymentStatus(
147
+		EE_Payment $payment,
148
+		string $status,
149
+		$response_data,
150
+		string $update_message = ''
151
+	): EE_Payment {
152
+		$paypal_pm = ! empty($payment->payment_method())
153
+			? EEM_Payment_Method::instance()->get_one_by_slug($payment->payment_method()->name())
154
+			: null;
155
+		// Is this a successful payment ?
156
+		if ($status === EEM_Payment::status_id_approved) {
157
+			$default_message = esc_html__('Successful payment.', 'event_espresso');
158
+			$amount          = $response_data['purchase_units'][0]['payments']['captures'][0]['amount']['value'] ?? 0;
159
+			// Don't set the amount if there is no info on that with this order.
160
+			if (! empty($amount)) {
161
+				$payment->set_amount((float) $amount);
162
+			}
163
+			$payment->set_txn_id_chq_nmbr(
164
+				$order['purchase_units'][0]['payments']['captures'][0]['id'] ?? $response_data['id']
165
+			);
166
+		} else {
167
+			$default_message = sprintf(
168
+				esc_html__(
169
+					'Your payment could not be processed successfully due to a technical issue.%1$sPlease try again or contact%2$s for assistance.',
170
+					'event_espresso'
171
+				),
172
+				'<br/>',
173
+				EE_Registry::instance()->CFG->organization->get_pretty('email')
174
+			);
175
+		}
176
+		$log_message = $update_message ?: $default_message;
177
+		PayPalLogger::errorLog($log_message, $response_data, $paypal_pm, false, $payment->transaction());
178
+		$payment->set_status($status);
179
+		$payment->set_details($log_message);
180
+		$payment->set_gateway_response($log_message);
181
+		$payment->save();
182
+		return $payment;
183
+	}
184 184
 
185 185
 
186
-    /**
187
-     * Save some transaction details, like billing information.
188
-     *
189
-     * @param EE_Payment     $payment
190
-     * @param EE_Transaction $transaction
191
-     * @param array          $order
192
-     * @param array          $billing_info
193
-     * @return void
194
-     * @throws EE_Error
195
-     * @throws ReflectionException
196
-     */
197
-    public static function saveBillingDetails(
198
-        EE_Payment $payment,
199
-        EE_Transaction $transaction,
200
-        array $order,
201
-        array $billing_info
202
-    ): void {
203
-        $primary_reg    = $transaction->primary_registration();
204
-        $attendee       = $primary_reg instanceof EE_Registration ? $primary_reg->attendee() : null;
205
-        $payment_method = $transaction->payment_method();
206
-        $postmeta_name  = $payment_method->type_obj() instanceof EE_PMT_Base
207
-            ? 'billing_info_' . $payment_method->type_obj()->system_name()
208
-            : '';
209
-        if (empty($order['payment_source']) || ! $attendee instanceof EE_Attendee) {
210
-            // I guess we are done here then. Just save what we have.
211
-            $payment->set_details($order);
212
-            return;
213
-        }
214
-        // Do we have order information from the express checkout (PayPal button) ?
215
-        $billing_info['first_name'] = $billing_info['first_name'] ?? $attendee->fname();
216
-        $billing_info['last_name']  = $billing_info['last_name'] ?? $attendee->lname();
217
-        $billing_info['email']      = $billing_info['email'] ?? $attendee->email();
218
-        if (! empty($billing_info['address'])) {
219
-            $attendee->set_address($billing_info['address']);
220
-        }
221
-        if (! empty($billing_info['address_2'])) {
222
-            $attendee->set_address2($billing_info['address_2']);
223
-        }
224
-        if (! empty($billing_info['city'])) {
225
-            $attendee->set_city($billing_info['city']);
226
-        }
227
-        if (! empty($billing_info['state_id'])) {
228
-            $attendee->set_state((int) $billing_info['state_id']);
229
-        }
230
-        if (! empty($billing_info['country'])) {
231
-            $attendee->set_country($billing_info['country']);
232
-        }
233
-        if (! empty($billing_info['zip'])) {
234
-            $attendee->set_zip($billing_info['zip']);
235
-        }
236
-        // Or card information from ACDC ?
237
-        if (! empty($order['payment_source']['card'])) {
238
-            $payer_card = $order['payment_source']['card'];
239
-            if (! empty($payer_card['name'])) {
240
-                $full_name = explode(' ', $payer_card['name']);
241
-                // Don't need to save each field because others should be populated from the billing form.
242
-                $billing_info['credit_card'] = $payer_card['last_digits'] ?? '';
243
-                $billing_info['first_name']  = $full_name[0] ?? $attendee->fname();
244
-                $billing_info['last_name']   = $full_name[1] ?? $attendee->lname();
245
-            }
246
-        }
247
-        update_post_meta($attendee->ID(), $postmeta_name, $billing_info);
248
-        $attendee->save();
249
-    }
186
+	/**
187
+	 * Save some transaction details, like billing information.
188
+	 *
189
+	 * @param EE_Payment     $payment
190
+	 * @param EE_Transaction $transaction
191
+	 * @param array          $order
192
+	 * @param array          $billing_info
193
+	 * @return void
194
+	 * @throws EE_Error
195
+	 * @throws ReflectionException
196
+	 */
197
+	public static function saveBillingDetails(
198
+		EE_Payment $payment,
199
+		EE_Transaction $transaction,
200
+		array $order,
201
+		array $billing_info
202
+	): void {
203
+		$primary_reg    = $transaction->primary_registration();
204
+		$attendee       = $primary_reg instanceof EE_Registration ? $primary_reg->attendee() : null;
205
+		$payment_method = $transaction->payment_method();
206
+		$postmeta_name  = $payment_method->type_obj() instanceof EE_PMT_Base
207
+			? 'billing_info_' . $payment_method->type_obj()->system_name()
208
+			: '';
209
+		if (empty($order['payment_source']) || ! $attendee instanceof EE_Attendee) {
210
+			// I guess we are done here then. Just save what we have.
211
+			$payment->set_details($order);
212
+			return;
213
+		}
214
+		// Do we have order information from the express checkout (PayPal button) ?
215
+		$billing_info['first_name'] = $billing_info['first_name'] ?? $attendee->fname();
216
+		$billing_info['last_name']  = $billing_info['last_name'] ?? $attendee->lname();
217
+		$billing_info['email']      = $billing_info['email'] ?? $attendee->email();
218
+		if (! empty($billing_info['address'])) {
219
+			$attendee->set_address($billing_info['address']);
220
+		}
221
+		if (! empty($billing_info['address_2'])) {
222
+			$attendee->set_address2($billing_info['address_2']);
223
+		}
224
+		if (! empty($billing_info['city'])) {
225
+			$attendee->set_city($billing_info['city']);
226
+		}
227
+		if (! empty($billing_info['state_id'])) {
228
+			$attendee->set_state((int) $billing_info['state_id']);
229
+		}
230
+		if (! empty($billing_info['country'])) {
231
+			$attendee->set_country($billing_info['country']);
232
+		}
233
+		if (! empty($billing_info['zip'])) {
234
+			$attendee->set_zip($billing_info['zip']);
235
+		}
236
+		// Or card information from ACDC ?
237
+		if (! empty($order['payment_source']['card'])) {
238
+			$payer_card = $order['payment_source']['card'];
239
+			if (! empty($payer_card['name'])) {
240
+				$full_name = explode(' ', $payer_card['name']);
241
+				// Don't need to save each field because others should be populated from the billing form.
242
+				$billing_info['credit_card'] = $payer_card['last_digits'] ?? '';
243
+				$billing_info['first_name']  = $full_name[0] ?? $attendee->fname();
244
+				$billing_info['last_name']   = $full_name[1] ?? $attendee->lname();
245
+			}
246
+		}
247
+		update_post_meta($attendee->ID(), $postmeta_name, $billing_info);
248
+		$attendee->save();
249
+	}
250 250
 }
Please login to merge, or discard this patch.
PaymentMethods/PayPalCommerce/tools/fees/PartnerPaymentFees.php 1 patch
Indentation   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -16,39 +16,39 @@
 block discarded – undo
16 16
  */
17 17
 class PartnerPaymentFees
18 18
 {
19
-    private PaymentProcessorFees $payment_processor_fees;
19
+	private PaymentProcessorFees $payment_processor_fees;
20 20
 
21 21
 
22
-    /**
23
-     * PartnerPaymentFees constructor.
24
-     *
25
-     * @param PaymentProcessorFees $payment_processor_fees
26
-     */
27
-    public function __construct(PaymentProcessorFees $payment_processor_fees)
28
-    {
29
-        $this->payment_processor_fees = $payment_processor_fees;
30
-    }
22
+	/**
23
+	 * PartnerPaymentFees constructor.
24
+	 *
25
+	 * @param PaymentProcessorFees $payment_processor_fees
26
+	 */
27
+	public function __construct(PaymentProcessorFees $payment_processor_fees)
28
+	{
29
+		$this->payment_processor_fees = $payment_processor_fees;
30
+	}
31 31
 
32 32
 
33
-    /**
34
-     * @param EE_Transaction $transaction
35
-     * @return float
36
-     * @throws Exception
37
-     */
38
-    public function getPartnerFee(EE_Transaction $transaction): float
39
-    {
40
-        $fee_rate = $this->payment_processor_fees->forPaymentMethod(PaymentProcessorFees::GATEWAY_PAYPAL);
41
-        if ($fee_rate <= 0) {
42
-            return 0;
43
-        }
44
-        // Don't count tax.
45
-        $total_remaining = $transaction->total() - $transaction->tax_total();
46
-        // If this is a partial payment, try to get a tax-free amount.
47
-        if ($transaction->paid() > 0) {
48
-            $paid_percent    = $transaction->paid() * 100 / $transaction->total();
49
-            $paid_tax        = ($transaction->tax_total() / 100) * $paid_percent;
50
-            $total_remaining = $transaction->remaining() - $paid_tax;
51
-        }
52
-        return CurrencyManager::normalizeValue(($total_remaining / 100) * $fee_rate);
53
-    }
33
+	/**
34
+	 * @param EE_Transaction $transaction
35
+	 * @return float
36
+	 * @throws Exception
37
+	 */
38
+	public function getPartnerFee(EE_Transaction $transaction): float
39
+	{
40
+		$fee_rate = $this->payment_processor_fees->forPaymentMethod(PaymentProcessorFees::GATEWAY_PAYPAL);
41
+		if ($fee_rate <= 0) {
42
+			return 0;
43
+		}
44
+		// Don't count tax.
45
+		$total_remaining = $transaction->total() - $transaction->tax_total();
46
+		// If this is a partial payment, try to get a tax-free amount.
47
+		if ($transaction->paid() > 0) {
48
+			$paid_percent    = $transaction->paid() * 100 / $transaction->total();
49
+			$paid_tax        = ($transaction->tax_total() / 100) * $paid_percent;
50
+			$total_remaining = $transaction->remaining() - $paid_tax;
51
+		}
52
+		return CurrencyManager::normalizeValue(($total_remaining / 100) * $fee_rate);
53
+	}
54 54
 }
Please login to merge, or discard this patch.
PaymentMethods/PayPalCommerce/tools/logging/PayPalLogger.php 2 patches
Indentation   +154 added lines, -154 removed lines patch added patch discarded remove patch
@@ -19,149 +19,149 @@  discard block
 block discarded – undo
19 19
  */
20 20
 class PayPalLogger
21 21
 {
22
-    /**
23
-     * Log an error, return a json message and maybe exit.
24
-     *
25
-     * @param string                 $error_message
26
-     * @param array                  $data
27
-     * @param EE_Payment_Method|null $paypal_pm
28
-     * @param mixed             $object_logged
29
-     * @param bool                   $return_json Should we echo json and exit
30
-     * @param bool                   $popup_log
31
-     * @param bool                   $show_alert  Show an alert on the front end or not
32
-     * @return void
33
-     */
34
-    public static function errorLogAndExit(
35
-        string $error_message = '',
36
-        array $data = [],
37
-        ?EE_Payment_Method $paypal_pm = null,
38
-        bool $return_json = true,
39
-        bool $popup_log = false,
40
-        bool $show_alert = false,
41
-        $object_logged = null
42
-    ): void {
43
-        PayPalLogger::errorLog($error_message, $data, $paypal_pm, $popup_log, $object_logged);
44
-        // Do we echo json and exit or just close the window ?
45
-        if ($return_json) {
46
-            PayPalLogger::exitWithJson($error_message, $show_alert);
47
-        }
48
-        if ($popup_log) {
49
-            PayPalLogger::logInWindow($error_message);
50
-        }
51
-        PayPalLogger::closeWindowAndExit();
52
-    }
22
+	/**
23
+	 * Log an error, return a json message and maybe exit.
24
+	 *
25
+	 * @param string                 $error_message
26
+	 * @param array                  $data
27
+	 * @param EE_Payment_Method|null $paypal_pm
28
+	 * @param mixed             $object_logged
29
+	 * @param bool                   $return_json Should we echo json and exit
30
+	 * @param bool                   $popup_log
31
+	 * @param bool                   $show_alert  Show an alert on the front end or not
32
+	 * @return void
33
+	 */
34
+	public static function errorLogAndExit(
35
+		string $error_message = '',
36
+		array $data = [],
37
+		?EE_Payment_Method $paypal_pm = null,
38
+		bool $return_json = true,
39
+		bool $popup_log = false,
40
+		bool $show_alert = false,
41
+		$object_logged = null
42
+	): void {
43
+		PayPalLogger::errorLog($error_message, $data, $paypal_pm, $popup_log, $object_logged);
44
+		// Do we echo json and exit or just close the window ?
45
+		if ($return_json) {
46
+			PayPalLogger::exitWithJson($error_message, $show_alert);
47
+		}
48
+		if ($popup_log) {
49
+			PayPalLogger::logInWindow($error_message);
50
+		}
51
+		PayPalLogger::closeWindowAndExit();
52
+	}
53 53
 
54 54
 
55
-    /**
56
-     * Log an error, return a json message.
57
-     *
58
-     * @param string                 $error_message
59
-     * @param array                  $data
60
-     * @param EE_Payment_Method|null $paypal_pm
61
-     * @param mixed             $object_logged
62
-     * @param bool                   $popup_log
63
-     * @return bool
64
-     */
65
-    public static function errorLog(
66
-        string $error_message = '',
67
-        array $data = [],
68
-        ?EE_Payment_Method $paypal_pm = null,
69
-        bool $popup_log = false,
70
-        $object_logged = null
71
-    ): bool {
72
-        $default_msg = 'PayPal Commerce error';
73
-        if ($data) {
74
-            $data        = PayPalLogger::cleanDataArray($data);
75
-            $default_msg = $error_message;
76
-        }
77
-        try {
78
-            if (! $paypal_pm instanceof EE_Payment_Method) {
79
-                // Default to the standard PP Commerce PM.
80
-                $paypal_pm = EEM_Payment_Method::instance()->get_one_by_slug(Domain::PM_SLUG);
81
-            }
82
-            $paypal_gateway = $paypal_pm->type_obj()->get_gateway();
83
-            if ($paypal_gateway instanceof EE_Gateway) {
84
-                $paypal_gateway->log([$default_msg => $data], $object_logged);
85
-            }
86
-            if ($popup_log) {
87
-                PayPalLogger::logInWindow(json_encode($data));
88
-            }
89
-        } catch (ReflectionException | EE_Error $error) {
90
-            new ExceptionLogger($error);
91
-            return false;
92
-        }
93
-        // Yes, always return true.
94
-        return true;
95
-    }
55
+	/**
56
+	 * Log an error, return a json message.
57
+	 *
58
+	 * @param string                 $error_message
59
+	 * @param array                  $data
60
+	 * @param EE_Payment_Method|null $paypal_pm
61
+	 * @param mixed             $object_logged
62
+	 * @param bool                   $popup_log
63
+	 * @return bool
64
+	 */
65
+	public static function errorLog(
66
+		string $error_message = '',
67
+		array $data = [],
68
+		?EE_Payment_Method $paypal_pm = null,
69
+		bool $popup_log = false,
70
+		$object_logged = null
71
+	): bool {
72
+		$default_msg = 'PayPal Commerce error';
73
+		if ($data) {
74
+			$data        = PayPalLogger::cleanDataArray($data);
75
+			$default_msg = $error_message;
76
+		}
77
+		try {
78
+			if (! $paypal_pm instanceof EE_Payment_Method) {
79
+				// Default to the standard PP Commerce PM.
80
+				$paypal_pm = EEM_Payment_Method::instance()->get_one_by_slug(Domain::PM_SLUG);
81
+			}
82
+			$paypal_gateway = $paypal_pm->type_obj()->get_gateway();
83
+			if ($paypal_gateway instanceof EE_Gateway) {
84
+				$paypal_gateway->log([$default_msg => $data], $object_logged);
85
+			}
86
+			if ($popup_log) {
87
+				PayPalLogger::logInWindow(json_encode($data));
88
+			}
89
+		} catch (ReflectionException | EE_Error $error) {
90
+			new ExceptionLogger($error);
91
+			return false;
92
+		}
93
+		// Yes, always return true.
94
+		return true;
95
+	}
96 96
 
97 97
 
98
-    /**
99
-     * Clean the array of data from sensitive information.
100
-     *
101
-     * @param array $data
102
-     * @return array
103
-     */
104
-    private static function cleanDataArray(array $data): array
105
-    {
106
-        $sensitive_data = [
107
-            'access_token',
108
-            'refresh_token',
109
-            'nonce',
110
-            'seller_nonce',
111
-            'client_secret',
112
-            Domain::API_KEY_AUTH_CODE,
113
-            'Authorization',
114
-            'merchantIdInPayPal',
115
-        ];
116
-        foreach ($data as $key => $value) {
117
-            if (is_string($value)) {
118
-                // Json encoded ?
119
-                $value = json_decode($value) ?? $value;
120
-            }
121
-            $value = is_array($value) ? PayPalLogger::cleanDataArray($value) : $value;
122
-            // Validate the data type. Some objects won't encode easily, so try getting from them some basic info.
123
-            if (is_object($value)) {
124
-                $obj_vars = get_object_vars($value);
125
-                $value    = ! empty($obj_vars) ? PayPalLogger::cleanDataArray($obj_vars) : get_class($value);
126
-            }
127
-            if (is_string($key) && in_array($key, $sensitive_data)) {
128
-                $data[ $key ] = empty($value) ? '**empty**' : '**hidden**';
129
-            } else {
130
-                $data[ $key ] = $value;
131
-            }
132
-        }
133
-        return $data;
134
-    }
98
+	/**
99
+	 * Clean the array of data from sensitive information.
100
+	 *
101
+	 * @param array $data
102
+	 * @return array
103
+	 */
104
+	private static function cleanDataArray(array $data): array
105
+	{
106
+		$sensitive_data = [
107
+			'access_token',
108
+			'refresh_token',
109
+			'nonce',
110
+			'seller_nonce',
111
+			'client_secret',
112
+			Domain::API_KEY_AUTH_CODE,
113
+			'Authorization',
114
+			'merchantIdInPayPal',
115
+		];
116
+		foreach ($data as $key => $value) {
117
+			if (is_string($value)) {
118
+				// Json encoded ?
119
+				$value = json_decode($value) ?? $value;
120
+			}
121
+			$value = is_array($value) ? PayPalLogger::cleanDataArray($value) : $value;
122
+			// Validate the data type. Some objects won't encode easily, so try getting from them some basic info.
123
+			if (is_object($value)) {
124
+				$obj_vars = get_object_vars($value);
125
+				$value    = ! empty($obj_vars) ? PayPalLogger::cleanDataArray($obj_vars) : get_class($value);
126
+			}
127
+			if (is_string($key) && in_array($key, $sensitive_data)) {
128
+				$data[ $key ] = empty($value) ? '**empty**' : '**hidden**';
129
+			} else {
130
+				$data[ $key ] = $value;
131
+			}
132
+		}
133
+		return $data;
134
+	}
135 135
 
136 136
 
137
-    /**
138
-     * Return error message as json allowing to show an alert on the front-end.
139
-     *
140
-     * @param string $error_message
141
-     * @param bool   $show_alert
142
-     * @return void
143
-     */
144
-    public static function exitWithJson(string $error_message = '', bool $show_alert = false)
145
-    {
146
-        wp_send_json(
147
-            [
148
-                'error'   => $error_message,
149
-                'message' => $error_message,
150
-                'alert'   => $show_alert,
151
-            ]
152
-        );
153
-    }
137
+	/**
138
+	 * Return error message as json allowing to show an alert on the front-end.
139
+	 *
140
+	 * @param string $error_message
141
+	 * @param bool   $show_alert
142
+	 * @return void
143
+	 */
144
+	public static function exitWithJson(string $error_message = '', bool $show_alert = false)
145
+	{
146
+		wp_send_json(
147
+			[
148
+				'error'   => $error_message,
149
+				'message' => $error_message,
150
+				'alert'   => $show_alert,
151
+			]
152
+		);
153
+	}
154 154
 
155 155
 
156
-    /**
157
-     * Close the OAuth window with JS.
158
-     *
159
-     * @param string $message
160
-     * @return void
161
-     */
162
-    public static function logInWindow(string $message): void
163
-    {
164
-        $js_out = '<script type="text/javascript">
156
+	/**
157
+	 * Close the OAuth window with JS.
158
+	 *
159
+	 * @param string $message
160
+	 * @return void
161
+	 */
162
+	public static function logInWindow(string $message): void
163
+	{
164
+		$js_out = '<script type="text/javascript">
165 165
                 if (window.opener) {
166 166
                     try {
167 167
                         window.opener.console.log("' . $message . '");
@@ -170,22 +170,22 @@  discard block
 block discarded – undo
170 170
                     }
171 171
                 }
172 172
             </script>';
173
-        echo $js_out;
174
-        wp_die();
175
-    }
173
+		echo $js_out;
174
+		wp_die();
175
+	}
176 176
 
177 177
 
178
-    /**
179
-     * Close the JS opened auth window.
180
-     *
181
-     * @param string $message
182
-     * @return void
183
-     */
184
-    public static function closeWindowAndExit(string $message = ''): void
185
-    {
186
-        $js_out = '<script type="text/javascript">';
187
-        if (! empty($message)) {
188
-            $js_out .= '
178
+	/**
179
+	 * Close the JS opened auth window.
180
+	 *
181
+	 * @param string $message
182
+	 * @return void
183
+	 */
184
+	public static function closeWindowAndExit(string $message = ''): void
185
+	{
186
+		$js_out = '<script type="text/javascript">';
187
+		if (! empty($message)) {
188
+			$js_out .= '
189 189
                 if (window.opener) {
190 190
                     try {
191 191
                         window.opener.console.log("' . $message . '");
@@ -194,11 +194,11 @@  discard block
 block discarded – undo
194 194
                     }
195 195
                 }
196 196
             ';
197
-        }
198
-        $js_out .= 'window.opener = self;
197
+		}
198
+		$js_out .= 'window.opener = self;
199 199
             window.close();
200 200
             </script>';
201
-        echo $js_out;
202
-        wp_die();
203
-    }
201
+		echo $js_out;
202
+		wp_die();
203
+	}
204 204
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -75,7 +75,7 @@  discard block
 block discarded – undo
75 75
             $default_msg = $error_message;
76 76
         }
77 77
         try {
78
-            if (! $paypal_pm instanceof EE_Payment_Method) {
78
+            if ( ! $paypal_pm instanceof EE_Payment_Method) {
79 79
                 // Default to the standard PP Commerce PM.
80 80
                 $paypal_pm = EEM_Payment_Method::instance()->get_one_by_slug(Domain::PM_SLUG);
81 81
             }
@@ -125,9 +125,9 @@  discard block
 block discarded – undo
125 125
                 $value    = ! empty($obj_vars) ? PayPalLogger::cleanDataArray($obj_vars) : get_class($value);
126 126
             }
127 127
             if (is_string($key) && in_array($key, $sensitive_data)) {
128
-                $data[ $key ] = empty($value) ? '**empty**' : '**hidden**';
128
+                $data[$key] = empty($value) ? '**empty**' : '**hidden**';
129 129
             } else {
130
-                $data[ $key ] = $value;
130
+                $data[$key] = $value;
131 131
             }
132 132
         }
133 133
         return $data;
@@ -164,9 +164,9 @@  discard block
 block discarded – undo
164 164
         $js_out = '<script type="text/javascript">
165 165
                 if (window.opener) {
166 166
                     try {
167
-                        window.opener.console.log("' . $message . '");
167
+                        window.opener.console.log("' . $message.'");
168 168
                     } catch (e) {
169
-                        console.log("' . $message . '");
169
+                        console.log("' . $message.'");
170 170
                     }
171 171
                 }
172 172
             </script>';
@@ -184,13 +184,13 @@  discard block
 block discarded – undo
184 184
     public static function closeWindowAndExit(string $message = ''): void
185 185
     {
186 186
         $js_out = '<script type="text/javascript">';
187
-        if (! empty($message)) {
187
+        if ( ! empty($message)) {
188 188
             $js_out .= '
189 189
                 if (window.opener) {
190 190
                     try {
191
-                        window.opener.console.log("' . $message . '");
191
+                        window.opener.console.log("' . $message.'");
192 192
                     } catch (e) {
193
-                        console.log("' . $message . '");
193
+                        console.log("' . $message.'");
194 194
                     }
195 195
                 }
196 196
             ';
Please login to merge, or discard this patch.