Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 | 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 719x 719x 53x 666x 799x 171x 628x 628x 4x 624x 756x 161x 595x 1x 594x 755x 6x 749x 10x 3x 7x 142x 142x 100x 25x 75x 42x 15x 27x 5x 22x 2x 20x 44x 29x 29x 8x 21x 8x 13x 5x 8x 41x 41x 15x 26x 26x 6x 20x 34x 1376x 1376x 432x 944x 944x 29x 915x 770x 742x 28x 17x 11x 1x 10x 750x 747x 3x 16x 3647x 34954x 3647x 1225x 750x 750x 2213x 28x 26x 2x 1x 1x 29x 6x | /**
* PayPal Payment Buttons — Validation Utilities.
*
* Extracted from edit.js for testability. These functions validate
* form inputs client-side before API submission and map API errors
* to user-friendly messages. sanitizePayPalUrl() does the same for a URL held
* in a block attribute rather than typed into a field.
*
* @package
* @since 0.8.0
*/
import { __, sprintf } from '@wordpress/i18n';
import { VALID_CURRENCY_CODES } from './currencies';
import { ZERO_DECIMAL_CURRENCIES } from './currency-symbols';
/**
* Validation constants - PayPal's own limits, mirrored in `PayPal_Attribute_Mapper`.
* Change both together. A character over either is a 400 `INVALID_STRING_LENGTH`.
*/
export const MAX_NAME_LENGTH = 127;
export const MAX_DESCRIPTION_LENGTH = 2048;
// PayPal rejects a longer return URL with a 400.
export const MAX_RETURN_URL_LENGTH = 1024;
// Caps the Product ID input. The server answers a longer one with product_id_too_long.
export const MAX_PRODUCT_ID_LENGTH = 50;
// PayPal rejects a higher maximum quantity with a 400.
export const MAX_QUANTITY = 100;
// PayPal rejects a third custom checkout field with a 400.
export const MAX_CUSTOMER_NOTES = 2;
// Shipping modes that ask the merchant for an amount. The form draws the fee field
// from this list and the validator checks it from the same one.
export const SHIPPING_MODES_WITH_FEE = [ 'FLAT', 'QUANTITY' ];
// A copy of `PayPal_API_Client::ALLOWED_PAYPAL_DOMAINS`, under the same name. Exported
// because test_paypal_host_allow_lists_are_in_sync() reads this declaration out of the
// file to compare the two.
export const ALLOWED_PAYPAL_DOMAINS = [
'www.paypal.com',
'paypal.com',
'www.sandbox.paypal.com',
'sandbox.paypal.com',
];
// Shown under a field a merchant turned on and left empty. validateCustomerNotes()
// reuses it.
export const REQUIRED_FIELD_ERROR = __(
'To continue, add the requested info or turn off this feature.',
'jetpack-paypal-payments'
);
// PayPal's link builder copy, word for word. PayPal rejects tax or shipping from PayPal
// settings without the address.
export const ADDRESS_REQUIRED_ERROR = __(
'You need to be able to collect customer shipping address first.',
'jetpack-paypal-payments'
);
/**
* Check the decimals a price carries against what PayPal accepts for the currency.
*
* PayPal rejects any decimal for JPY, HUF and TWD; every other currency takes up to two.
*
* @param {string} value - The price value.
* @param {string} currencyCode - The ISO currency code the price is in.
* @return {string|null} Error message or null if valid.
*/
export function getPriceFormatError( value, currencyCode = 'USD' ) {
const trimmed = `${ value ?? '' }`.trim();
if ( ZERO_DECIMAL_CURRENCIES.has( currencyCode ) ) {
return /^\d+$/.test( trimmed )
? null
: sprintf(
/* translators: %s: currency code, e.g. JPY */
__( 'Prices in %s are whole numbers (e.g., "1500").', 'jetpack-paypal-payments' ),
currencyCode
);
}
return /^\d+(\.\d{1,2})?$/.test( trimmed )
? null
: __( 'Price can have at most 2 decimal places (e.g., "29.99").', 'jetpack-paypal-payments' );
}
/**
* Validate a price string.
*
* @param {string} value - The price value.
* @param {string} currencyCode - The ISO currency code the price is in.
* @return {string|null} Error message or null if valid.
*/
export function validatePrice( value, currencyCode = 'USD' ) {
if ( ! value || value.trim() === '' ) {
return __( 'Price is required.', 'jetpack-paypal-payments' );
}
const num = parseFloat( value );
if ( isNaN( num ) || num <= 0 ) {
return __( 'Price must be a positive number.', 'jetpack-paypal-payments' );
}
return getPriceFormatError( value, currencyCode );
}
/**
* Validate a product name.
*
* @param {string} value - The product name.
* @return {string|null} Error message or null if valid.
*/
export function validateProductName( value ) {
if ( ! value || value.trim() === '' ) {
return __( 'Product name is required.', 'jetpack-paypal-payments' );
}
if ( value.length > MAX_NAME_LENGTH ) {
return sprintf(
/* translators: %d: maximum number of characters allowed for the product name */
__( 'Product name must be %d characters or fewer.', 'jetpack-paypal-payments' ),
MAX_NAME_LENGTH
);
}
return null;
}
/**
* Validate a description (optional field).
*
* @param {string} value - The description.
* @return {string|null} Error message or null if valid.
*/
export function validateDescription( value ) {
// The server trims before it measures, so trim here to match.
if ( value && value.trim().length > MAX_DESCRIPTION_LENGTH ) {
return sprintf(
/* translators: %d: maximum number of characters allowed for the description */
__( 'Description must be %d characters or fewer.', 'jetpack-paypal-payments' ),
MAX_DESCRIPTION_LENGTH
);
}
return null;
}
/**
* Validate a maximum quantity.
*
* Checks the upper limit. The field's own minimum and fallback handle the low end.
*
* @param {number|string} value - The maximum quantity.
* @return {string|null} Error message or null if valid.
*/
export function validateMaxQuantity( value ) {
if ( parseInt( value, 10 ) > MAX_QUANTITY ) {
return sprintf(
/* translators: %d: the largest maximum quantity allowed */
__( 'Maximum quantity must be %d or less.', 'jetpack-paypal-payments' ),
MAX_QUANTITY
);
}
return null;
}
/**
* Whether a value the merchant had to fill in is missing.
*
* The sign comes off the string as well: `parseFloat( '-0' )` is `-0`, and `-0 < 0`
* is false.
*
* @param {string} value - The rate, amount or fee.
* @return {boolean} True when there is nothing usable in the field.
*/
function isMissingAmount( value ) {
const num = parseFloat( value );
return isNaN( num ) || num < 0 || `${ value ?? '' }`.trim().startsWith( '-' );
}
/**
* Validate an amount of money a toggle asked the merchant for.
*
* Zero or more, with the decimals the currency allows. PayPal stores a zero fee, and
* the toggle is how a merchant skips one.
*
* @param {string} value - The amount.
* @param {string} currencyCode - The ISO currency code the amount is in.
* @return {string|null} Error message or null if valid.
*/
export function validateMoney( value, currencyCode = 'USD' ) {
if ( isMissingAmount( value ) ) {
return REQUIRED_FIELD_ERROR;
}
return getPriceFormatError( value, currencyCode );
}
/**
* Validate a percentage a toggle asked the merchant for.
*
* Under 100 with at most two decimals. PayPal returns a 422 either way, and the
* decimal limit is the same in every currency, so the value alone is enough to check.
*
* @param {string} value - The rate.
* @return {string|null} Error message or null if valid.
*/
export function validatePercentage( value ) {
if ( isMissingAmount( value ) ) {
return REQUIRED_FIELD_ERROR;
}
if ( parseFloat( value ) >= 100 ) {
return __( 'Rate must be less than 100%.', 'jetpack-paypal-payments' );
}
if ( ! /^\d+(\.\d{1,2})?$/.test( `${ value ?? '' }`.trim() ) ) {
return __( 'Rate can have at most 2 decimal places.', 'jetpack-paypal-payments' );
}
return null;
}
/**
* Validate a tax against the rule its own type carries.
*
* PERCENTAGE alone is a rate. Every other type draws a currency suffix in the editor
* and validates as money, matching `taxIsPercentage` there.
*
* @param {string} type - Tax type: PERCENTAGE or FLAT.
* @param {string} value - The rate or amount.
* @param {string} currencyCode - The ISO currency code a flat amount is in.
* @return {string|null} Error message or null if valid.
*/
function validateTax( type, value, currencyCode ) {
return 'PERCENTAGE' === ( type || 'PERCENTAGE' )
? validatePercentage( value )
: validateMoney( value, currencyCode );
}
/**
* Validate a percentage discount.
*
* Whole numbers 1 to 99. The check is on the string: PayPal rejects "1.0", which
* parseFloat reads as a valid 1.
*
* @param {string} value - The percentage off.
* @return {string|null} Error message or null if valid.
*/
export function validateDiscountPercentage( value ) {
const num = parseFloat( value );
if ( isNaN( num ) || num <= 0 ) {
return REQUIRED_FIELD_ERROR;
}
if ( ! /^\d+$/.test( `${ value ?? '' }`.trim() ) ) {
return __( 'Discount percentage must be a whole number.', 'jetpack-paypal-payments' );
}
if ( num > 99 ) {
return __( 'Discount must be between 1% and 99%.', 'jetpack-paypal-payments' );
}
return null;
}
/**
* Validate a flat discount against the price it comes off.
*
* Where there is a price to compare against, the amount has to come in under it -
* PayPal returns a 422 at or above.
*
* @param {string} value - The amount off.
* @param {string} comparisonPrice - The price it comes off, or '' when there is none.
* @param {string} currencyCode - The ISO currency code the amount is in.
* @return {string|null} Error message or null if valid.
*/
export function validateDiscountAmount( value, comparisonPrice, currencyCode = 'USD' ) {
const num = parseFloat( value );
// PayPal rejects a zero discount, "0" and "0.00" alike, so zero points at the toggle.
if ( isNaN( num ) || num <= 0 ) {
return REQUIRED_FIELD_ERROR;
}
const against = parseFloat( comparisonPrice );
if ( ! isNaN( against ) && num >= against ) {
return __( 'Discount must be less than the product price.', 'jetpack-paypal-payments' );
}
return getPriceFormatError( value, currencyCode );
}
/**
* Validate a discount against the rule its own type carries.
*
* A percentage checks a range and an amount checks against the price, so the type
* picks between the two here.
*
* @param {string} type - Discount type: FLAT or PERCENTAGE.
* @param {string} value - The amount or percentage off.
* @param {string} comparisonPrice - The price a flat discount comes off.
* @param {string} currencyCode - The ISO currency code the amount is in.
* @return {string|null} Error message or null if valid.
*/
function validateDiscount( type, value, comparisonPrice, currencyCode ) {
return 'PERCENTAGE' === type
? validateDiscountPercentage( value )
: validateDiscountAmount( value, comparisonPrice, currencyCode );
}
/**
* A PayPal URL rebuilt from its parsed parts, or '' for anything else.
*
* Mirrored server-side by `sanitize_paypal_script_url()`. `tests/fixtures/url-parity.json`
* pins both sides' output for every URL in it, including the rows where the two part
* company. This half takes `https:` and nothing else, because what comes out of it is
* injected as a script src inside wp-admin; the published page repairs the scheme instead,
* rather than dropping a button a merchant already has.
*
* Rebuilt rather than returned as given, because a URL is checked on its own and then
* used against the document it goes into: `https:www.paypal.com/../../x` parses to a
* PayPal host here, and resolves to the site's own origin once it is an href or a
* script src.
*
* `new URL()` does the parsing, so userinfo, backslashes, tabs, case and punycode
* follow the browser's rules rather than a second set of ours.
*
* @param {string} url - A URL from a block attribute.
* @return {string} The rebuilt PayPal URL, or '' for anything else.
*/
export function sanitizePayPalUrl( url ) {
let parsed;
try {
// No base, so a relative or scheme-relative string throws rather than picking up
// the editor's own origin.
parsed = new URL( url );
} catch {
return '';
}
const host = parsed.hostname.replace( /\.+$/, '' );
// `javascript://www.paypal.com/%0aalert(1)` parses with a PayPal hostname, so the
// protocol is checked as well as the host.
if ( 'https:' !== parsed.protocol || ! ALLOWED_PAYPAL_DOMAINS.includes( host ) ) {
return '';
}
// These URLs are block attributes read back out of post content, so an ampersand in
// the query can come back HTML-escaped. The PHP unescapes the query and leaves the
// rest alone, and this matches it: withPartnerAttribution() re-parses this output,
// where a surviving `&` would become a parameter named `amp;…`.
return `https://${ host }${ parsed.pathname }${ parsed.search.replace( /&/g, '&' ) }`;
}
/**
* Validate a return URL (optional field).
*
* Matches what the server accepts: an http or https URL with a host. Empty means the
* buyer is not redirected anywhere.
*
* @param {string} value - The return URL.
* @return {string|null} Error message or null if valid.
*/
export function validateReturnUrl( value ) {
if ( ! value ) {
return null;
}
if ( ! /^https?:\/\/[^/?#@\s]+(?:[/?#]\S*)?$/.test( value ) ) {
return __(
'Return URL must be a valid URL (e.g., https://example.com/thank-you).',
'jetpack-paypal-payments'
);
}
if ( value.length > MAX_RETURN_URL_LENGTH ) {
return sprintf(
/* translators: %d: maximum number of characters allowed for the return URL */
__( 'Return URL must be %d characters or fewer.', 'jetpack-paypal-payments' ),
MAX_RETURN_URL_LENGTH
);
}
return null;
}
/**
* Validate a currency code.
*
* The picker only offers codes PayPal takes, so a bad one arrived from a paste or
* an older block rather than from the merchant.
*
* @param {string} value - The ISO currency code.
* @return {string|null} Error message or null if valid.
*/
export function validateCurrency( value ) {
if ( ! value || VALID_CURRENCY_CODES.has( value ) ) {
return null;
}
return __( 'Unsupported currency.', 'jetpack-paypal-payments' );
}
/**
* Error keys whose control sits outside the Checkout Options panel.
*
* The panel opens itself on an error from one of its own fields. Listing the
* outsiders covers a new checkout field the moment its key exists.
*/
export const NON_CHECKOUT_ERROR_KEYS = [
'productName',
'price',
'productDescription',
'currencyCode',
'returnUrl',
];
/**
* The first error message, skipping the fields the caller excludes.
*
* @param {object} errors - Errors from getValidationErrors().
* @param {string[]} exclude - Keys to skip.
* @return {string|null} The message, or null when there is nothing to report.
*/
export function firstBlockingError( errors, exclude = [] ) {
const found = Object.entries( errors ).find(
( [ field, message ] ) => message && ! exclude.includes( field )
);
return found ? found[ 1 ] : null;
}
/**
* Whether an error belongs to a field inside the Checkout Options panel.
*
* @param {object} errors - Errors from getValidationErrors().
* @return {boolean} True when the panel should open itself.
*/
export function hasCheckoutOptionError( errors ) {
return null !== firstBlockingError( errors, NON_CHECKOUT_ERROR_KEYS );
}
/**
* Validate every form field at once.
*
* Two things consume each key: hasBlockingError() below, which disables the save
* button, and a control's `help` or the error row under a select, which tells the
* merchant what is wrong. A key that reaches only the first leaves a dead button
* and nothing on screen saying why. Adding a key here means adding what renders it.
*
* Return every key on every call, `null` where it does not apply - building the
* object conditionally would shrink the key set the tests enumerate, and the
* fence would go quiet with nothing failing.
*
* @param {object} fields - The form's current values.
* @param {string} fields.productName - Product name.
* @param {string} fields.price - Product price.
* @param {string} fields.productDescription - Product description.
* @param {string} fields.returnUrl - Post-payment redirect.
* @param {string} fields.currencyCode - ISO currency code.
* @param {boolean} fields.variantPricingOn - Whether options carry their own prices.
* @param {boolean} fields.taxEnabled - Whether tax collection is on.
* @param {string} fields.taxType - Tax type: PERCENTAGE, FLAT or PREFERENCE.
* @param {string} fields.taxValue - Tax rate or flat amount.
* @param {boolean} fields.handlingEnabled - Whether a handling fee is on.
* @param {string} fields.handlingValue - Handling fee amount.
* @param {boolean} fields.discountEnabled - Whether a discount is on.
* @param {string} fields.discountType - Discount type: FLAT or PERCENTAGE.
* @param {string} fields.discountValue - Discount amount or percentage.
* @param {string} fields.comparisonPrice - The price a flat discount comes off,
* from getComparisonPrice().
* @param {boolean} fields.shippingEnabled - Whether shipping is on.
* @param {string} fields.shippingMode - PROFILE, QUANTITY, FLAT or FREE.
* @param {string} fields.shippingValue - Shipping fee, or the first-item fee.
* @param {string} fields.shippingAdditionalValue
* - The per-extra-item fee. Optional.
* @param {boolean} fields.collectShippingAddress - Whether checkout asks for the address.
* @param {boolean} fields.adjustableQuantity - Whether buyers pick a quantity.
* @param {number} fields.maxQuantity - The most a buyer can pick.
* @return {object} An error message or null, keyed by field.
*/
export function getValidationErrors( {
productName,
price,
productDescription,
returnUrl,
currencyCode,
variantPricingOn,
taxEnabled,
taxType,
taxValue,
handlingEnabled,
handlingValue,
discountEnabled,
discountType,
discountValue,
comparisonPrice,
shippingEnabled,
shippingMode,
shippingValue,
shippingAdditionalValue,
collectShippingAddress,
adjustableQuantity,
maxQuantity,
} ) {
const currency = currencyCode || 'USD';
return {
productName: validateProductName( productName ),
// The price field is hidden once per-variant pricing is on, so don't validate
// it - an error on an invisible field would disable Save with nothing to fix.
price: variantPricingOn ? null : validatePrice( price, currency ),
productDescription: validateDescription( productDescription ),
returnUrl: validateReturnUrl( returnUrl ),
// PREFERENCE takes its rate from the merchant's PayPal profile.
taxValue:
taxEnabled && 'PREFERENCE' !== taxType ? validateTax( taxType, taxValue, currency ) : null,
taxType:
taxEnabled && 'PREFERENCE' === taxType && ! collectShippingAddress
? ADDRESS_REQUIRED_ERROR
: null,
handlingValue: handlingEnabled ? validateMoney( handlingValue, currency ) : null,
discountValue: discountEnabled
? validateDiscount( discountType, discountValue, comparisonPrice, currency )
: null,
// PROFILE and FREE send their own value, so only the fee modes have a field to fill.
shippingValue:
shippingEnabled && SHIPPING_MODES_WITH_FEE.includes( shippingMode || 'FLAT' )
? validateMoney( shippingValue, currency )
: null,
// PayPal requires only the first fee, so this is checked when it is filled in.
shippingAdditionalValue:
shippingEnabled && 'QUANTITY' === shippingMode && '' !== ( shippingAdditionalValue ?? '' )
? validateMoney( shippingAdditionalValue, currency )
: null,
shippingMode:
shippingEnabled && 'PROFILE' === shippingMode && ! collectShippingAddress
? ADDRESS_REQUIRED_ERROR
: null,
// The field shows only with the toggle on.
maxQuantity: adjustableQuantity ? validateMaxQuantity( maxQuantity ) : null,
currencyCode: validateCurrency( currencyCode ),
};
}
/**
* Whether any field has an error. Any error blocks the save.
*
* Derived rather than a hand-written list of fields, so a new key cannot be
* forgotten on the gate side.
*
* @param {object} errors - Errors from getValidationErrors().
* @return {boolean} True when a field has an error.
*/
export function hasBlockingError( errors ) {
return null !== firstBlockingError( errors );
}
/**
* Map an API error response to a user-friendly message.
*
* The server-side already returns user-friendly messages, but this
* provides client-side fallbacks for network errors and edge cases.
*
* @param {object} err - The error object from apiFetch.
* @return {string} User-friendly error message.
*/
export function getUserFriendlyError( err ) {
// Server already provides friendly messages — use them.
if ( err.message ) {
return err.message;
}
// Network-level errors (no response from server).
if ( err.code === 'fetch_error' ) {
return __(
'Could not reach the server. Please check your internet connection and try again.',
'jetpack-paypal-payments'
);
}
return __( 'An unexpected error occurred. Please try again.', 'jetpack-paypal-payments' );
}
/**
* Whether an API error says the payment no longer exists at PayPal.
*
* @param {object} err - The apiFetch error.
* @return {boolean} True for a 404.
*/
export function isNotFound( err ) {
return err?.code === 'paypal_api_resource_not_found' || err?.data?.status === 404;
}
/**
* Whether an API error says this user may not manage PayPal on the site.
*
* A stale nonce is a 403 too, but that is the tab's problem, not the user's role.
*
* @param {object} err - The apiFetch error.
* @return {boolean} True for a 403 other than a stale nonce.
*/
export function isForbidden( err ) {
return err?.data?.status === 403 && err?.code !== 'rest_cookie_invalid_nonce';
}
|