=== SutraPay for PayPal ===
Contributors: fresheradvice
Tags: paypal, paylater, venmo, credit cards, woocommerce
Requires at least: 6.4
Requires PHP: 8.0
Tested up to: 7.1
Stable tag: 0.10.0
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

Accept PayPal, Venmo, Pay Later, Apple Pay, Google Pay, and credit/debit cards in WooCommerce via PayPal's official REST API.

== Description ==
SutraPay for PayPal lets customers pay with PayPal, Venmo, Pay Later, Apple Pay, Google Pay, and
credit/debit cards, using PayPal's official REST APIs and PayPal's JavaScript SDK v6 (no bundled third-party SDK).

= Features =
* PayPal, Venmo, Pay Later and PayPal Credit buttons (PayPal JavaScript SDK v6) on the product, cart, checkout, and mini-cart
* Pay Later installment messaging
* Advanced Credit and Debit Card Payments (hosted card fields) with 3-D Secure
* Apple Pay and Google Pay at checkout
* Saved payment methods (PayPal Vault) for PayPal accounts and cards, under My Account -> Payment methods, at checkout and on the order Pay page
* Subscription renewals charged automatically with the saved method: WooCommerce Subscriptions, and any subscription plugin that uses the same renewal hook
* Webhook listener to keep orders in sync with PayPal-side events
* HPOS (custom order tables) compatible

= Subscriptions =
Your subscription plugin decides when a renewal is due and what it costs -- including a renewal coupon or a changed price -- and this plugin charges each renewal order with the customer's saved PayPal account or card, while the customer is away. A renewal that needs the customer (their bank asks for 3-D Secure) fails with a clear note and can be paid by the customer from the order's Pay page, where the saved methods are offered too.

The plugin works with WooCommerce Subscriptions and with other subscription plugins that fire the standard `woocommerce_scheduled_subscription_payment_{gateway}` action. Results are announced with `sutrapay_paypal_renewal_payment_result`, `sutrapay_paypal_renewal_requires_authentication`, `sutrapay_paypal_renewal_paid_by_customer` and `sutrapay_paypal_payment_method_saved`.

If your PayPal account cannot save payment methods, a subscription sold through the `sutrapay_paypal_recurring_plan` filter is created as a PayPal-run subscription instead, which PayPal bills by itself at the plan's price.

== Installation ==
1. Upload the plugin to `/wp-content/plugins/`.
2. Activate it through the 'Plugins' menu in WordPress.
3. Go to SutraPay for PayPal -> General and connect your PayPal REST API credentials.

== Frequently Asked Questions ==

= Why are renewals not charged? =
Saving payment methods has to be allowed for your PayPal REST app: in the PayPal developer dashboard open the app, turn on "Save payment methods" (and "Advanced Credit and Debit Card Payments" for cards), then click "Test connection" on the General tab. The Saved Payment Methods tab shows whether your account can save methods.

= Can customers add a PayPal account without buying anything? =
Yes: My Account -> Payment methods -> Add payment method takes them to PayPal to approve saving their account; nothing is charged. Cards are saved together with a payment.

= Do subscriptions created by an earlier version keep working? =
Yes. Subscriptions already running at PayPal keep billing and syncing by webhook until they end.

== External Services ==

This plugin connects to PayPal, which is required for it to work. No data is sent until a payment method is configured and a customer starts a PayPal, Venmo, Pay Later, Apple Pay, Google Pay or card payment (or an administrator uses the connection test, webhook or refund tools).

1. PayPal REST API
* Service URLs: https://api-m.paypal.com (live) and https://api-m.sandbox.paypal.com (sandbox)
* Purpose: authenticating with your REST credentials, creating, authorizing, capturing and refunding orders, saving payment methods (Vault), registering and verifying webhooks, and billing subscription renewals.
* Data sent: your REST client ID and secret (for authentication), the order amount, currency, line items, order number, the customer's billing and shipping name, address, e-mail address and phone number, the site's return/cancel URLs, and PayPal payment tokens for saved payment methods.
* When: when a customer pays, when an administrator connects or tests the account, refunds an order or registers a webhook, and when a renewal is charged.

