Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
86.29% covered (warning)
86.29%
340 / 394
58.82% covered (warning)
58.82%
10 / 17
CRAP
0.00% covered (danger)
0.00%
0 / 1
PayPal_Attribute_Mapper
86.73% covered (warning)
86.73%
340 / 392
58.82% covered (warning)
58.82%
10 / 17
248.31
0.00% covered (danger)
0.00%
0 / 1
 attributes_to_api_request
45.61% covered (danger)
45.61%
26 / 57
0.00% covered (danger)
0.00%
0 / 1
99.86
 api_response_to_attributes
85.90% covered (warning)
85.90%
67 / 78
0.00% covered (danger)
0.00%
0 / 1
43.27
 images_to_attributes
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
6
 merge_into_resource
91.30% covered (success)
91.30%
21 / 23
0.00% covered (danger)
0.00%
0 / 1
10.07
 extract_script_src
92.31% covered (success)
92.31%
12 / 13
0.00% covered (danger)
0.00%
0 / 1
7.02
 validate_attributes
100.00% covered (success)
100.00%
88 / 88
100.00% covered (success)
100.00%
1 / 1
30
 is_valid_resource_id
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 is_api_managed
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 merge_response_attributes
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 is_zero_decimal_currency
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 get_invalid_price_message
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 is_valid_price
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
6.05
 get_variant_currency
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
4.13
 variants_have_pricing
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
9
 validate_variant_structure
100.00% covered (success)
100.00%
29 / 29
100.00% covered (success)
100.00%
1 / 1
11
 validate_variant_pricing
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
7
 sanitize_variants
