Completed
Push — add/changelog-910 ( c277c8...7fd9c0 )
by Jeremy
19:06 queued 09:10
created

setup_paypal_checkout_button()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 3
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
1
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2
/**
3
 * Simple Payments lets users embed a PayPal button fully integrated with wpcom to sell products on the site.
4
 * This is not a proper module yet, because not all the pieces are in place. Until everything is shipped, it can be turned
5
 * into module that can be enabled/disabled.
6
 *
7
 * @package Jetpack
8
 */
9
10
/**
11
 * Jetpack_Simple_Payments
12
 */
13
class Jetpack_Simple_Payments {
14
	// These have to be under 20 chars because that is CPT limit.
15
	static $post_type_order = 'jp_pay_order';
16
	static $post_type_product = 'jp_pay_product';
17
18
	static $shortcode = 'simple-payment';
19
20
	static $css_classname_prefix = 'jetpack-simple-payments';
21
22
	static $required_plan;
23
24
	// Increase this number each time there's a change in CSS or JS to bust cache.
25
	static $version = '0.25';
26
27
	// Classic singleton pattern:
28
	private static $instance;
29
	private function __construct() {}
30 View Code Duplication
	static function getInstance() {
31
		if ( ! self::$instance ) {
32
			self::$instance = new self();
33
			self::$instance->register_init_hooks();
34
			self::$required_plan = ( defined( 'IS_WPCOM' ) && IS_WPCOM ) ? 'value_bundle' : 'jetpack_premium';
35
		}
36
		return self::$instance;
37
	}
38
39
	private function register_scripts_and_styles() {
40
		/**
41
		 * Paypal heavily discourages putting that script in your own server:
42
		 * @see https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/add-paypal-button/
43
		 */
44
		wp_register_script( 'paypal-checkout-js', 'https://www.paypalobjects.com/api/checkout.js', array(), null, true );
45
		wp_register_script( 'paypal-express-checkout', plugins_url( '/paypal-express-checkout.js', __FILE__ ),
46
			array( 'jquery', 'paypal-checkout-js' ), self::$version );
47
		wp_register_style( 'jetpack-simple-payments', plugins_url( '/simple-payments.css', __FILE__ ), array( 'dashicons' ) );
48
	}
49
50
	private function register_init_hooks() {
51
		add_action( 'init', array( $this, 'init_hook_action' ) );
52
		add_action( 'rest_api_init', array( $this, 'register_meta_fields_in_rest_api' ) );
53
	}
54
55
	private function register_shortcode() {
56
		add_shortcode( self::$shortcode, array( $this, 'parse_shortcode' ) );
57
	}
58
59
	public function init_hook_action() {
60
		add_filter( 'rest_api_allowed_post_types', array( $this, 'allow_rest_api_types' ) );
61
		add_filter( 'jetpack_sync_post_meta_whitelist', array( $this, 'allow_sync_post_meta' ) );
62
		if ( ! is_admin() ) {
63
			$this->register_scripts_and_styles();
64
		}
65
		$this->register_shortcode();
66
		$this->setup_cpts();
67
68
		add_filter( 'the_content', array( $this, 'remove_auto_paragraph_from_product_description' ), 0 );
69
	}
70
71
	/**
72
	 * Enqueue the static assets needed in the frontend.
73
	 */
74
	public function enqueue_frontend_assets() {
75
		if ( ! wp_style_is( 'jetpack-simple-payments', 'enqueued' ) ) {
76
			wp_enqueue_style( 'jetpack-simple-payments' );
77
		}
78
79
		if ( ! wp_script_is( 'paypal-express-checkout', 'enqueued' ) ) {
80
			wp_enqueue_script( 'paypal-express-checkout' );
81
		}
82
	}
83
84
	/**
85
	 * Add an inline script for setting up the PayPal checkout button.
86
	 *
87
	 * @param int     $id Product ID.
88
	 * @param int     $dom_id ID of the DOM element with the purchase message.
89
	 * @param boolean $is_multiple Whether multiple items of the same product can be purchased.
90
	 */
91
	public function setup_paypal_checkout_button( $id, $dom_id, $is_multiple ) {
92
		wp_add_inline_script(
93
			'paypal-express-checkout',
94
			sprintf(
95
				"try{PaypalExpressCheckout.renderButton( '%d', '%d', '%s', '%d' );}catch(e){}",
96
				esc_js( $this->get_blog_id() ),
97
				esc_js( $id ),
98
				esc_js( $dom_id ),
99
				esc_js( $is_multiple )
100
			)
101
		);
102
	}
103
104
	function remove_auto_paragraph_from_product_description( $content ) {
105
		if ( get_post_type() === self::$post_type_product ) {
106
			remove_filter( 'the_content', 'wpautop' );
107
		}
108
109
		return $content;
110
	}
111
112
	function get_blog_id() {
113
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
114
			return get_current_blog_id();
115
		}
116
117
		return Jetpack_Options::get_option( 'id' );
118
	}