2. PayPal JavaScript SDK v6 and hosted card fields
* Service URLs: https://www.paypal.com/web-sdk/v6/core (live) and https://www.sandbox.paypal.com/web-sdk/v6/core (sandbox), loaded on product, cart and checkout pages when a PayPal method is enabled
* Purpose: renders the PayPal, Venmo, Pay Later and PayPal Credit buttons, Pay Later messages, the Apple Pay / Google Pay payment sessions and the hosted card-number, expiry and CVV fields (with 3-D Secure). Card details are entered into fields hosted by PayPal and never reach your server.
* Data sent: your REST client ID (public), the page type, currency and amount (to check which payment methods are available and for Pay Later messages); the visitor's IP address, browser information and cookies are sent to PayPal by the SDK, as with any PayPal script.

3. Google Pay
* Service URL: https://pay.google.com/gp/p/js/pay.js (loaded on the checkout page only when Google Pay is enabled on the Apple Pay / Google Pay screen)
* Purpose: shows the Google Pay button and payment sheet; the payment itself is confirmed with PayPal.
* Data sent: the visitor's IP address and browser information are sent to Google by the script; the store's country, currency and order total are passed to the Google Pay sheet when the shopper uses it.
* Google Pay terms: https://payments.developers.google.com/terms/sellertos -- Privacy: https://policies.google.com/privacy

4. Apple Pay
* Uses Safari's built-in Apple Pay (no script is loaded). When Apple Pay is enabled, the domain-association file you add on the Apple Pay / Google Pay screen is served at /.well-known/apple-developer-merchantid-domain-association so Apple can verify your domain.
* Apple Pay terms: https://www.apple.com/legal/applepayments/ -- Privacy: https://www.apple.com/legal/privacy/

5. Webhooks (incoming)
* PayPal sends event notifications to the webhook URL shown in the plugin settings; the plugin verifies each event's signature with PayPal (service URL above) before acting on it.

Terms of Service: https://www.paypal.com/legalhub/useragreement-full
Privacy Policy: https://www.paypal.com/legalhub/privacy-full

== Changelog ==
= 0.10.0 =
* Changed: every internal name (code, settings, gateway id, webhook address, styles, scripts) is now sutrapay_paypal; earlier builds used flexwoopaypal.

= 0.9.0 =
* Changed: the plugin is now called SutraPay for PayPal and lives in the sutrapay-for-paypal folder. Settings, webhooks and saved payment methods are kept; a copy in the previous folder (flex-paypal-payments) is switched off and can be removed with one button.
* Changed: updates come through WordPress's Updates screen when MemberSutra (website download) or MemberSutra Pro for WooCommerce is active.

= 0.8.4 =
* Changed: renamed to Flex PayPal Payments (formerly MemberSutra). The plugin now lives in the flex-paypal-payments folder (text domain flex-paypal-payments). Installing this version next to the old flexwoo-paypal-payments copy switches the old copy off and keeps all settings and data; a notice then offers to remove the old copy safely.
= 0.8.3 =
* Maintenance: released with MemberSutra 1.43.3; no code changes since 0.8.2.

= 0.8.2 =
* Changed: the plugin's home page and author links point to https://sutraplugins.com.
* Security: the settings screen's JSON and the checkout error reports are sanitized as they are decoded.

= 0.8.1 =
* Security: the General tab no longer writes the PayPal Client Secrets into the page. The fields show a mask with the last 4 characters; leave it unchanged to keep the saved secret, or type a new one to replace it.
* Changed: the admin menu and main page are named "SutraPay for PayPal" (was "PayPal Payments by MemberSutra"), matching the plugin name.

= 0.8.0 =
* Changed: the plugin is now named SutraPay for PayPal, like the other MemberSutra plugins. The folder, slug and text domain stay sutrapay-paypal-payments, so updating replaces the installed copy and settings are kept.
* Maintenance release: production-readiness review with MemberSutra 1.41.0 (Plugin Check clean, full regression including PayPal sandbox subscriptions). Its scheduled cleanup job is listed under MemberSutra > Tools > Cron Jobs. No functional changes.

