[ReviewReady] Rest API endpoint framework for WP-local APIs#2928
[ReviewReady] Rest API endpoint framework for WP-local APIs#2928
Conversation
|
@sol-loup has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator. |
|
@sol-loup has updated the pull request. You must reimport the pull request before landing. |
a0d9cef to
8f71033
Compare
|
@sol-loup has updated the pull request. You must reimport the pull request before landing. |
2 similar comments
|
@sol-loup has updated the pull request. You must reimport the pull request before landing. |
|
@sol-loup has updated the pull request. You must reimport the pull request before landing. |
|
@sol-loup has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator. |
|
@sol-loup has updated the pull request. You must reimport the pull request before landing. |
|
@sol-loup has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator. |
Remove duplicate CSS cleaning up MetaExtension unused functions Updating tests Fix PHPCS Complaints remaining phpcs fixes removing comment
832e866 to
d06adef
Compare
|
@sol-loup has updated the pull request. You must reimport the pull request before landing. |
|
@sol-loup has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator. |
|
@sol-loup has updated the pull request. You must reimport the pull request before landing. |
|
@sol-loup has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator. |
|
@sol-loup has updated the pull request. You must reimport the pull request before landing. |
|
@sol-loup has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator. |
|
@sol-loup has updated the pull request. You must reimport the pull request before landing. |
|
@sol-loup has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator. |
|
@sol-loup has updated the pull request. You must reimport the pull request before landing. |
|
@sol-loup has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator. |
|
@sol-loup has updated the pull request. You must reimport the pull request before landing. |
|
@sol-loup has updated the pull request. You must reimport the pull request before landing. |
|
@sol-loup has imported this pull request. If you are a Meta employee, you can view this diff on Phabricator. |
Summary: # Add REST API Framework for local APIs called by AJAX ## Changes proposed in this Pull Request: - Introduces a comprehensive REST API framework for Facebook for WooCommerce - Migrates existing API functionality to the new structured system - Improves security with proper nonce handling and request validation - Adds JavaScript integration for secure client-side API calls - Provides extensive documentation for future development Closes facebook#2345 (Replace with actual issue number if applicable) ## Description This PR introduces a new REST API framework for Facebook for WooCommerce that provides a structured, secure, and extensible way to handle API requests between the WordPress admin and Facebook services. The previous implementation used ad-hoc REST endpoints with inconsistent validation and error handling. This new framework standardizes how we define endpoints, validate requests, and expose functionality to JavaScript, making the codebase more maintainable and secure. ### Key Components 1. **Controller** (`includes/API/REST/Controller.php`): - Central registry for all REST API endpoints - Manages endpoint registration and initialization - Maintains constants for endpoint handlers and JS-enabled requests 2. **AbstractRESTEndpoint** (`includes/API/REST/AbstractRESTEndpoint.php`): - Base class for all endpoint handlers - Provides common functionality for permission checks and response formatting - Handles JS API definitions generation 3. **Request** (`includes/API/REST/Request.php`): - Base class for request validation and parameter handling - Sanitizes and validates all incoming data - Provides structured access to request parameters 4. **JS_Exposable** (`includes/API/REST/Traits/JS_Exposable.php`): - Trait for exposing endpoints to JavaScript - Defines interface for JS API integration - Generates API definitions for client-side consumption 5. **InitializeRestAPI** (`includes/API/REST/InitializeRestAPI.php`): - Initializes the REST API framework - Generates JavaScript API definitions - Handles script enqueuing and localization ### Security Improvements The new framework significantly improves security: - Nonces are no longer exposed globally in JavaScript - Each page that needs API access creates its own API client with a fresh nonce - All request parameters are properly validated and sanitized - Structured error handling prevents leaking sensitive information - Clear separation between public and private endpoints ### Migration Strategy We've migrated the existing functionality from `MetaExtension` to the new framework: - Settings update endpoint (`/settings/update`) - Uninstall endpoint (`/settings/uninstall`) The Connection screen has been updated to use the new API framework, ensuring backward compatibility while leveraging the improved architecture. ## Do the changed files pass phpcs checks? Yes, all new and modified files pass phpcs checks. No phpcs:ignore comments were added. ## Screenshots [Validating old functionality is not broken]   ## Detailed test instructions ### 1. Basic Functionality 1. Install and activate the plugin 2. Go to WooCommerce > Facebook 3. Verify the connection page loads correctly with no JavaScript errors 4. Check browser console for any errors related to API initialization ### 2. Legacy Connection Flow 1. If not connected, click "Get Started" 2. Complete the Facebook connection flow 3. Verify you're redirected back to WooCommerce and connection is established 4. Check that catalog ID, pixel ID, and other settings are properly saved 5. Verify the connection details are displayed correctly on the settings page ### 3. Enhanced Onboarding 1. Connect to Facebook using the enhanced onboarding flow 2. Verify the iframe splash page loads correctly and displays the Facebook onboarding interface 3. Complete the connection process through the iframe 4. Verify the connection to MICE is established and settings are saved correctly 5. Check that the iframe resizes properly when content changes ### 4. Disconnection Flow 1. With an active connection, click "Disconnect" 2. Confirm the disconnection in the confirmation dialog 3. Verify all Facebook integration settings are cleared 4. Verify the connection page returns to the unconnected state 5. Verify you can reconnect successfully after disconnection ### 5. JavaScript API Testing 1. Open browser developer tools (F12) 2. Go to Console tab 3. Test API client creation: ```javascript // Get a fresh nonce (you'll need to be on the settings page) const nonce = wp_create_nonce('wp_rest'); // Create API client const fbAPI = FacebookWooCommerceAPIFactory(nonce); // Examine available methods console.log(Object.keys(fbAPI)); ``` 4. Test uninstall endpoint (only if you're willing to disconnect): ```javascript fbAPI.uninstallSettings() .then(response => console.log('Success:', response)) .catch(error => console.error('Error:', error)); ``` 5. Verify the page reloads and connection is removed ### 6. Error Handling 1. Test invalid API calls to verify error handling: ```javascript // Missing required parameters fbAPI.updateSettings({}) .then(response => console.log('Success:', response)) .catch(error => console.log('Error correctly caught:', error)); ``` 2. Verify appropriate error messages are displayed ## Additional details - The framework is designed to be extensible, making it easy to add new endpoints in the future - Comprehensive documentation on new endpoint process is provided in `includes/API/REST/README.md` Pull Request resolved: facebook#2928 Test Plan: Imported from GitHub, without a `Test Plan:` line. **!---- (auto-generated) DO NOT EDIT OR PUT ANYTHING AFTER THIS LINE ----!** MFTRunTestsScript Run / Test Suite: sa_checkout / Test Collection: www / Diff Version V9 https://internalfb.com/intern/testinfra/testrun/9570149282153152 MFTRunTestsScript Run / Test Suite: sa_checkout / Test Collection: bloks / Diff Version V9 https://internalfb.com/intern/testinfra/testrun/1970325111022726 Reviewed By: vinkmeta Differential Revision: D70733325 Pulled By: sol-loup fbshipit-source-id: f2275644ac6447d3940294d916020f1a484ca92e
Summary: # Add REST API Framework for local APIs called by AJAX ## Changes proposed in this Pull Request: - Introduces a comprehensive REST API framework for Facebook for WooCommerce - Migrates existing API functionality to the new structured system - Improves security with proper nonce handling and request validation - Adds JavaScript integration for secure client-side API calls - Provides extensive documentation for future development Closes #2345 (Replace with actual issue number if applicable) ## Description This PR introduces a new REST API framework for Facebook for WooCommerce that provides a structured, secure, and extensible way to handle API requests between the WordPress admin and Facebook services. The previous implementation used ad-hoc REST endpoints with inconsistent validation and error handling. This new framework standardizes how we define endpoints, validate requests, and expose functionality to JavaScript, making the codebase more maintainable and secure. ### Key Components 1. **Controller** (`includes/API/REST/Controller.php`): - Central registry for all REST API endpoints - Manages endpoint registration and initialization - Maintains constants for endpoint handlers and JS-enabled requests 2. **AbstractRESTEndpoint** (`includes/API/REST/AbstractRESTEndpoint.php`): - Base class for all endpoint handlers - Provides common functionality for permission checks and response formatting - Handles JS API definitions generation 3. **Request** (`includes/API/REST/Request.php`): - Base class for request validation and parameter handling - Sanitizes and validates all incoming data - Provides structured access to request parameters 4. **JS_Exposable** (`includes/API/REST/Traits/JS_Exposable.php`): - Trait for exposing endpoints to JavaScript - Defines interface for JS API integration - Generates API definitions for client-side consumption 5. **InitializeRestAPI** (`includes/API/REST/InitializeRestAPI.php`): - Initializes the REST API framework - Generates JavaScript API definitions - Handles script enqueuing and localization ### Security Improvements The new framework significantly improves security: - Nonces are no longer exposed globally in JavaScript - Each page that needs API access creates its own API client with a fresh nonce - All request parameters are properly validated and sanitized - Structured error handling prevents leaking sensitive information - Clear separation between public and private endpoints ### Migration Strategy We've migrated the existing functionality from `MetaExtension` to the new framework: - Settings update endpoint (`/settings/update`) - Uninstall endpoint (`/settings/uninstall`) The Connection screen has been updated to use the new API framework, ensuring backward compatibility while leveraging the improved architecture. ## Do the changed files pass phpcs checks? Yes, all new and modified files pass phpcs checks. No phpcs:ignore comments were added. ## Screenshots [Validating old functionality is not broken]   ## Detailed test instructions ### 1. Basic Functionality 1. Install and activate the plugin 2. Go to WooCommerce > Facebook 3. Verify the connection page loads correctly with no JavaScript errors 4. Check browser console for any errors related to API initialization ### 2. Legacy Connection Flow 1. If not connected, click "Get Started" 2. Complete the Facebook connection flow 3. Verify you're redirected back to WooCommerce and connection is established 4. Check that catalog ID, pixel ID, and other settings are properly saved 5. Verify the connection details are displayed correctly on the settings page ### 3. Enhanced Onboarding 1. Connect to Facebook using the enhanced onboarding flow 2. Verify the iframe splash page loads correctly and displays the Facebook onboarding interface 3. Complete the connection process through the iframe 4. Verify the connection to MICE is established and settings are saved correctly 5. Check that the iframe resizes properly when content changes ### 4. Disconnection Flow 1. With an active connection, click "Disconnect" 2. Confirm the disconnection in the confirmation dialog 3. Verify all Facebook integration settings are cleared 4. Verify the connection page returns to the unconnected state 5. Verify you can reconnect successfully after disconnection ### 5. JavaScript API Testing 1. Open browser developer tools (F12) 2. Go to Console tab 3. Test API client creation: ```javascript // Get a fresh nonce (you'll need to be on the settings page) const nonce = wp_create_nonce('wp_rest'); // Create API client const fbAPI = FacebookWooCommerceAPIFactory(nonce); // Examine available methods console.log(Object.keys(fbAPI)); ``` 4. Test uninstall endpoint (only if you're willing to disconnect): ```javascript fbAPI.uninstallSettings() .then(response => console.log('Success:', response)) .catch(error => console.error('Error:', error)); ``` 5. Verify the page reloads and connection is removed ### 6. Error Handling 1. Test invalid API calls to verify error handling: ```javascript // Missing required parameters fbAPI.updateSettings({}) .then(response => console.log('Success:', response)) .catch(error => console.log('Error correctly caught:', error)); ``` 2. Verify appropriate error messages are displayed ## Additional details - The framework is designed to be extensible, making it easy to add new endpoints in the future - Comprehensive documentation on new endpoint process is provided in `includes/API/REST/README.md` Pull Request resolved: #2928 Test Plan: Imported from GitHub, without a `Test Plan:` line. **!---- (auto-generated) DO NOT EDIT OR PUT ANYTHING AFTER THIS LINE ----!** MFTRunTestsScript Run / Test Suite: sa_checkout / Test Collection: www / Diff Version V9 https://internalfb.com/intern/testinfra/testrun/9570149282153152 MFTRunTestsScript Run / Test Suite: sa_checkout / Test Collection: bloks / Diff Version V9 https://internalfb.com/intern/testinfra/testrun/1970325111022726 Reviewed By: vinkmeta Differential Revision: D70733325 Pulled By: sol-loup fbshipit-source-id: f2275644ac6447d3940294d916020f1a484ca92e
Summary: = 3.5.0 - 2025-05-28 = * Add - Create basic checkout permalink w/ products and coupon support by ajello-meta in #2887 * Add - Common Feed Upload Framework by Jmencab in #2875 * Fix - Fix bug where templates were not loading correctly by ajello-meta in #2915 * Tweak - Change MICE to use base site url instead of shop url by carterbuce in #2934 * Tweak - Improve custom checkout UI by ajello-meta in #2930 * Tweak - Make custom checkout UI mobile compatible by ajello-meta in #2942 * Fix - Update parsing for Checkout URL Product IDs by carterbuce in #2935 * Add - Implement dummy logging util by nealweiMeta in #2920 * Add - Setup cron job for batch logging with global message queue by nealweiMeta in #2924 * Add - Error log request api activate by nealweiMeta in #2933 * Add - Log locally with debug mode enabled by nealweiMeta in #2939 * Add - Ratings and reviews feed upload by nrostrow-meta in #2937 * Tweak - Feed upload skip logic and logging calls by nrostrow-meta in #2964 * Add - Add function to fetch feed upload instance by nrostrow-meta in #2970 * Tweak - Have feed uploads always use feed generator by nrostrow-meta in #2971 * Tweak - Trigger metadata feed uploads on CPI ID change (post onboarding) by nrostrow-meta in #2995 * Add - Shipping profile feed upload button by nrostrow-meta in #3140 * Add - Navigation menu feed upload logic by nrostrow-meta in #3159 * Fix - Fixing some fclose and logging gaps in the feed upload logic by nrostrow-meta in #3192 * Add - Enabling navigation menu feed upload and adding manual sync button by nrostrow-meta in #3223 * Add - Promotions feed upload by carterbuce in #2941 * Add - Plugin AJAX API Framework by sol-loup in #2928 * Tweak - Test Infrastructure Enhancement by sol-loup in #2944 * Add - Implement telemetry logs api by nealweiMeta in #2940 * Fix - Make error logging event configurable by nealweiMeta in #2954 * Add - Implement logging toggle by nealweiMeta in #2959 * Fix - auto products sync by nealweiMeta in #2978 * Tweak - Sync products with restriction by nealweiMeta in #2983 * Fix - Fix use_enhanced_onboarding for legacy connections by carterbuce in #2986 * Add - Create enhanced settings UI by ajello-meta in #2968 * Add - Create new troubleshooting drawer from legacy debug settings by ajello-meta in #2977 * Add - Add manual product and coupon sync buttons by ajello-meta in #2984 * Tweak - Make page title in enhanced settings static by ajello-meta in #2985 * Tweak - Align finalized content for logging toggle by nealweiMeta in #2992 * Tweak - Improve local log by nealweiMeta in #3009 * Fix - Fix free shipping coupon sync by carterbuce in #2993 * Tweak - Add logging for feed generation scheduling failure by carterbuce in #2994 * Tweak - Add logging in checkout for coupon code by ajello-meta in #2991 * Tweak - Clean up CSS in enhanced settings UI by ajello-meta in #2996 * Tweak - Remove the "Advertise" tab by ajello-meta in #3024 * Tweak - Sync "Usage Count" in Promos Feed by carterbuce in #3036 * Tweak - Disable mini_shops product capability for unsupported items by carterbuce in #3084 * Add - Add usage logging for enhanced settings tabs by ajello-meta in #3202 * Tweak - Remove UI of a checkbox that controls enablement of the new style feed generation by mshymon in #3056 * Fix - Fix linter errors for ./includes/fbutils.php files by ajello-meta in #3075 * Fix - Hotfix for Rollout Switches by vinkmeta in #3236 * Add - Opt out sync experience. by SayanPandey in #3220 * Fix - Added a transient flag to avoid flooding of product set api requests by vinkmeta in #3245 * Fix - Additional check for the opt-out banner by SayanPandey in #3259 * Fix - Bump up GraphAPI version to 21 by vahidkay-meta in #3219 * Fix - fix linter errors for ./class-wc-facebookcommerce.php by ajello-meta in #3255 * Fix - fix linter errors for ./facebook-commerce-events-tracker.php by ajello-meta in #3254 * Fix - fix linter errors for ./includes/Admin/Settings_Screens/Advertise.php by ajello-meta in #3237 * Fix - fix linter errors for ./includes/Admin/Settings_Screens/Product_Sync.php by ajello-meta in #3239 * Fix - fix function return typing for get_settings() by ajello-meta in #3257 * Tweak - Addition check for opt out by SayanPandey in #3259 * Tweak - Update the GraphAPI version to 21 by vahidkay-meta in #3219 * Fix - Enabled rollout switch only for plugin admins by vinkmeta in #3242 * Add - reset connection functionality by jczhuoMeta in #3262 * Fix - fixing the non static method called as static issue by SayanPandey in #3263 * Fix - Fix linter errors for ./facebook-commerce.php by ajello-meta in #3251 Pull Request resolved: #3264 Test Plan: Imported from GitHub, without a `Test Plan:` line. **!---- (auto-generated) DO NOT EDIT OR PUT ANYTHING AFTER THIS LINE ----!** MFTRunTestsScript Run / Test Suite: sa_checkout / Test Collection: bloks / Diff Version V7 https://internalfb.com/intern/testinfra/testrun/10414574226197703 MFTRunTestsScript Run / Test Suite: sa_checkout / Test Collection: www / Diff Version V7 https://internalfb.com/intern/testinfra/testrun/844425351364266 Reviewed By: vinkmeta, nrostrow-meta Differential Revision: D75569981 Pulled By: carterbuce fbshipit-source-id: 11bb39a9d66dfcbc80af413466feef0792d27ce4
Add REST API Framework for local APIs called by AJAX
Changes proposed in this Pull Request:
Closes #2345 (Replace with actual issue number if applicable)
Description
This PR introduces a new REST API framework for Facebook for WooCommerce that provides a structured, secure, and extensible way to handle API requests between the WordPress admin and Facebook services.
The previous implementation used ad-hoc REST endpoints with inconsistent validation and error handling. This new framework standardizes how we define endpoints, validate requests, and expose functionality to JavaScript, making the codebase more maintainable and secure.
Key Components
Controller (
includes/API/REST/Controller.php):AbstractRESTEndpoint (
includes/API/REST/AbstractRESTEndpoint.php):Request (
includes/API/REST/Request.php):JS_Exposable (
includes/API/REST/Traits/JS_Exposable.php):InitializeRestAPI (
includes/API/REST/InitializeRestAPI.php):Security Improvements
The new framework significantly improves security:
Migration Strategy
We've migrated the existing functionality from
MetaExtensionto the new framework:/settings/update)/settings/uninstall)The Connection screen has been updated to use the new API framework, ensuring backward compatibility while leveraging the improved architecture.
Do the changed files pass phpcs checks?
Yes, all new and modified files pass phpcs checks. No phpcs:ignore comments were added.
Screenshots [Validating old functionality is not broken]
Detailed test instructions
1. Basic Functionality
2. Legacy Connection Flow
3. Enhanced Onboarding
4. Disconnection Flow
5. JavaScript API Testing
Open browser developer tools (F12)
Go to Console tab
Test API client creation:
Test uninstall endpoint (only if you're willing to disconnect):
Verify the page reloads and connection is removed
6. Error Handling
Test invalid API calls to verify error handling:
Verify appropriate error messages are displayed
Additional details
includes/API/REST/README.md