119
120
	/**
121
	 * Used to check whether Simple Payments are enabled for given site.
122
	 *
123
	 * @return bool True if Simple Payments are enabled, false otherwise.
124
	 */
125
	function is_enabled_jetpack_simple_payments() {
126
		/**
127
		 * Can be used by plugin authors to disable the conflicting output of Simple Payments.
128
		 *
129
		 * @since 6.3.0
130
		 *
131
		 * @param bool True if Simple Payments should be disabled, false otherwise.
132
		 */
133
		if ( apply_filters( 'jetpack_disable_simple_payments', false ) ) {
134
			return false;
135
		}
136
137
		// For WPCOM sites
138 View Code Duplication
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM && function_exists( 'has_any_blog_stickers' ) ) {
139
			$site_id = $this->get_blog_id();
140
			return has_any_blog_stickers( array( 'premium-plan', 'business-plan', 'ecommerce-plan' ), $site_id );
141
		}
142
143
		// For all Jetpack sites
144
		return Jetpack::is_active() && Jetpack_Plan::supports( 'simple-payments');
145
	}
146
147
	function parse_shortcode( $attrs, $content = false ) {
148
		if ( empty( $attrs['id'] ) ) {
149
			return;
150
		}
151
		$product = get_post( $attrs['id'] );
152
		if ( ! $product || is_wp_error( $product ) ) {
153
			return;
154
		}
155
		if ( $product->post_type !== self::$post_type_product || 'publish' !== $product->post_status ) {
156
			return;
157
		}
158
159
		// We allow for overriding the presentation labels
160
		$data = shortcode_atts( array(
161
			'blog_id'     => $this->get_blog_id(),
162
			'dom_id'      => uniqid( self::$css_classname_prefix . '-' . $product->ID . '_', true ),
163
			'class'       => self::$css_classname_prefix . '-' . $product->ID,
164
			'title'       => get_the_title( $product ),
165
			'description' => $product->post_content,
166
			'cta'         => get_post_meta( $product->ID, 'spay_cta', true ),
167
			'multiple'    => get_post_meta( $product->ID, 'spay_multiple', true ) || '0'
168
		), $attrs );
169
170
		$data['price'] = $this->format_price(
171
			get_post_meta( $product->ID, 'spay_price', true ),
172
			get_post_meta( $product->ID, 'spay_currency', true )
173
		);
174
175
		$data['id'] = $attrs['id'];
176
177
		if ( ! $this->is_enabled_jetpack_simple_payments() ) {
178
			if ( jetpack_is_frontend() ) {
179
				return $this->output_admin_warning( $data );
180
			}
181
			return;
182
		}
183
184
		$this->enqueue_frontend_assets();
185
		$this->setup_paypal_checkout_button( $attrs['id'], $data['dom_id'], $data['multiple'] );
186
187
		return $this->output_shortcode( $data );
188
	}
189
190
	function output_admin_warning( $data ) {
191
		if ( ! current_user_can( 'manage_options' ) ) {
192
			return;
193
		}
194
195
		jetpack_require_lib( 'components' );
196
		return Jetpack_Components::render_upgrade_nudge( array(
197
			'plan' => self::$required_plan
198
		) );
199
	}
200
201
	/**
202
	 * Get the HTML output to use as PayPal purchase box.
203
	 *
204
	 * @param string  $dom_id ID of the DOM element with the purchase message.
205
	 * @param boolean $is_multiple Whether multiple items of the same product can be purchased.
206
	 *
207
	 * @return string
208
	 */
209
	public function output_purchase_box( $dom_id, $is_multiple ) {
210
		$items = '';
211
		$css_prefix = self::$css_classname_prefix;
212
213
		if ( $is_multiple ) {
214
			$items = sprintf( '
215
				<div class="%1$s">
216
					<input class="%2$s" type="number" value="1" min="1" id="%3$s" />
217
				</div>
218
				',
219
				esc_attr( "${css_prefix}-items" ),
220
				esc_attr( "${css_prefix}-items-number" ),
221
				esc_attr( "{$dom_id}_number" )
222
			);
223
		}
224
225
		return sprintf(
226
			'<div class="%1$s" id="%2$s"></div><div class="%3$s">%4$s<div class="%5$s" id="%6$s"></div></div>',
227
			esc_attr( "${css_prefix}-purchase-message" ),
228
			esc_attr( "{$dom_id}-message-container" ),
229
			esc_attr( "${css_prefix}-purchase-box" ),
230
			$items,
231
			esc_attr( "${css_prefix}-button" ),
232
			esc_attr( "{$dom_id}_button" )
233
		);
234
	}