= 0.7.0 =
* Added: a subscription plugin can ask for its plan to be sold as a PayPal-run subscription even when the payment method could be saved ('paypal_billing'), and can describe one discounted run of renewals after the first payment ('discount'). The discount becomes the plan's second trial cycle.
* Added: filters to read, cancel, suspend and re-activate a PayPal-run subscription (sutrapay_paypal_billing_subscription_get, _cancel, _suspend, _activate).
* Added: the plan filter (sutrapay_paypal_recurring_plan) receives the order being paid, so the plan can depend on its coupons.
* Fixed: a plan limited to a number of payments without a trial billed one payment too many. total_cycles now counts every payment, the first included. Billing plans are re-created once for new subscriptions; running subscriptions keep their plans.

= 0.6.0 =
* Changed: the storefront runs on PayPal's JavaScript SDK v6 (v5 is deprecated by PayPal). The SDK is started with `paypal.createInstance()` and the components each page needs, payment methods are checked with `findEligibleMethods()`, the buttons are PayPal's web components (`<paypal-button>`, `<venmo-button>`, `<paypal-pay-later-button>`, `<paypal-credit-button>`) started through payment sessions, Pay Later messages use `<paypal-messages>`, and the hosted card fields use the v6 card fields session. Sandbox credentials load PayPal's sandbox SDK.
* Added: Google Pay and Apple Pay at checkout through the v6 sessions. Both are off by default: turn them on once the wallet is enabled on your PayPal account; Apple Pay also needs the domain-association file from PayPal's dashboard, which is pasted on the Apple Pay / Google Pay screen and served for Apple. (Before, they could be switched on but no button was ever shown.)
* Added: Pay Later messages on the checkout page ("Show on checkout page" had no effect), and PayPal Credit as a button.
* Fixed: the Cards "3D Secure" setting was not applied. Card orders now ask for 3-D Secure always / when required, and an approved card payment is only captured when its 3-D Secure result allows it (a failed or unknown authentication is refused and nothing is charged).
* Changed: button settings follow v6: colours gold, blue or white (silver is shown as white, black as blue), labels "Pay with PayPal", "PayPal Checkout" or "PayPal Buy Now"; the Pay Later message style is now a logo and text colour choice. The "Credit/Debit Card button" funding option is gone (cards are paid in the card fields).
* Changed: a purchase that renews automatically is only offered the PayPal button, the card fields and saved methods (Venmo, Pay Later, Credit and the wallets cannot be saved for renewals).
* Changed: orders built for a PayPal redirect use `payment_source.paypal.experience_context` instead of the deprecated `application_context`.

