• May I ask that I have installed CoCart – JWT Authentication and set .htaccess to RewriteEngine on
    RewriteCond %{HTTP:Authorization} ^(.)
    RewriteRule ^(.) – [E=HTTP_AUTHORIZATION:%1] and
    set COCART_JWT_AUTH_SECRET_KEY, can I do this in function.php?

    function generate_cocart_jwt_on_login($user_login, $user) {
    error_log(‘User logged in: ‘ . $user_login);

    // Define the API endpoint for CoCart login
    $cocart_login_url = get_site_url() . ‘/wp-json/cocart/v2/login’;

    // Prepare the request body
    $body = array(
    ‘username’ => $user->user_login,
    ‘password’ => ” // Password is not needed since the user is already authenticated
    );

    // Send a request to the CoCart login endpoint
    $response = wp_remote_post($cocart_login_url, array(
    ‘method’ => ‘POST’,
    ‘body’ => json_encode($body),
    ‘headers’ => array(
    ‘Content-Type’ => ‘application/json’
    ),
    ‘sslverify’ => false // Ensure this is set appropriately for your environment
    ));

    // Handle the response
    if (is_wp_error($response)) {
    error_log(‘CoCart JWT Error: ‘ . $response->get_error_message());
    return;
    }

    $response_body = json_decode(wp_remote_retrieve_body($response), true);

    // Check if ‘extras’ and ‘jwt_token’ exist in the response
    if (isset($response_body[‘extras’][‘jwt_token’])) {
    $jwt_token = $response_body[‘extras’][‘jwt_token’];
    // Store the JWT token in user meta
    update_user_meta($user->ID, ‘cocart_jwt_token’, $jwt_token);
    error_log(‘JWT token stored for user ID: ‘ . $user->ID);
    } else {
    error_log(‘JWT token not found in CoCart response.’);
    }
    }
    add_action(‘wp_login’, ‘generate_cocart_jwt_on_login’, 10, 2);

  • You must be logged in to reply to this topic.