235
236
	/**
237
	 * Get the HTML output to replace the `simple-payments` shortcode.
238
	 *
239
	 * @param array $data Product data.
240
	 * @return string
241
	 */
242
	public function output_shortcode( $data ) {
243
		$css_prefix = self::$css_classname_prefix;
244
245
		$image = "";
246
		if( has_post_thumbnail( $data['id'] ) ) {
247
			$image = sprintf( '<div class="%1$s"><div class="%2$s">%3$s</div></div>',
248
				esc_attr( "${css_prefix}-product-image" ),
249
				esc_attr( "${css_prefix}-image" ),
250
				get_the_post_thumbnail( $data['id'], 'full' )
251
			);
252
		}
253
254
		return sprintf( '
255
<div class="%1$s">
256
	<div class="%2$s">
257
		%3$s
258
		<div class="%4$s">
259
			<div class="%5$s"><p>%6$s</p></div>
260
			<div class="%7$s"><p>%8$s</p></div>
261
			<div class="%9$s"><p>%10$s</p></div>
262
			%11$s
263
		</div>
264
	</div>
265
</div>
266
',
267
			esc_attr( "{$data['class']} ${css_prefix}-wrapper" ),
268
			esc_attr( "${css_prefix}-product" ),
269
			$image,
270
			esc_attr( "${css_prefix}-details" ),
271
			esc_attr( "${css_prefix}-title" ),
272
			esc_html( $data['title'] ),
273
			esc_attr( "${css_prefix}-description" ),
274
			wp_kses( $data['description'], wp_kses_allowed_html( 'post' ) ),
275
			esc_attr( "${css_prefix}-price" ),
276
			esc_html( $data['price'] ),
277
			$this->output_purchase_box( $data['dom_id'], $data['multiple'] )
278
		);
279
	}
280
281
	/**
282
	 * Format a price with currency
283
	 *
284
	 * Uses currency-aware formatting to output a formatted price with a simple fallback.
285
	 *
286
	 * Largely inspired by WordPress.com's Store_Price::display_currency
287
	 *
288
	 * @param  string $price    Price.
289
	 * @param  string $currency Currency.
290
	 * @return string           Formatted price.
291
	 */
292
	private function format_price( $price, $currency ) {
293
		jetpack_require_lib( 'class-jetpack-currencies' );
294
		return Jetpack_Currencies::format_price( $price, $currency );
295
	}
296
297
	/**
298
	 * Allows custom post types to be used by REST API.
299
	 * @param $post_types
300
	 * @see hook 'rest_api_allowed_post_types'
301
	 * @return array
302
	 */
303
	function allow_rest_api_types( $post_types ) {
304
		$post_types[] = self::$post_type_order;
305
		$post_types[] = self::$post_type_product;
306
		return $post_types;
307
	}
308
309
	function allow_sync_post_meta( $post_meta ) {
310
		return array_merge( $post_meta, array(
311
			'spay_paypal_id',
312
			'spay_status',
313
			'spay_product_id',
314
			'spay_quantity',
315
			'spay_price',
316
			'spay_customer_email',
317
			'spay_currency',
318
			'spay_cta',
319
			'spay_email',
320
			'spay_multiple',
321
			'spay_formatted_price',
322
		) );
323
	}
324
325
	/**
326
	 * Enable Simple payments custom meta values for access through the REST API.
327
	 * Field’s value will be exposed on a .meta key in the endpoint response,
328
	 * and WordPress will handle setting up the callbacks for reading and writing
329
	 * to that meta key.
330
	 *
331
	 * @link https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/
332
	 */