= 0.5.0 =
* Added: saved payment methods (PayPal Vault v3) for PayPal accounts and cards. A subscription always saves the method it is paid with; for other purchases customers can tick "Save this payment method". Saved methods are offered at checkout (classic and block) and on the order Pay page.
* Added: subscription renewals are charged off-session with the saved method through `woocommerce_scheduled_subscription_payment_{gateway}` for any subscription engine (WooCommerce Subscriptions, MemberSutra ...), with the outcome written on the order and announced by `sutrapay_paypal_renewal_payment_result`. A renewal PayPal holds for review waits On hold for the webhook; a renewal that needs the customer fails with a note and can be paid from its Pay page.
* Added: the order Pay page (a failed renewal, an invoice) can be paid with the PayPal buttons, the card fields or a saved method; a 3-D Secure challenge takes the customer to PayPal and back.
* Added: My Account -> Add payment method saves a PayPal account (approved at PayPal, nothing charged); a free trial saves the PayPal account the same way at checkout. Cards are saved together with a payment, so the card gateway is not offered on that page.
* Added: My Account -> Payment methods names saved methods ("PayPal (email)", "Visa ending in 1111") instead of "N/A".
* Added: WooCommerce Subscriptions: the saved method per subscription (editable by the admin), payment method changes after a failed renewal, and moving subscriptions to another saved method when one is deleted.
* Added: the Saved Payment Methods tab shows whether your PayPal account can save payment methods; "Test connection" checks it.
* Changed: a recurring plan described by the `sutrapay_paypal_recurring_plan` filter is bought with a saved method and renewed by the site; it is only sold as a PayPal-run subscription when the method cannot be saved. Existing PayPal-run subscriptions are unchanged.
* Fixed: express checkout (product, cart and mini-cart buttons) now builds the order like WooCommerce's checkout -- cart coupons, fees, shipping and taxes are kept, so a cart with a coupon no longer fails the amount check -- attaches the logged-in customer and fills the buyer's e-mail and address from PayPal when none was typed.
* Fixed: card payments were recorded as the PayPal gateway instead of the card gateway.
* Fixed: a capture PayPal holds for review (PENDING) marked the order paid; it now waits On hold for PayPal's decision.
* Fixed: capture webhooks for orders paid with the buttons could not find their order; a partial refund at PayPal marked the whole order Refunded.
* Removed: the "retry failed renewals" settings, which did nothing -- the subscription plugin owns retries.
= 0.4.10 =
* Security: the webhook event-ledger cleanup no longer instantiates objects from stored values (`allowed_classes` disabled).
* Verified against the PayPal sandbox: OAuth handshake, order creation and read-back, refusal of a capture the buyer has not approved, forged-signature rejection, webhook registration.
* Fixed: the card fields never rendered on the classic checkout (rendered once into a hidden panel and never retried); they now render when visible, retry on failure and re-render after a checkout refresh. Cross-origin "Script error." events are no longer logged as plugin errors.
* Fixed: settings saves accepted any value; every field is now validated (allowed lists, integer ranges) and an invalid save is refused with a message.
* Fixed: the Logs screen used WooCommerce log helpers deprecated since 8.6.
* Added: "External services" disclosure in readme.txt. `WC tested up to` 11.1.1.

= 0.4.9 =
* Maintenance and stability release: verified webhook listener security, vault tokens, and compatibility with MemberSutra 1.35.2.

= 0.4.8 =
* Maintenance and stability release: comprehensive end-to-end payment and subscription lifecycle testing and verification.

= 0.4.3 =
* Added: the webhook listener now subscribes to PayPal's subscription-lifecycle events (BILLING.SUBSCRIPTION.CREATED/ACTIVATED/UPDATED/EXPIRED/CANCELLED/SUSPENDED, PAYMENT.SALE.COMPLETED, PAYMENT.SUBSCRIPTION.PAYMENT.FAILED) and dispatches a new `sutrapay_paypal_webhook_received` action for every processed webhook event, so other plugins (e.g. MemberSutra) can react to PayPal-side subscription changes that don't originate from a WooCommerce order/checkout flow.

= 0.4.2 =
* Maintenance update and compatibility verification for WooCommerce 9.0+ and WordPress 6.7+.

= 0.4.1 =
* Version bump; no functional changes since 0.4.0.

= 0.4.0 =
* Renamed: plugin is now "SutraPay for PayPal for WooCommerce"; all internal identifiers (namespace, constants, option/transient/meta keys, AJAX actions, REST namespace, CSS classes, JS globals) moved from the flexpay/fpay prefix to sutrapay_paypal.
* Security: classic checkout no longer trusts the browser-submitted PayPal order id at face value — it is now verified to match this order's exact amount and currency before capture, and rejected if the same PayPal order id was already used to pay a different order. This closes a payment-amount-manipulation gap where a low-value approved PayPal order could otherwise be submitted against a higher-value WooCommerce order.
* Security: webhook events are now claimed atomically (an idempotency ledger, safe under concurrent/duplicate deliveries) so a redelivered or replayed event can never be applied twice; a daily cleanup job prunes the ledger.
* Security: webhook capture-completed events are cross-checked against the order's actual amount/currency before the order is marked paid.
* Security: webhook request bodies above a sane size are now rejected before parsing.
* Security: added per-visitor rate limiting to the order-create/order-approve AJAX endpoints.
* Security: the Checkout block's gateway description now runs through wp_kses_post() server-side before being sent to the client, rather than relying solely on settings-save sanitization.
* Fix: the classic and express checkout flows now consistently record the PayPal order id on the WooCommerce order, which is what lets a PayPal webhook (delayed capture, dispute, refund from the PayPal dashboard) find and update the right order — previously this only worked for orders reached via a code path that isn't used by the live checkout flows.
* Added: uninstall.php cleans up this plugin's options/transients when deleted from the Plugins screen.

