PluginProbe
PayPlug for WooCommerce (Official) / 2.8.2
PayPlug for WooCommerce (Official) v2.8.2
3.0.0 2.18.0 1.0.17 1.0.18 1.0.19 1.0.20 1.0.21 1.0.22 1.0.3 1.0.4 1.0.5 1.0.6 1.0.7 1.0.8 1.1.0 1.10.0 1.10.1 1.2.1 1.2.10 1.2.11 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 All 101 releases
payplug / src / Controller / ApplePay.php

ApplePay.php in PayPlug for WooCommerce (Official) 2.8.2, at src/Controller/ApplePay.php

459 lines 13.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace Payplug\PayplugWoocommerce\Controller;
4
5 use Payplug\Exception\HttpException;
6 use Payplug\PayplugWoocommerce\Gateway\PayplugAddressData;
7 use Payplug\PayplugWoocommerce\PayplugWoocommerceHelper;
8 use Payplug\PayplugWoocommerce\Gateway\PayplugGateway;
9 use Payplug\Resource\Payment as PaymentResource;
10 use function is_cart;
11 use function is_checkout;
12
13 class ApplePay extends PayplugGateway
14 {
15
16 protected $domain_name = "";
17
18 protected $cart=false;
19
20 protected $checkout = false;
21
22 protected $carriers = [];
23 const ENABLE_ON_TEST_MODE = false;
24
25 public function __construct()
26 {
27
28 parent::__construct();
29
30 /** @var \WC_Settings_API override $id */
31 $this->id = 'apple_pay';
32
33 /** @var \WC_Payment_Gateway overwrite for apple pay settings */
34 $this->method_title = __('payplug_apple_pay_title', 'payplug');
35 $this->method_description = "";
36 $this->has_fields = false;
37
38 $this->title = __('payplug_apple_pay_title', 'payplug');
39 $this->description = '<div id="apple-pay-button-wrapper"><apple-pay-button buttonstyle="black" type="pay" locale="'. get_locale() .'"></apple-pay-button></div>';
40 $this->domain_name = $_SERVER['HTTP_HOST'];
41 $this->enabled = "no";
42
43
44 if( $this->checkApplePay() && is_admin()){
45 $this->enabled = "yes";
46
47 }else if( $this->checkApplePay() && $this->checkDeviceComptability() && $this->isSSL() ){
48 if (!is_admin() && is_checkout() && $this->get_button_checkout()) {
49 $this->enabled = 'yes';
50 $this->add_apple_pay_css();
51 add_action('wp_enqueue_scripts', [$this, 'add_apple_pay_js']);
52 }
53
54 if (!is_admin() && is_cart() && $this->get_button_cart()) {
55 $this->enabled = 'yes';
56 $this->add_apple_pay_css();
57 add_action('woocommerce_proceed_to_checkout', [$this, "add_apple_pay_cart_js"], 15);
58
59 }
60 }
61
62 }
63
64 /**
65 * @return bool|void
66 */
67 public function process_admin_options() {
68 $data = $this->get_post_data();
69 if (isset($data['woocommerce_payplug_mode'])) {
70 if ( $this->get_post_data()['woocommerce_payplug_mode'] === '0' ) {
71 $options = get_option( 'woocommerce_payplug_settings', [] );
72 $options['apple_pay'] = 'no';
73 update_option( 'woocommerce_payplug_settings', apply_filters( 'woocommerce_settings_api_sanitized_fields_payplug', $options ) );
74 }
75 }
76 if (isset($data['woocommerce_payplug_apple_pay'])) {
77 if (($data['woocommerce_payplug_apple_pay'] == 1) && (!$this->checkApplePay())) {
78 add_action( 'admin_notices', [$this ,"display_notice"] );
79 }
80 }
81
82 }
83
84 /**
85 *
86 * Check Apple Pay Authorization
87 *
88 * @return bool
89 */
90
91 private function checkApplePay(){
92 $account = PayplugWoocommerceHelper::generic_get_account_data_from_options($this->id);
93 $options = PayplugWoocommerceHelper::get_payplug_options();
94
95 //it's disabled
96 if(isset($options['apple_pay']) && $options['apple_pay'] === "no"){
97 return false;
98 }
99
100 if ( is_cart() && !empty( WC()->cart ) ) {
101 $order_amount = (float) WC()->cart->total;
102 if ($order_amount < self::MIN_AMOUNT || $order_amount > self::MAX_AMOUNT) {
103 return false;
104 }
105 }
106
107 //support legacy applepay
108 if( !isset($options['applepay_checkout']) && !isset($options['applepay_cart']) && isset($options['apple_pay']) && $options['apple_pay'] ==="yes"){
109 $this->set_button_checkout(true);
110 }
111
112 if(isset($options['applepay_checkout']) && $options['applepay_checkout'] === "yes"){
113 $this->set_button_checkout(true);
114 }
115
116 if(isset($options['applepay_cart']) && $options['applepay_cart'] === "yes"){
117 $this->set_button_cart(true);
118 }
119
120 if(isset($options['applepay_carriers']) ){
121 $this->set_carriers($options['applepay_carriers']);
122 }
123
124 //no auth
125 if(!isset($account['payment_methods']['apple_pay']) || !isset($account['payment_methods']['apple_pay']['allowed_domain_names']) ){
126 return false;
127 }
128
129 //$account has permissions to use apple_pay
130 $auth = isset($account['payment_methods']['apple_pay']['enabled']) && $account['payment_methods']['apple_pay']['enabled'];
131 $auth_domains = in_array(strtr(get_site_url(), array("http://" => "", "https://" => "")), $account['payment_methods']['apple_pay']['allowed_domain_names']);
132 $accepted_domain = in_array($this->domain_name, $account['payment_methods']['apple_pay']['allowed_domain_names']);
133
134 $account_auth = $auth && $auth_domains && $accepted_domain;
135
136 //lost auth
137 if(!$account_auth){
138 $options['apple_pay'] = "no";
139 update_option( 'woocommerce_payplug_settings', apply_filters('woocommerce_settings_api_sanitized_fields_payplug', $options) );
140 return false;
141 }
142
143 return true;
144 }
145
146 public function payment_fields()
147 {
148 $description = $this->get_description();
149
150 if (!empty($description)) {
151 echo wpautop(wptexturize($description));
152 }
153 }
154
155 /**
156 * extend the woocommmerce get description to include personalized html
157 *
158 * @return mixed|string|null
159 */
160 public function get_description()
161 {
162 return apply_filters('woocommerce_gateway_description', $this->description, $this->id);
163 }
164 public function add_apple_pay_cart_js(){
165 wp_enqueue_script( 'apple-pay-sdk', 'https://applepay.cdn-apple.com/jsapi/v1/apple-pay-sdk.js', array(), false, true );
166 wp_enqueue_script('payplug-apple-pay-cart', PAYPLUG_GATEWAY_PLUGIN_URL . 'assets/js/payplug-apple-pay-cart.js', ['jquery', 'apple-pay-sdk'], PAYPLUG_GATEWAY_VERSION, true);
167 wp_localize_script( 'payplug-apple-pay-cart', 'apple_pay_params',
168 array(
169 'ajax_url_applepay_get_shippings' => \WC_AJAX::get_endpoint('applepay_get_shippings'),
170 'ajax_url_place_order_with_dummy_data' => \WC_AJAX::get_endpoint('place_order_with_dummy_data'),
171 'ajax_url_update_applepay_order' => \WC_AJAX::get_endpoint('update_applepay_order'),
172 'ajax_url_update_applepay_payment' => \WC_AJAX::get_endpoint('update_applepay_payment'),
173 'ajax_url_applepay_get_order_totals' => \WC_AJAX::get_endpoint('applepay_get_order_totals'),
174 'ajax_url_applepay_cancel_order' => \WC_AJAX::get_endpoint('applepay_cancel_order'),
175
176 'countryCode' => WC()->customer->get_billing_country(),
177 'currencyCode' => get_woocommerce_currency(),
178 'apple_pay_domain' => $_SERVER['HTTP_HOST']
179 )
180 );
181
182 if($this->checkButtonVisibility()){
183 echo $this->get_description();
184 }
185 }
186
187 /**
188 * Check if the shipping address is a carrier
189 *
190 * @return bool
191 */
192 private function checkButtonVisibility(){
193 $apple_carriers = $this->get_carriers();
194 $allowed = false;
195 $post = $this->get_post_data();
196 $chosen_method = isset($post["shipping_method"][0]) ? $post["shipping_method"][0] : null;
197 if(!$chosen_method){
198 $chosen_method = WC()->session->chosen_shipping_methods[0];
199 }
200
201 foreach ( WC()->shipping()->get_packages() as $i => $package ) {
202 $available_rates = !empty($package['rates']) ? $package['rates'] : [];
203 if(!empty($available_rates)){
204 foreach($available_rates as $method){
205 if(in_array($method->get_method_id(), $apple_carriers) ){
206 if($chosen_method === $method->get_method_id() . ":" . $method->get_instance_id()){
207 $allowed = true;
208 }
209 }
210 }
211 }
212 }
213
214 return $allowed;
215 }
216
217
218 /**
219 * Display unauthorized error
220 *
221 * @return void
222 */
223
224 public static function display_notice() {
225 ?>
226 <div class="notice notice-error is-dismissible">
227 <p><?php echo __( 'payplug_apple_pay_unauthorized_error', 'payplug' ); ?></p>
228 </div>
229 <?php
230 }
231
232 /**
233 * Check User-Agent to make sure it is on Mac OS
234 *
235 * @return bool
236 */
237 public function checkDeviceComptability(){
238 $user_agent = isset($_SERVER["HTTP_USER_AGENT"]) ? $_SERVER['HTTP_USER_AGENT'] : '';
239
240 // Check if the Browser is Safari
241 if (stripos( $user_agent, 'Chrome') !== false) {
242 return false;
243
244 } elseif (stripos( $user_agent, 'Safari') !== false) {
245 // Check if the OS is Mac
246 if(!preg_match('/macintosh|mac os x/i', $user_agent)) {
247 return false;
248 }
249 }
250 return true;
251 }
252
253 /**
254 * Check if SSL
255 *
256 */
257 public function isSSL()
258 {
259 if( !empty( $_SERVER['HTTPS'] ) ) {
260 if ( 'on' == strtolower($_SERVER['HTTPS']) )
261 return true;
262 } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
263 return true;
264 }
265
266 if( !empty( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https' )
267 return true;
268
269 return false;
270 }
271
272 /**
273 * Add CSS
274 *
275 */
276 public function add_apple_pay_css() {
277 wp_enqueue_style('payplug-apple-pay', PAYPLUG_GATEWAY_PLUGIN_URL . 'assets/css/payplug-apple-pay.css', [], PAYPLUG_GATEWAY_VERSION);
278 }
279
280 /**
281 * Add JS
282 *
283 */
284 public function add_apple_pay_js() {
285 wp_enqueue_script( 'apple-pay-sdk', 'https://applepay.cdn-apple.com/jsapi/v1/apple-pay-sdk.js', array(), false, true );
286 wp_enqueue_script('payplug-apple-pay', PAYPLUG_GATEWAY_PLUGIN_URL . 'assets/js/payplug-apple-pay.js',
287 [
288 'jquery',
289 'apple-pay-sdk'
290 ], PAYPLUG_GATEWAY_VERSION, true);
291 wp_localize_script( 'payplug-apple-pay', 'apple_pay_params',
292 array(
293 'ajax_url_payplug_create_order' => \WC_AJAX::get_endpoint('payplug_create_order'),
294 'ajax_url_applepay_update_payment' => \WC_AJAX::get_endpoint('applepay_update_payment'),
295 'ajax_url_applepay_get_order_totals' => \WC_AJAX::get_endpoint('applepay_get_order_totals'),
296 'countryCode' => WC()->customer->get_billing_country(),
297 'currencyCode' => get_woocommerce_currency(),
298 'total' => WC()->cart->total,
299 'apple_pay_domain' => $this->domain_name
300 )
301 );
302 }
303
304 /**
305 * Get payment icons.
306 *
307 * @return string
308 */
309 public function get_icon()
310 {
311 $available_img = 'apple-pay-checkout.svg';
312 $icons = apply_filters('payplug_payment_icons', [
313 'payplug' => sprintf('<img src="%s" alt="Apple Pay" class="payplug-payment-icon" />', esc_url(PAYPLUG_GATEWAY_PLUGIN_URL . '/assets/images/checkout/' . $available_img)),
314 ]);
315 $icons_str = '';
316 foreach ($icons as $icon) {
317 $icons_str .= $icon;
318 }
319 return $icons_str;
320 }
321
322
323 /**
324 * @param \WC_Order $order
325 * @param int $amount
326 * @param int $customer_id
327 *
328 * @return array
329 * @throws \Exception
330 */
331 public function process_standard_payment($order, $amount, $customer_id, $workflow = 'checkout')
332 {
333 $order_id = PayplugWoocommerceHelper::is_pre_30() ? $order->id : $order->get_id();
334 try {
335 $address_data = PayplugAddressData::from_order($order);
336
337 $return_url = esc_url_raw($order->get_checkout_order_received_url());
338
339 if (!(substr( $return_url, 0, 4 ) === "http")) {
340 $return_url = get_site_url().$return_url;
341 }
342
343 // delivery_type must be removed in Apple Pay
344 $billing = $address_data->get_billing();
345 unset($billing['delivery_type']);
346 $shipping = $address_data->get_shipping();
347 unset($shipping['delivery_type']);
348
349 $payment_data = [
350 'amount' => $amount,
351 'currency' => get_woocommerce_currency(),
352 'payment_method' => $this->id,
353 'payment_context' => array(
354 'apple_pay' => array(
355 'domain_name' => $this->domain_name,
356 'application_data' => base64_encode(json_encode(array(
357 'apple_pay_domain' => $this->domain_name,
358 )))
359 )
360 ),
361 'billing' => $billing,
362 'shipping' => $shipping,
363 'hosted_payment' => [
364 'return_url' => $return_url,
365 'cancel_url' => esc_url_raw($order->get_cancel_order_url_raw()),
366 ],
367 'notification_url' => esc_url_raw(WC()->api_request_url('PayplugGateway')),
368 'metadata' => [
369 'order_id' => $order_id,
370 'customer_id' => ((int) $customer_id > 0) ? $customer_id : 'guest',
371 'domain' => $this->domain_name,
372 'applepay_workflow' => $workflow
373 ]
374 ];
375
376 /**
377 * Filter the payment data before it's used
378 *
379 * @param array $payment_data
380 * @param int $order_id
381 * @param array $customer_details
382 * @param PayplugAddressData $address_data
383 */
384 $payment_data = apply_filters('payplug_gateway_payment_data', $payment_data, $order_id, [], $address_data);
385 $payment = $this->api->payment_create($payment_data);
386
387 // Save transaction id for the order
388 PayplugWoocommerceHelper::is_pre_30()
389 ? update_post_meta($order_id, '_transaction_id', $payment->id)
390 : $order->set_transaction_id($payment->id);
391
392 if (is_callable([$order, 'save'])) {
393 $order->save();
394 }
395
396 /**
397 * Fires once a payment has been created.
398 *
399 * @param int $order_id Order ID
400 * @param PaymentResource $payment Payment resource
401 */
402 \do_action('payplug_gateway_payment_created', $order_id, $payment);
403
404 $metadata = PayplugWoocommerceHelper::extract_transaction_metadata($payment);
405 PayplugWoocommerceHelper::save_transaction_metadata($order, $metadata);
406
407 PayplugGateway::log(sprintf('Payment creation complete for order #%s', $order_id));
408
409 return [
410 'result' => 'success',
411 'merchant_session' => $payment->payment_method["merchant_session"],
412 'payment_id' => $payment->id,
413 'cancel_url' => esc_url_raw($order->get_cancel_order_url_raw()),
414 'return_url' => $return_url,
415 ];
416
417 } catch (HttpException $e) {
418 PayplugGateway::log(sprintf('Error while processing order #%s : %s', $order_id, wc_print_r($e->getErrorObject(), true)), 'error');
419 if($workflow === "cart"){
420 wp_send_json_error(["code" => $e->getCode(), "msg" => __('Payment processing failed. Please retry.', 'payplug'), "order_id" => $order_id ]);
421 }
422 throw new \Exception(__('Payment processing failed. Please retry.', 'payplug'));
423 } catch (\Exception $e) {
424 PayplugGateway::log(sprintf('Error while processing order #%s : %s', $order_id, $e->getMessage()), 'error');
425 if($workflow === "cart"){
426 wp_send_json_error(["code" => $e->getCode(), "msg" => __('Payment processing failed. Please retry.', 'payplug'), "order_id" => $order_id ]);
427 }
428 throw new \Exception(__('Payment processing failed. Please retry.', 'payplug'));
429 }
430
431 }
432
433 private function set_button_checkout($status){
434 $this->checkout = $status;
435 }
436
437 private function set_button_cart($status){
438 $this->cart = $status;
439 }
440
441 private function get_button_checkout(){
442 return $this->checkout;
443 }
444
445 private function get_button_cart(){
446 return $this->cart;
447 }
448
449 private function get_carriers(){
450 return $this->carriers;
451 }
452
453 private function set_carriers($carriers){
454 $this->carriers = $carriers;
455 }
456
457
458 }
459