333
	public function register_meta_fields_in_rest_api() {
334
		register_meta( 'post', 'spay_price', array(
335
			'description'       => esc_html__( 'Simple payments; price.', 'jetpack' ),
336
			'object_subtype'    => self::$post_type_product,
337
			'sanitize_callback' => array( $this, 'sanitize_price' ),
338
			'show_in_rest'      => true,
339
			'single'            => true,
340
			'type'              => 'number',
341
		) );
342
343
		register_meta( 'post', 'spay_currency', array(
344
			'description'       => esc_html__( 'Simple payments; currency code.', 'jetpack' ),
345
			'object_subtype'    => self::$post_type_product,
346
			'sanitize_callback' => array( $this, 'sanitize_currency' ),
347
			'show_in_rest'      => true,
348
			'single'            => true,
349
			'type'              => 'string',
350
		) );
351
352
		register_meta( 'post', 'spay_cta', array(
353
			'description'       => esc_html__( 'Simple payments; text with "Buy" or other CTA', 'jetpack' ),
354
			'object_subtype'    => self::$post_type_product,
355
			'sanitize_callback' => 'sanitize_text_field',
356
			'show_in_rest'      => true,
357
			'single'            => true,
358
			'type'              => 'string',
359
		) );
360
361
		register_meta( 'post', 'spay_multiple', array(
362
			'description'       => esc_html__( 'Simple payments; allow multiple items', 'jetpack' ),
363
			'object_subtype'    => self::$post_type_product,
364
			'sanitize_callback' => 'rest_sanitize_boolean',
365
			'show_in_rest'      => true,
366
			'single'            => true,
367
			'type'              => 'boolean',
368
		) );
369
370
		register_meta( 'post', 'spay_email', array(
371
			'description'       => esc_html__( 'Simple payments button; paypal email.', 'jetpack' ),
372
			'sanitize_callback' => 'sanitize_email',
373
			'show_in_rest'      => true,
374
			'single'            => true,
375
			'type'              => 'string',
376
		) );
377
378
		register_meta( 'post', 'spay_status', array(
379
			'description'       => esc_html__( 'Simple payments; status.', 'jetpack' ),
380
			'object_subtype'    => self::$post_type_product,
381
			'sanitize_callback' => 'sanitize_text_field',
382
			'show_in_rest'      => true,
383
			'single'            => true,
384
			'type'              => 'string',
385
		) );
386
	}
387
388
	/**
389
	 * Sanitize three-character ISO-4217 Simple payments currency
390
	 *
391
	 * List has to be in sync with list at the block's client side and widget's backend side:
392
	 * @link https://github.com/Automattic/jetpack/blob/31efa189ad223c0eb7ad085ac0650a23facf9ef5/extensions/blocks/simple-payments/constants.js#L9-L39
393
	 * @link https://github.com/Automattic/jetpack/blob/31efa189ad223c0eb7ad085ac0650a23facf9ef5/modules/widgets/simple-payments.php#L19-L44
394
	 *
395
	 * Currencies should be supported by PayPal:
396
	 * @link https://developer.paypal.com/docs/api/reference/currency-codes/
397
	 *
398
	 * Indian Rupee (INR) not supported because at the time of the creation of this file
399
	 * because it's limited to in-country PayPal India accounts only.
400
	 * Discussion: https://github.com/Automattic/wp-calypso/pull/28236
401
	 */
402
	public static function sanitize_currency( $currency ) {
403
		$valid_currencies = array(
404
			'USD',
405
			'EUR',
406
			'AUD',
407
			'BRL',
408
			'CAD',
409
			'CZK',
410
			'DKK',
411
			'HKD',
412
			'HUF',
413
			'ILS',
414
			'JPY',
415
			'MYR',
416
			'MXN',
417
			'TWD',
418
			'NZD',
419
			'NOK',
420
			'PHP',
421
			'PLN',
422
			'GBP',
423
			'RUB',
424
			'SGD',
425
			'SEK',
426
			'CHF',
427
			'THB',
428
		);
429
430
		return in_array( $currency, $valid_currencies ) ? $currency : false;
431
	}
432
433
	/**
434
	 * Sanitize price:
435
	 *
436
	 * Positive integers and floats
437
	 * Supports two decimal places.
438
	 * Maximum length: 10.
439
	 *
440
	 * See `price` from PayPal docs:
441
	 * @link https://developer.paypal.com/docs/api/orders/v1/#definition-item
442
	 *
443
	 * @param      $value
444
	 * @return null|string
445
	 */
446
	public static function sanitize_price( $price ) {
447
		return preg_match( '/^[0-9]{0,10}(\.[0-9]{0,2})?$/', $price ) ? $price : false;
448
	}
449
450
	/**
451
	 * Sets up the custom post types for the module.
452
	 */