= 0.3.2 =
* Fix: admin CSS/JS were only loading on the General settings tab — every other tab (Smart Buttons, Pay Later, Card Fields, etc.) was rendering completely unstyled. Root cause: WordPress builds each submenu's hook suffix as `toplevel_page_{that page's own slug}` under a custom top-level menu, not `{parent_slug}_page_{slug}` — the asset-loading check was matching against the wrong substring.
* Fix: our own in-page sidebar's "General" link pointed to an unregistered page slug (a leftover from an earlier constant rename), which would 404/blank out if clicked from another tab.

= 0.3.1 =
* Fixed all issues reported by the WordPress Plugin Check tool: text domain now matches the plugin slug (sutrapay-paypal-payments) throughout; removed discouraged load_plugin_textdomain() call; prefixed all template-local variables per naming conventions; addressed nonce/sanitization/escaping sniff findings; replaced readfile() with WP_Filesystem; added missing translators comment; corrected readme.txt "Tested up to" format and added a short description.

= 0.3.0 =
* Added: checkout field validation (billing/shipping required fields, email format, postcode format, terms-and-conditions) for the express Smart Buttons / Card Fields flow, both client-side (fast feedback, no wasted PayPal popup) and server-side (authoritative). Previously this flow bypassed WooCommerce's own checkout validation entirely and created orders with no customer details attached.

= 0.2.0 =
* Security: webhook endpoint now rejects any event it can't cryptographically verify against a registered webhook id, instead of accepting it unverified (previously, an unregistered webhook would fail open).
* Security: product/cart express-checkout AJAX flow now re-validates stock and purchasability before charging, and after charging but before fulfillment.
* Security: capped log entry size and added basic rate limiting on the client-error reporting endpoint.
* Fix: PayPal order capture/authorize calls no longer send a malformed empty-array JSON body (was causing MALFORMED_REQUEST_JSON errors on every capture).
* Fix: removed a leftover filter that nulled out every customer's saved payment tokens site-wide.
* Fix: Smart Buttons and Card Fields now register with the WooCommerce Checkout/Cart *blocks*, not just the classic shortcode checkout.
* Added: PayPal-official currency support checks and India domestic-payment compliance detection, enforced at checkout (not just a warning).
* Added: in-plugin Logs screen (SutraPay for PayPal -> Logs) with database-backed storage, so failures are visible without server file access.
* Added: client-side (JS) error reporting into the same log.

= 0.1.0 =
* Initial release.

== Upgrade Notice ==
= 0.10.0 =
First build under the SutraPay code names. Not an update from older builds: settings, orders and webhooks made with an earlier version are not carried over. Install on a new site (or start fresh) and connect the payment provider again.

= 0.9.0 =
Renamed to SutraPay for PayPal (new folder; settings are kept). No functional change.

= 0.8.4 =
Renamed to Flex PayPal Payments in a new folder (flex-paypal-payments). Settings and data are kept; remove the old copy with the button in the notice.

= 0.8.3 =
Maintenance release, no code changes.

= 0.8.2 =
WordPress.org review hardening. No functional changes.

= 0.8.1 =
Security hardening: the Client Secrets are masked on the settings page. Your saved credentials are kept.

= 0.8.0 =
Maintenance release, no functional changes.

= 0.7.0 =
Lets subscription plugins have PayPal run their subscriptions, with renewal discounts, and fixes a payment count. Running subscriptions are unchanged. No database changes.

= 0.6.0 =
Moves the storefront to PayPal's JavaScript SDK v6. Check your button style on the PayPal buttons screen. Apple Pay and Google Pay are now off until you set them up on the Apple Pay / Google Pay screen.

= 0.5.0 =
Saved payment methods and site-charged subscription renewals. After updating, click "Register webhook" once (Advanced tab) and "Test connection" (General tab).

= 0.4.10 =
No database changes.
