You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce自定义登录API端点报404无REST路由错误求助

Fixing the 404 Error for Your Custom WooCommerce Login REST Endpoint

Hey there! Let's troubleshoot why your custom login endpoint is throwing a 404 and get it up and running smoothly. Looking at your code snippet, there are a few clear issues and best practices to address:

1. Fix the Route Path Syntax Error

Your route path has an extra closing parenthesis (/login/)) that’s breaking the route registration—this is almost certainly the main cause of your 404. Clean up the path to either /login or /login/ (no stray parentheses).

2. Complete the Route with a Callback Function

Your code cuts off at 'call...'—every valid REST route requires a callback parameter pointing to a function that handles the incoming request. Without this, the route isn’t fully registered and won’t be recognized by WordPress.

3. Add a Permission Callback (and Prioritize Security)

Since this is a login endpoint, you’ll need to make it publicly accessible (users aren’t logged in yet), so set permission_callback to __return_true. Just be sure your site uses HTTPS to avoid sending credentials over unencrypted connections.

Corrected Full Code Example

Here’s a polished, working version of your code with all fixes and a sample login handler:

add_action( 'rest_api_init', function () {
    register_rest_route( 
        'wc/v2', 
        '/login', // Fixed route path
        array(
            'methods' => WP_REST_Server::CREATABLE, // Use WordPress constant instead of 'POST' for consistency
            'callback' => 'custom_wc_login_handler', // Required request handler function
            'permission_callback' => '__return_true', // Allow public access for login requests
        )
    );
} );

// Handler function to process login logic
function custom_wc_login_handler( WP_REST_Request $request ) {
    // Extract JSON credentials from the POST request
    $credentials = $request->get_json_params();
    
    // Validate required fields
    if ( empty( $credentials['username'] ) || empty( $credentials['password'] ) ) {
        return new WP_REST_Response(
            array( 'error' => 'Username and password are required' ),
            400
        );
    }

    // Authenticate user with WordPress core function
    $user = wp_authenticate( $credentials['username'], $credentials['password'] );
    
    if ( is_wp_error( $user ) ) {
        return new WP_REST_Response(
            array( 'error' => 'Invalid username or password' ),
            401
        );
    }

    // Optional: Initialize WooCommerce customer session if your app needs it
    wc_set_customer_session_cookie( true );

    // Return success response with relevant user data (adjust based on your app's needs)
    return new WP_REST_Response(
        array(
            'success' => true,
            'user_id' => $user->ID,
            'user_email' => $user->user_email,
            'display_name' => $user->display_name
        ),
        200
    );
}

Testing the Endpoint

After adding this code to your theme’s functions.php or a custom plugin, test it with a tool like Postman or curl:

  • Send a POST request to https://your-woocommerce-site.com/wp-json/wc/v2/login
  • Include a JSON body with your credentials:
    {
        "username": "your-test-username",
        "password": "your-test-password"
    }
    

Additional Tips

  • API Version: Consider using WooCommerce’s latest REST API version (v3) instead of v2 for better compatibility and updated features.
  • Security: For production, avoid returning raw user data—implement JWT tokens instead for secure subsequent requests.
  • Plugin Best Practice: Add this code to a custom plugin rather than your theme’s functions.php so your endpoint won’t break if you switch themes later.

内容的提问来源于stack exchange,提问作者Nagender Gupta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:09:17