453
	function setup_cpts() {
454
455
		/*
456
		 * ORDER data structure. holds:
457
		 * title = customer_name | 4xproduct_name
458
		 * excerpt = customer_name + customer contact info + customer notes from paypal form
459
		 * metadata:
460
		 * spay_paypal_id - paypal id of transaction
461
		 * spay_status
462
		 * spay_product_id - post_id of bought product
463
		 * spay_quantity - quantity of product
464
		 * spay_price - item price at the time of purchase
465
		 * spay_customer_email - customer email
466
		 * ... (WIP)
467
		 */
468
		$order_capabilities = array(
469
			'edit_post'             => 'edit_posts',
470
			'read_post'             => 'read_private_posts',
471
			'delete_post'           => 'delete_posts',
472
			'edit_posts'            => 'edit_posts',
473
			'edit_others_posts'     => 'edit_others_posts',
474
			'publish_posts'         => 'publish_posts',
475
			'read_private_posts'    => 'read_private_posts',
476
		);
477
		$order_args = array(
478
			'label'                 => esc_html_x( 'Order', 'noun: a quantity of goods or items purchased or sold', 'jetpack' ),
479
			'description'           => esc_html__( 'Simple Payments orders', 'jetpack' ),
480
			'supports'              => array( 'custom-fields', 'excerpt' ),
481
			'hierarchical'          => false,
482
			'public'                => false,
483
			'show_ui'               => false,
484
			'show_in_menu'          => false,
485
			'show_in_admin_bar'     => false,
486
			'show_in_nav_menus'     => false,
487
			'can_export'            => true,
488
			'has_archive'           => false,
489
			'exclude_from_search'   => true,
490
			'publicly_queryable'    => false,
491
			'rewrite'               => false,
492
			'capabilities'          => $order_capabilities,
493
			'show_in_rest'          => true,
494
		);
495
		register_post_type( self::$post_type_order, $order_args );
496
497
		/*
498
		 * PRODUCT data structure. Holds:
499
		 * title - title
500
		 * content - description
501
		 * thumbnail - image
502
		 * metadata:
503
		 * spay_price - price
504
		 * spay_formatted_price
505
		 * spay_currency - currency code
506
		 * spay_cta - text with "Buy" or other CTA
507
		 * spay_email - paypal email
508
		 * spay_multiple - allow for multiple items
509
		 * spay_status - status. { enabled | disabled }
510
		 */
511
		$product_capabilities = array(
512
			'edit_post'             => 'edit_posts',
513
			'read_post'             => 'read_private_posts',
514
			'delete_post'           => 'delete_posts',
515
			'edit_posts'            => 'publish_posts',
516
			'edit_others_posts'     => 'edit_others_posts',
517
			'publish_posts'         => 'publish_posts',
518
			'read_private_posts'    => 'read_private_posts',
519
		);
520
		$product_args = array(
521
			'label'                 => esc_html__( 'Product', 'jetpack' ),
522
			'description'           => esc_html__( 'Simple Payments products', 'jetpack' ),
523
			'supports'              => array( 'title', 'editor','thumbnail', 'custom-fields', 'author' ),
524
			'hierarchical'          => false,
525
			'public'                => false,
526
			'show_ui'               => false,
527
			'show_in_menu'          => false,
528
			'show_in_admin_bar'     => false,
529
			'show_in_nav_menus'     => false,
530
			'can_export'            => true,
531
			'has_archive'           => false,
532
			'exclude_from_search'   => true,
533
			'publicly_queryable'    => false,
534
			'rewrite'               => false,
535
			'capabilities'          => $product_capabilities,
536
			'show_in_rest'          => true,
537
		);
538
		register_post_type( self::$post_type_product, $product_args );
539
	}
540
541
	/**
542
	 * Format a price for display
543
	 *
544
	 * Largely taken from WordPress.com Store_Price class
545
	 *
546
	 * The currency array will have the shape:
547
	 *   format  => string sprintf format with placeholders `%1$s`: Symbol `%2$s`: Price.
548
	 *   symbol  => string Symbol string
549
	 *   desc    => string Text description of currency
550
	 *   decimal => int    Number of decimal places
551
	 *
552
	 * @param  string $the_currency The desired currency, e.g. 'USD'.
553
	 * @return ?array               Currency object or null if not found.
0 ignored issues
show
Documentation introduced by
The doc-type ?array could not be parsed: Unknown type name "?array" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
554
	 */
555
	private static function get_currency( $the_currency ) {
556
		jetpack_require_lib( 'class-jetpack-currencies' );
557
		$currencies = Jetpack_Currencies::CURRENCIES;
558
559
		if ( isset( $currencies[ $the_currency ] ) ) {
560
			return $currencies[ $the_currency ];
561
		}
562
		return null;
563
	}
564
}
565
Jetpack_Simple_Payments::getInstance();
566