85.29% covered (warning)
85.29%
29 / 34
0.00% covered (danger)
0.00%
0 / 1
14.62
1<?php
2/**
3 * Attribute mapper between WordPress block attributes and PayPal Pay Links & Buttons API.
4 *
5 * Maps a PayPal API response onto block attributes, and validates them before a save.
6 * The block builds its own request body in utils/request-data.js.
7 *
8 * @package automattic/jetpack-paypal-payments
9 * @since 0.8.0
10 */
11
12namespace Automattic\Jetpack\PaypalPayments;
13
14if ( ! defined( 'ABSPATH' ) ) {
15    exit;
16}
17
18use WP_Error;
19
20/**
21 * Class PayPal_Attribute_Mapper
22 *
23 * Maps block editor attributes to PayPal API request/response formats.
24 * Provides validation, sanitization, and transformation for Phase 1
25 * (BUY_NOW type, LINK integration mode, single line item).
26 */
27class PayPal_Attribute_Mapper {
28
29    /**
30     * Supported currency codes for Phase 1.
31     *
32     * PayPal supports many currencies, but we validate against the most common
33     * to prevent typos. Full list at:
34     * https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/
35     *
36     * @var array
37     */
38    const SUPPORTED_CURRENCIES = array(
39        'USD',
40        'EUR',
41        'GBP',
42        'CAD',
43        'AUD',
44        'JPY',
45        'CNY',
46        'CHF',
47        'SEK',
48        'NOK',
49        'DKK',
50        'NZD',
51        'SGD',
52        'HKD',
53        'MXN',
54        'BRL',
55        'PLN',
56        'CZK',
57        'HUF',
58        'ILS',
59        'MYR',
60        'PHP',
61        'TWD',
62        'THB',
63    );
64
65    /**
66     * Maximum number of option groups (variant dimensions) per product.
67     *
68     * @since 0.9.0
69     *
70     * @var int
71     */
72    const MAX_VARIANT_DIMENSIONS = 5;
73
74    /**
75     * Maximum number of options per option group.
76     *
77     * @since 0.9.0
78     *
79     * @var int
80     */
81    const MAX_VARIANT_OPTIONS = 10;
82
83    /**
84     * Line-item images PayPal shows on one payment. Mirrored in `utils/images.js`.
85     *
86     * @since 0.15.0
87     *
88     * @var int
89     */
90    const MAX_PRODUCT_IMAGES = 5;
91
92    /**
93     * Maximum product name length.
94     *
95     * @var int
96     */
97    const MAX_NAME_LENGTH = 127;
98
99    /**
100     * Maximum description length.
101     *
102     * Anything longer is a 400 `INVALID_STRING_LENGTH` from PayPal. Mirrored in
103     * `utils/validation.js`; change both together.
104     *
105     * @var int
106     */
107    const MAX_DESCRIPTION_LENGTH = 2048;
108
109    /**
110     * Maximum button text length.
111     *
112     * @var int
113     */
114    const MAX_BUTTON_TEXT_LENGTH = 50;
115
116    /**
117     * Maximum return URL length PayPal accepts.
118     *
119     * @var int
120     */
121    const MAX_RETURN_URL_LENGTH = 1024;
122
123    /**
124     * Maximum product id (SKU) length.
125     *
126     * @var int
127     */
128    const MAX_PRODUCT_ID_LENGTH = 50;
129
130    /**
131     * Maximum quantity a buyer can pick.
132     *
133     * Anything higher is a 400 `INVALID_INTEGER_MAX_VALUE` from PayPal. Mirrored in
134     * `utils/validation.js`; change both together.
135     *
136     * @var int
137     */
138    const MAX_QUANTITY = 100;
139
140    /**
141     * Keys a GET returns that a PUT must not send back.
142     *
143     * `payment_link` is this package's own copy of the HATEOAS link.
144     *
145     * @since 0.13.0
146     *
147     * @var string[]
148     */
149    const READ_ONLY_RESOURCE_KEYS = array(
150        'id',
151        'payment_link',
152        'links',
153        'create_time',
154        'update_time',
155        'status',
156        'code_snippets',
157    );
158
159    /**
160     * Top-level keys the block edits, so a save clears one it leaves out.
161     *
162     * With OWNED_LINE_ITEM_KEYS, these are the keys api_response_to_attributes() reads
163     * into editable attributes; change the three together.
164     *
165     * @since 0.13.0
166     *
167     * @var string[]
168     */
169    const OWNED_RESOURCE_KEYS = array(
170        'integration_mode',
171        'return_url',
172        'line_items',
173    );
174
175    /**
176     * Line item keys the block edits, so a save clears one it leaves out.
177     *
178     * `collect_shipping_address` is left off on purpose: PayPal turns address
179     * collection on for a body without it, so it stays as PayPal had it when not sent.
180     *
181     * @since 0.13.0
182     *
183     * @var string[]
184     */
185    const OWNED_LINE_ITEM_KEYS = array(
186        'name',
187        'unit_amount',
188        'description',
189        'product_id',
190        'images',
191        'variants',
192        'adjustable_quantity',
193        'customer_notes',
194        'taxes',
195        'shipping',
196        'handling',
197        'discounts',
198    );
199
200    /**
201     * Convert block attributes to a PayPal API request body.
202     *
203     * Only the tests call this.
204     *
205     * @param array $attributes Block attributes from the editor.
206     * @return array PayPal API request body.
207     */
208    public static function attributes_to_api_request( array $attributes ) {
209        $line_item = array(
210            'name' => sanitize_text_field( $attributes['productName'] ?? '' ),
211        );
212
213        // Product variants (dimensions with options).
214        if ( ! empty( $attributes['variantsEnabled'] ) && ! empty( $attributes['variants']['dimensions'] ) ) {
215            $line_item['variants'] = self::sanitize_variants( $attributes['variants'] );
216        }
217
218        // PayPal errors with "unit_amount is specified at both product level and
219        // variant level" when both are present, so per-option prices replace the
220        // product-level price rather than sitting alongside it.
221        if ( ! self::variants_have_pricing( $line_item['variants'] ?? null ) ) {
222            $line_item['unit_amount'] = array(
223                'currency_code' => sanitize_text_field( $attributes['currencyCode'] ?? 'USD' ),
224                'value'         => sanitize_text_field( $attributes['price'] ?? '0.00' ),
225            );
226        }
227
228        // Optional line item fields.
229        if ( ! empty( $attributes['productDescription'] ) ) {
230            $line_item['description'] = sanitize_text_field( $attributes['productDescription'] );
231        }
232
233        // Adjustable quantity.
234        if ( ! empty( $attributes['adjustableQuantity'] ) && ! empty( $attributes['maxQuantity'] ) ) {
235            $max = absint( $attributes['maxQuantity'] );
236            if ( $max >= 2 ) {
237                $line_item['adjustable_quantity'] = array( 'maximum' => $max );
238            }
239        }
240
241        // Customer notes / custom fields.
242        if ( ! empty( $attributes['customerNotes'] ) && is_array( $attributes['customerNotes'] ) ) {
243            $notes = array();
244            foreach ( $attributes['customerNotes'] as $note ) {
245                $label = sanitize_text_field( $note['label'] ?? '' );
246                if ( '' !== $label ) {
247                    $notes[] = array(
248                        'label'    => $label,
249                        'required' => ! empty( $note['required'] ),
250                    );
251                }
252            }
253            if ( ! empty( $notes ) ) {
254                $line_item['customer_notes'] = $notes;
255            }
256        }
257
258        // Tax configuration.
259        if ( ! empty( $attributes['taxEnabled'] ) && ! empty( $attributes['taxName'] ) ) {
260            $tax_type = sanitize_text_field( $attributes['taxType'] ?? 'PERCENTAGE' );
261            $tax      = array(
262                'name' => sanitize_text_field( $attributes['taxName'] ),
263                'type' => in_array( $tax_type, array( 'PERCENTAGE', 'PREFERENCE' ), true ) ? $tax_type : 'PERCENTAGE',
264            );
265
266            if ( 'PREFERENCE' === $tax_type ) {
267                $tax['value'] = 'PROFILE';
268            } else {
269                $tax['value'] = sanitize_text_field( $attributes['taxValue'] ?? '0' );
270            }
271
272            $line_item['taxes'] = array( $tax );
273        }
274
275        // Shipping configuration.
276        if ( ! empty( $attributes['shippingEnabled'] ) ) {
277            $shipping_type = sanitize_text_field( $attributes['shippingType'] ?? 'FLAT' );
278
279            $shipping = array(
280                'type' => in_array( $shipping_type, array( 'FLAT', 'PREFERENCE' ), true ) ? $shipping_type : 'FLAT',
281            );
282
283            if ( 'PREFERENCE' === $shipping_type ) {
284                $shipping['value'] = 'PROFILE';
285            } else {
286                $shipping['value'] = sanitize_text_field( $attributes['shippingValue'] ?? '0' );
287            }
288
289            $line_item['shipping'] = array( $shipping );
290        }
291
292        if ( ! empty( $attributes['collectShippingAddress'] ) ) {
293            $line_item['collect_shipping_address'] = true;
294        }
295
296        $request = array(
297            'type'             => 'BUY_NOW',
298            'integration_mode' => 'LINK',
299            'reusable'         => 'MULTIPLE',
300            'line_items'       => array( $line_item ),
301        );
302
303        // Optional top-level fields.
304        if ( ! empty( $attributes['returnUrl'] ) ) {
305            $request['return_url'] = esc_url_raw( $attributes['returnUrl'] );
306        }
307
308        return $request;
309    }
310
311    /**
312     * Convert a PayPal API response to block attributes.
313     *
314     * Extracts the relevant fields from the PayPal API response and maps
315     * them to the flat attribute structure used by the block editor.
316     *
317     * @param array $response PayPal API response body (decoded JSON).
318     * @return array Block attributes to store.
319     */
320    public static function api_response_to_attributes( array $response ) {
321        $attributes = array(
322            'isApiManaged' => true,
323            'resourceId'   => sanitize_text_field( $response['id'] ?? '' ),
324            'paymentLink'  => esc_url_raw( $response['payment_link'] ?? '' ),
325        );
326
327        // Extract first line item details.
328        if ( ! empty( $response['line_items'] ) && is_array( $response['line_items'] ) ) {
329            $line_item = $response['line_items'][0];
330
331            $attributes['productName'] = sanitize_text_field( $line_item['name'] ?? '' );
332
333            if ( isset( $line_item['unit_amount'] ) && is_array( $line_item['unit_amount'] ) ) {
334                $attributes['currencyCode'] = sanitize_text_field( $line_item['unit_amount']['currency_code'] ?? 'USD' );
335                $attributes['price']        = sanitize_text_field( $line_item['unit_amount']['value'] ?? '0.00' );
336            }
337
338            if ( ! empty( $line_item['description'] ) ) {
339                // Keep the line breaks PayPal sent back - sanitize_text_field() flattens them.
340                $attributes['productDescription'] = sanitize_textarea_field( $line_item['description'] );
341            }
342
343            if ( isset( $line_item['product_id'] ) && '' !== $line_item['product_id'] ) {
344                $attributes['productId'] = sanitize_text_field( $line_item['product_id'] );
345            }
346
347            if ( ! empty( $line_item['images'] ) && is_array( $line_item['images'] ) ) {
348                $attributes['images'] = self::images_to_attributes( $line_item['images'] );
349            }
350
351            if ( ! empty( $line_item['variants']['dimensions'] ) ) {
352                $attributes['variantsEnabled'] = true;
353                $attributes['variants']        = $line_item['variants'];
354
355                // With per-option pricing the currency lives on the options.
356                if ( ! isset( $attributes['currencyCode'] ) ) {
357                    $variant_currency = self::get_variant_currency( $line_item['variants'] );
358                    if ( null !== $variant_currency ) {
359                        $attributes['currencyCode'] = $variant_currency;
360                    }
361                }
362            }
363
364            // Adjustable quantity.
365            if ( ! empty( $line_item['adjustable_quantity']['maximum'] ) ) {
366                $attributes['adjustableQuantity'] = true;
367                $attributes['maxQuantity']        = absint( $line_item['adjustable_quantity']['maximum'] );
368            }
369
370            // Customer notes.
371            if ( ! empty( $line_item['customer_notes'] ) && is_array( $line_item['customer_notes'] ) ) {
372                $attributes['customerNotes'] = array_map(
373                    function ( $note ) {
374                        return array(
375                            'label'    => sanitize_text_field( $note['label'] ?? '' ),
376                            'required' => ! empty( $note['required'] ),
377                        );
378                    },
379                    $line_item['customer_notes']
380                );
381            }
382
383            // Tax configuration.
384            if ( ! empty( $line_item['taxes'] ) && is_array( $line_item['taxes'] ) ) {
385                $tax                      = $line_item['taxes'][0];
386                $attributes['taxEnabled'] = true;
387                $attributes['taxName']    = sanitize_text_field( $tax['name'] ?? 'Sales Tax' );
388                $attributes['taxType']    = sanitize_text_field( $tax['type'] ?? 'PERCENTAGE' );
389                $attributes['taxValue']   = 'PREFERENCE' === $attributes['taxType'] ? '' : sanitize_text_field( $tax['value'] ?? '' );
390            }
391
392            // Shipping configuration. PayPal stores a type and a value, so the
393            // block's mode comes from both.
394            if ( ! empty( $line_item['shipping'] ) && is_array( $line_item['shipping'] ) ) {
395                $shipping = $line_item['shipping'][0];
396                $type     = sanitize_text_field( $shipping['type'] ?? 'FLAT' );
397                $value    = sanitize_text_field( $shipping['value'] ?? '' );
398                $extra    = sanitize_text_field( $shipping['additional_unit_value'] ?? '' );
399
400                $attributes['shippingEnabled'] = true;
401
402                if ( 'PREFERENCE' === $type ) {
403                    // `value` tells PROFILE from FREE_SHIPPING. Both modes hide the fee
404                    // field, so clear it.
405                    $attributes['shippingMode']  = 'FREE_SHIPPING' === $value ? 'FREE' : 'PROFILE';
406                    $attributes['shippingValue'] = '';
407                } else {
408                    // `additional_unit_value` tells QUANTITY from FLAT, so a quantity fee
409                    // that left it blank reads back as FLAT. Same charge either way.
410                    $attributes['shippingMode']  = '' !== $extra ? 'QUANTITY' : 'FLAT';
411                    $attributes['shippingValue'] = $value;
412                    if ( '' !== $extra ) {
413                        $attributes['shippingAdditionalValue'] = $extra;
414                    }
415                }
416            }
417
418            // Handling fee. The type is always FLAT, so the amount is all that comes back.
419            if ( ! empty( $line_item['handling'] ) && is_array( $line_item['handling'] ) ) {
420                $handling                      = $line_item['handling'][0];
421                $attributes['handlingEnabled'] = true;
422                $attributes['handlingValue']   = sanitize_text_field( $handling['value'] ?? '' );
423            }
424
425            // Discount. Store the type as PayPal sent it so a type set in PayPal's
426            // dashboard survives a save from the block.
427            if ( ! empty( $line_item['discounts'] ) && is_array( $line_item['discounts'] ) ) {
428                $discount = $line_item['discounts'][0] ?? null;
429                if ( is_array( $discount ) ) {
430                    $attributes['discountEnabled'] = true;
431                    $attributes['discountType']    = sanitize_text_field( $discount['type'] ?? 'FLAT' );
432                    $attributes['discountValue']   = sanitize_text_field( $discount['value'] ?? '' );
433                }
434            }
435
436            // The payment is the source of truth, so an absent key reads as off.
437            $attributes['collectShippingAddress'] = ! empty( $line_item['collect_shipping_address'] );
438        }
439
440        // Extract return_url if present.
441        if ( ! empty( $response['return_url'] ) ) {
442            $attributes['returnUrl'] = esc_url_raw( $response['return_url'] );
443        }
444
445        // Extract payment_link from HATEOAS links if not in top-level field.
446        if ( empty( $attributes['paymentLink'] ) && ! empty( $response['links'] ) && is_array( $response['links'] ) ) {
447            foreach ( $response['links'] as $link ) {
448                if ( isset( $link['rel'] ) && 'payment_link' === $link['rel'] && ! empty( $link['href'] ) ) {
449                    $attributes['paymentLink'] = esc_url_raw( $link['href'] );
450                    break;
451                }
452            }
453        }
454
455        // The payment's own mode, so a LINK or QR block re-sends it instead of downgrading
456        // a stacked payment. Anything outside the REST enum becomes '', since storing it
457        // would 400 every later save.
458        $mode                          = sanitize_text_field( $response['integration_mode'] ?? '' );
459        $attributes['integrationMode'] = in_array( $mode, array( 'LINK', 'BUTTON' ), true ) ? $mode : '';
460
461        // The SDK URL the stacked format draws with. Only a BUTTON-mode payment has
462        // code_snippets, so LINK mode gives ''.
463        $attributes['scriptSrc'] = self::extract_script_src( $response );
464
465        return $attributes;
466    }
467
468    /**
469     * A payment's line-item images as the block stores them, the primary one first.
470     *
471     * An image still in review has no URLs yet; the block keeps the media library's
472     * own thumbnail for it.
473     *
474     * @since 0.15.0
475     *
476     * @param array $images Images as PayPal returns them.
477     * @return array Each with assetId, status, url and thumbnailUrl.
478     */
479    public static function images_to_attributes( array $images ) {
480        $mapped = array();
481
482        foreach ( $images as $image ) {
483            $asset_id = is_array( $image ) ? trim( (string) ( $image['asset_id'] ?? '' ) ) : '';
484            if ( '' === $asset_id ) {
485                continue;
486            }
487
488            $row = array(
489                'assetId'      => sanitize_text_field( $asset_id ),
490                'status'       => 'IN_REVIEW' === ( $image['status'] ?? '' ) ? 'IN_REVIEW' : 'APPROVED',
491                'url'          => esc_url_raw( (string) ( $image['url'] ?? '' ) ),
492                'thumbnailUrl' => esc_url_raw( (string) ( $image['thumbnail_url'] ?? '' ) ),
493            );
494
495            if ( ! empty( $image['is_primary'] ) ) {
496                array_unshift( $mapped, $row );
497            } else {
498                $mapped[] = $row;
499            }
500        }
501
502        return $mapped;
503    }
504
505    /**
506     * Lay a block's request body over the payment as PayPal holds it.
507     *
508     * A PUT replaces the whole payment, so a key the block does not model is lost
509     * unless it is carried over from a GET. Owned keys are last-write-wins: set when
510     * the body has them, dropped when it does not, since leaving one out is how a PUT
511     * clears it. Line items merge per index, so a second item PayPal holds survives.
512     *
513     * @since 0.13.0
514     *
515     * @param array $current The payment as a GET returned it.
516     * @param array $update  The body built from the block.
517     * @return array The body to PUT.
518     */
519    public static function merge_into_resource( array $current, array $update ) {
520        $merged = array_diff_key(
521            $current,
522            array_flip( self::READ_ONLY_RESOURCE_KEYS ),
523            array_flip( self::OWNED_RESOURCE_KEYS )
524        );
525
526        $current_items = isset( $current['line_items'] ) && is_array( $current['line_items'] )
527            ? $current['line_items']
528            : array();
529
530        foreach ( $update as $key => $value ) {
531            if ( 'line_items' === $key ) {
532                continue;
533            }
534            $merged[ $key ] = $value;
535        }
536
537        if ( isset( $update['line_items'] ) && is_array( $update['line_items'] ) ) {
538            $merged['line_items'] = $current_items;
539            foreach ( $update['line_items'] as $index => $item ) {
540                $current_item = isset( $current_items[ $index ] ) && is_array( $current_items[ $index ] )
541                    ? $current_items[ $index ]
542                    : array();
543
544                $merged['line_items'][ $index ] = array_merge(
545                    array_diff_key( $current_item, array_flip( self::OWNED_LINE_ITEM_KEYS ) ),
546                    $item
547                );
548            }
549        }
550
551        return $merged;
552    }
553
554    /**
555     * Extract the PayPal SDK URL from a payment's stacked code snippet.
556     *
557     * PayPal returns a snippet per framework; the HTML one has a plain `<script src="…">`.
558     * The URL includes the merchant's client-id and currency, so it has to be read back.
559     *
560     * @param array $response The payment resource from the API.
561     * @return string The sanitized SDK URL, or '' when there is none.
562     */
563    private static function extract_script_src( array $response ) {
564        $snippets = $response['code_snippets']['stacked'] ?? null;
565        if ( ! is_array( $snippets ) ) {
566            return '';
567        }
568
569        foreach ( $snippets as $snippet ) {
570            if ( ! is_array( $snippet ) || 'HTML' !== ( $snippet['framework'] ?? '' ) ) {
571                continue;
572            }
573
574            // Match on the script tag: the first `src=` in PayPal's snippet may belong
575            // to something else.
576            if ( ! preg_match( '/<script[^>]+src=[\'"]([^\'"]+)[\'"]/i', (string) ( $snippet['head'] ?? '' ), $matches ) ) {
577                continue;
578            }
579
580            $url = PayPal_Payment_Buttons::sanitize_paypal_script_url(
581                html_entity_decode( $matches[1], ENT_QUOTES | ENT_HTML5, 'UTF-8' )
582            );
583
584            return false === $url ? '' : $url;
585        }
586
587        return '';
588    }
589
590    /**
591     * Validate block attributes before sending to the PayPal API.
592     *
593     * Checks required fields, format constraints, and business rules.
594     * Returns WP_Error on failure with specific error codes for each validation issue.
595     *
596     * @param array $attributes Block attributes to validate.
597     * @return true|WP_Error True if valid, WP_Error with details on failure.
598     */
599    public static function validate_attributes( array $attributes ) {
600        // trim() throws on an array, so only a string counts as a name.
601        $product_name = is_string( $attributes['productName'] ?? null ) ? $attributes['productName'] : '';
602
603        // Required: product name (reject empty and whitespace-only).
604        if ( empty( $product_name ) || '' === trim( $product_name ) ) {
605            return new WP_Error(
606                'missing_product_name',
607                __( 'Product name is required.', 'jetpack-paypal-payments' ),
608                array( 'status' => 400 )
609            );
610        }
611
612        if ( mb_strlen( sanitize_text_field( $product_name ) ) > self::MAX_NAME_LENGTH ) {
613            return new WP_Error(
614                'product_name_too_long',
615                /* translators: %d: maximum allowed characters */
616                sprintf( __( 'Product name must be %d characters or fewer.', 'jetpack-paypal-payments' ), self::MAX_NAME_LENGTH ),
617                array( 'status' => 400 )
618            );
619        }
620
621        // Anything sanitize_variants() would drop must be rejected here instead,
622        // or the pricing checks below run against options PayPal never receives.
623        if ( ! empty( $attributes['variantsEnabled'] ) && ! empty( $attributes['variants']['dimensions'] ) ) {
624            $variant_structure_error = self::validate_variant_structure( $attributes['variants'] );
625            if ( is_wp_error( $variant_structure_error ) ) {
626                return $variant_structure_error;
627            }
628        }
629
630        // Required: price â€” unless the product options carry their own prices,
631        // in which case PayPal takes the amount from the options instead.
632        $uses_variant_pricing = ! empty( $attributes['variantsEnabled'] )
633            && self::variants_have_pricing( $attributes['variants'] ?? null );
634
635        $has_price = isset( $attributes['price'] ) && '' !== $attributes['price'];
636
637        if ( ! $has_price && ! $uses_variant_pricing ) {
638            return new WP_Error(
639                'missing_price',
640                __( 'Price is required.', 'jetpack-paypal-payments' ),
641                array( 'status' => 400 )
642            );
643        }
644
645        // The currency decides how many decimals a price may carry, so the
646        // price checks need it before it is itself validated below.
647        $currency = strtoupper( sanitize_text_field( (string) ( $attributes['currencyCode'] ?? 'USD' ) ) );
648
649        if ( $has_price && ! self::is_valid_price( $attributes['price'], $currency ) ) {
650            return new WP_Error(
651                'invalid_price',
652                self::get_invalid_price_message( $currency ),
653                array( 'status' => 400 )
654            );
655        }
656
657        if ( $uses_variant_pricing ) {
658            $variant_price_error = self::validate_variant_pricing( $attributes['variants'], $currency );
659            if ( is_wp_error( $variant_price_error ) ) {
660                return $variant_price_error;
661            }
662        }
663
664        // Required: currency code.
665        if ( ! in_array( $currency, self::SUPPORTED_CURRENCIES, true ) ) {
666            return new WP_Error(
667                'invalid_currency',
668                __( 'Unsupported currency code.', 'jetpack-paypal-payments' ),
669                array( 'status' => 400 )
670            );
671        }
672
673        // Optional: description length.
674        if ( ! empty( $attributes['productDescription'] ) ) {
675            // Count it as the merchant wrote it - sanitize_text_field() collapses
676            // newlines, so a long description measures short.
677            $description = sanitize_textarea_field( $attributes['productDescription'] );
678            if ( mb_strlen( $description ) > self::MAX_DESCRIPTION_LENGTH ) {
679                return new WP_Error(
680                    'description_too_long',
681                    /* translators: %d: maximum allowed characters */
682                    sprintf( __( 'Description must be %d characters or fewer.', 'jetpack-paypal-payments' ), self::MAX_DESCRIPTION_LENGTH ),
683                    array( 'status' => 400 )
684                );
685            }
686        }
687
688        // Optional: product id length.
689        if ( ! empty( $attributes['productId'] ) ) {
690            $product_id = sanitize_text_field( $attributes['productId'] );
691            if ( mb_strlen( $product_id ) > self::MAX_PRODUCT_ID_LENGTH ) {
692                return new WP_Error(
693                    'product_id_too_long',
694                    /* translators: %d: maximum allowed characters */
695                    sprintf( __( 'Product ID must be %d characters or fewer.', 'jetpack-paypal-payments' ), self::MAX_PRODUCT_ID_LENGTH ),
696                    array( 'status' => 400 )
697                );
698            }
699        }
700
701        // Optional: maximum quantity. absint() so -101 is checked as the 101 the sanitizer sends PayPal.
702        if ( ! empty( $attributes['adjustableQuantity'] ) && absint( $attributes['maxQuantity'] ?? 0 ) > self::MAX_QUANTITY ) {
703            return new WP_Error(
704                'max_quantity_too_high',
705                /* translators: %d: the largest maximum quantity allowed */
706                sprintf( __( 'Maximum quantity must be %d or less.', 'jetpack-paypal-payments' ), self::MAX_QUANTITY ),
707                array( 'status' => 400 )
708            );
709        }
710
711        // Optional: button text length.
712        if ( ! empty( $attributes['buttonText'] ) ) {
713            $button_text = sanitize_text_field( $attributes['buttonText'] );
714            if ( mb_strlen( $button_text ) > self::MAX_BUTTON_TEXT_LENGTH ) {
715                return new WP_Error(
716                    'button_text_too_long',
717                    /* translators: %d: maximum allowed characters */
718                    sprintf( __( 'Button text must be %d characters or fewer.', 'jetpack-paypal-payments' ), self::MAX_BUTTON_TEXT_LENGTH ),
719                    array( 'status' => 400 )
720                );
721            }
722        }
723
724        // Optional: return URL validation.
725        if ( ! empty( $attributes['returnUrl'] ) ) {
726            $return_url = esc_url_raw( $attributes['returnUrl'] );
727            // wp_http_validate_url() accepts `//example.com`, so check the scheme as well.
728            if ( empty( $return_url ) || ! wp_http_validate_url( $return_url ) || ! preg_match( '#^https?://#', $return_url ) ) {
729                return new WP_Error(
730                    'invalid_return_url',
731                    __( 'Return URL must be a valid URL.', 'jetpack-paypal-payments' ),
732                    array( 'status' => 400 )
733                );
734            }
735            if ( mb_strlen( $return_url ) > self::MAX_RETURN_URL_LENGTH ) {
736                return new WP_Error(
737                    'return_url_too_long',
738                    /* translators: %d: maximum allowed characters */
739                    sprintf( __( 'Return URL must be %d characters or fewer.', 'jetpack-paypal-payments' ), self::MAX_RETURN_URL_LENGTH ),
740                    array( 'status' => 400 )
741                );
742            }
743        }
744
745        return true;
746    }
747
748    /**
749     * Validate a resource ID format (PLB-XXXXXXXXXXXX).
750     *
751     * @param string $resource_id The resource ID to validate.
752     * @return bool True if valid format.
753     */
754    public static function is_valid_resource_id( $resource_id ) {
755        return (bool) preg_match( '/^PLB-[A-Za-z0-9]+$/', $resource_id );
756    }
757
758    /**
759     * Check whether block attributes indicate a V2 API-managed block.
760     *
761     * @param array $attributes Block attributes.
762     * @return bool True if the block is managed via the PayPal API (V2).
763     */
764    public static function is_api_managed( array $attributes ) {
765        return ! empty( $attributes['isApiManaged'] ) && true === $attributes['isApiManaged'];
766    }
767
768    /**
769     * Merge API response attributes into existing block attributes.
770     *
771     * After a create or update API call, merge the response data back
772     * into the block attributes without overwriting frontend-only fields
773     * like buttonText and buttonType.
774     *
775     * @param array $existing_attributes Current block attributes.
776     * @param array $response_attributes Attributes extracted from API response.
777     * @return array Merged attributes.
778     */
779    public static function merge_response_attributes( array $existing_attributes, array $response_attributes ) {
780        // Frontend-only fields that should not be overwritten by API response.
781        $preserve_keys = array( 'buttonText', 'buttonType' );
782
783        $merged = array_merge( $existing_attributes, $response_attributes );
784
785        // Restore preserved frontend-only values.
786        foreach ( $preserve_keys as $key ) {
787            if ( isset( $existing_attributes[ $key ] ) ) {
788                $merged[ $key ] = $existing_attributes[ $key ];
789            }
790        }
791
792        return $merged;
793    }
794
795    /**
796     * Whether PayPal prices a currency without decimals.
797     *
798     * PayPal rejects a decimal amount in these currencies outright rather than
799     * rounding it. The legacy currency table already records which they are.
800     *
801     * @since 0.9.0
802     *
803     * @param string $currency ISO currency code.
804     * @return bool True for JPY, HUF and TWD.
805     */
806    public static function is_zero_decimal_currency( $currency ) {
807        $currency = strtoupper( (string) $currency );
808
809        return in_array( $currency, self::SUPPORTED_CURRENCIES, true )
810            && isset( \PayPal_Payments_Currencies::CURRENCIES[ $currency ]['decimal'] )
811            && 0 === \PayPal_Payments_Currencies::CURRENCIES[ $currency ]['decimal'];
812    }
813
814    /**
815     * The message for a price PayPal would not accept in the given currency.
816     *
817     * @since 0.9.0
818     *
819     * @param string $currency ISO currency code.
820     * @return string Translated message.
821     */
822    private static function get_invalid_price_message( $currency ) {
823        if ( self::is_zero_decimal_currency( $currency ) ) {
824            /* translators: %s: currency code, e.g. JPY */
825            return sprintf( __( 'Prices in %s must be whole numbers (e.g., "1500").', 'jetpack-paypal-payments' ), $currency );
826        }
827
828        return __( 'Price must be a valid positive number (e.g., "29.99").', 'jetpack-paypal-payments' );
829    }
830
831    /**
832     * Validate a price string.
833     *
834     * The price must be a positive number with at most two decimal places, or
835     * a whole number in a currency PayPal prices without decimals. PayPal
836     * requires string format prices like "29.99".
837     *
838     * @param string $price    The price string to validate.
839     * @param string $currency ISO currency code the price is in.
840     * @return bool True if valid.
841     */
842    private static function is_valid_price( $price, $currency = 'USD' ) {
843        // Must be a string representation of a positive decimal number.
844        if ( ! is_string( $price ) && ! is_numeric( $price ) ) {
845            return false;
846        }
847
848        $price = (string) $price;
849
850        $pattern = self::is_zero_decimal_currency( $currency ) ? '/^\d+$/' : '/^\d+(\.\d{1,2})?$/';
851        if ( ! preg_match( $pattern, $price ) ) {
852            return false;
853        }
854
855        // Must be greater than zero.
856        if ( (float) $price <= 0 ) {
857            return false;
858        }
859
860        return true;
861    }
862
863    /**
864     * Find the currency the per-option prices are in.
865     *
866     * @since 0.9.0
867     *
868     * @param array|null $variants Variants structure (block or API shape).
869     * @return string|null The first priced option's currency code, or null when none is priced.
870     */
871    private static function get_variant_currency( $variants ) {
872        foreach ( ( $variants['dimensions'] ?? array() ) as $dimension ) {
873            foreach ( ( $dimension['options'] ?? array() ) as $option ) {
874                if ( ! empty( $option['unit_amount']['currency_code'] ) ) {
875                    return sanitize_text_field( $option['unit_amount']['currency_code'] );
876                }
877            }
878        }
879
880        return null;
881    }
882
883    /**
884     * Whether a variants structure carries per-option pricing.
885     *
886     * PayPal rejects a line item that specifies `unit_amount` at both the
887     * product level and the variant level, so the two are mutually exclusive.
888     * Once any option in the primary dimension has its own amount, the
889     * product-level amount must be omitted.
890     *
891     * @since 0.9.0
892     *
893     * @param array|null $variants Variants structure (block or API shape).
894     * @return bool True when at least one option carries its own amount.
895     */
896    public static function variants_have_pricing( $variants ) {
897        if ( empty( $variants['dimensions'] ) || ! is_array( $variants['dimensions'] ) ) {
898            return false;
899        }
900
901        foreach ( $variants['dimensions'] as $dimension ) {
902            if ( empty( $dimension['primary'] ) || empty( $dimension['options'] ) || ! is_array( $dimension['options'] ) ) {
903                continue;
904            }
905
906            foreach ( $dimension['options'] as $option ) {
907                if ( '' !== trim( (string) ( $option['unit_amount']['value'] ?? '' ) ) ) {
908                    return true;
909                }
910            }
911        }
912
913        return false;
914    }
915
916    /**
917     * Validate the shape of a variants structure.
918     *
919     * Checks group and option names and counts. validate_variant_pricing() covers the amounts.
920     *
921     * @since 0.9.0
922     *
923     * @param array $variants Variants structure (block or API shape).
924     * @return true|WP_Error True when valid, WP_Error otherwise.
925     */
926    private static function validate_variant_structure( array $variants ) {
927        $dimensions = $variants['dimensions'] ?? array();
928
929        if ( ! is_array( $dimensions ) || count( $dimensions ) > self::MAX_VARIANT_DIMENSIONS ) {
930            return new WP_Error(
931                'too_many_variant_dimensions',
932                /* translators: %d: maximum number of option groups */
933                sprintf( __( 'A product can have at most %d option groups.', 'jetpack-paypal-payments' ), self::MAX_VARIANT_DIMENSIONS ),
934                array( 'status' => 400 )
935            );
936        }
937
938        foreach ( $dimensions as $dimension ) {
939            if ( ! is_array( $dimension ) || '' === trim( sanitize_text_field( (string) ( $dimension['name'] ?? '' ) ) ) ) {
940                return new WP_Error(
941                    'missing_variant_name',
942                    __( 'Every option group needs a name.', 'jetpack-paypal-payments' ),
943                    array( 'status' => 400 )
944                );
945            }
946
947            $options = $dimension['options'] ?? array();
948            if ( ! is_array( $options ) || count( $options ) > self::MAX_VARIANT_OPTIONS ) {
949                return new WP_Error(
950                    'too_many_variant_options',
951                    /* translators: %d: maximum number of options per group */
952                    sprintf( __( 'An option group can have at most %d options.', 'jetpack-paypal-payments' ), self::MAX_VARIANT_OPTIONS ),
953                    array( 'status' => 400 )
954                );
955            }
956
957            foreach ( $options as $option ) {
958                if ( ! is_array( $option ) || '' === trim( sanitize_text_field( (string) ( $option['label'] ?? '' ) ) ) ) {
959                    return new WP_Error(
960                        'missing_variant_label',
961                        __( 'Every product option needs a label.', 'jetpack-paypal-payments' ),
962                        array( 'status' => 400 )
963                    );
964                }
965            }
966        }
967
968        return true;
969    }
970
971    /**
972     * Validate per-option pricing.
973     *
974     * Per-option prices replace the product-level price, so they are
975     * all-or-nothing: every option in the primary dimension must carry a
976     * valid amount once any of them does.
977     *
978     * @since 0.9.0
979     *
980     * @param array|null $variants Variants structure (block or API shape).
981     * @param string     $currency ISO currency code the option prices are in.
982     * @return true|WP_Error True when valid, WP_Error otherwise.
983     */
984    private static function validate_variant_pricing( $variants, $currency = 'USD' ) {
985        foreach ( ( $variants['dimensions'] ?? array() ) as $dimension ) {
986            if ( empty( $dimension['primary'] ) ) {
987                continue;
988            }
989
990            foreach ( ( $dimension['options'] ?? array() ) as $option ) {
991                $value = trim( (string) ( $option['unit_amount']['value'] ?? '' ) );
992
993                if ( '' === $value ) {
994                    return new WP_Error(
995                        'missing_variant_price',
996                        __( 'Every product option must have a price when any option in the group has one.', 'jetpack-paypal-payments' ),
997                        array( 'status' => 400 )
998                    );
999                }
1000
1001                if ( ! self::is_valid_price( $value, $currency ) ) {
1002                    if ( self::is_zero_decimal_currency( $currency ) ) {
1003                        /* translators: %s: currency code, e.g. JPY */
1004                        $message = sprintf( __( 'Product option prices in %s must be whole numbers (e.g., "1500").', 'jetpack-paypal-payments' ), $currency );
1005                    } else {
1006                        $message = __( 'Product option prices must be valid positive numbers (e.g., "29.99").', 'jetpack-paypal-payments' );
1007                    }
1008
1009                    return new WP_Error( 'invalid_variant_price', $message, array( 'status' => 400 ) );
1010                }
1011            }
1012        }
1013
1014        return true;
1015    }
1016
1017    /**
1018     * Sanitize and validate a variants structure for the PayPal API.
1019     *
1020     * Enforces: max 5 dimensions, max 10 options per dimension,
1021     * only the primary dimension may have per-option pricing.
1022     *
1023     * @param array $variants Raw variants from block attributes.
1024     * @return array Sanitized variants ready for the API.
1025     */
1026    private static function sanitize_variants( array $variants ) {
1027        if ( empty( $variants['dimensions'] ) || ! is_array( $variants['dimensions'] ) ) {
1028            return array( 'dimensions' => array() );
1029        }
1030
1031        $sanitized_dimensions = array();
1032        $count                = 0;
1033
1034        foreach ( $variants['dimensions'] as $dimension ) {
1035            if ( ++$count > self::MAX_VARIANT_DIMENSIONS ) {
1036                break;
1037            }
1038
1039            $dim = array(
1040                'name'    => sanitize_text_field( $dimension['name'] ?? '' ),
1041                'primary' => ! empty( $dimension['primary'] ),
1042                'options' => array(),
1043            );
1044
1045            if ( empty( $dim['name'] ) ) {
1046                continue;
1047            }
1048
1049            $option_count = 0;
1050            foreach ( ( $dimension['options'] ?? array() ) as $option ) {
1051                if ( ++$option_count > self::MAX_VARIANT_OPTIONS ) {
1052                    break;
1053                }
1054
1055                $opt = array(
1056                    'label' => sanitize_text_field( $option['label'] ?? '' ),
1057                );
1058
1059                if ( empty( $opt['label'] ) ) {
1060                    continue;
1061                }
1062
1063                // Only the primary dimension can have per-option pricing, and an
1064                // empty value is "no price" rather than a price of nothing.
1065                if ( $dim['primary'] && ! empty( $option['unit_amount'] ) && is_array( $option['unit_amount'] ) ) {
1066                    $value = trim( sanitize_text_field( (string) ( $option['unit_amount']['value'] ?? '' ) ) );
1067                    if ( '' !== $value ) {
1068                        $opt['unit_amount'] = array(
1069                            'currency_code' => sanitize_text_field( $option['unit_amount']['currency_code'] ?? 'USD' ),
1070                            'value'         => $value,
1071                        );
1072                    }
1073                }
1074
1075                $dim['options'][] = $opt;
1076            }
1077
1078            if ( ! empty( $dim['options'] ) ) {
1079                $sanitized_dimensions[] = $dim;
1080            }
1081        }
1082
1083        return array( 'dimensions' => $sanitized_dimensions );
1084    }
1085}