I am trying to create a Plugin that does the following jobs:
- Authenticate the user to get Bearer token 'access_token'
- Get data from API and store in Database
I have checked all the APIs and endpoints using Postman and they successfully received the desired responses. I created a folder 'MYAPI' inside the 'Plugins' directory as per the WordPress plugin development documentation and also created the necessary files.
To authenticate the API, from what I understand I need to use the wp_safe_remote_request
function and I did. The following is my entire code for the authentication of the user to get a bearer token for the further API requests.
function authenticate_api() { $user_id = '[email protected]'; $password = '123456'; $auth_url = 'https://my-example-url.com/oauth/token'; $headers = array( 'Content-Type' => 'application/x-www-form-urlencoded', 'Authorization' => 'Basic Base64enodedusercredentials', ); $post_data = array( 'grant_type' => 'password', 'username' => $user_id, 'password' => $password, ); $response = wp_safe_remote_request($auth_url, array( 'method' => 'POST', 'headers' => $headers, 'body' => $post_data, )); if (is_wp_error($response)) { return 'API request error: ' . $response->get_error_message(); } $status_code = wp_remote_retrieve_response_code($response); if ($status_code === 200) { $response_body = wp_remote_retrieve_body($response); $auth_data = json_decode($response_body, true); if (isset($auth_data['access_token'])) { return 'API authentication succeeded. Bearer token: ' . esc_html($auth_data['access_token']); } } else { return 'API authentication failed. HTTP status code: ' . $status_code; } }
I also wrote a piece of code that generates a shortcode to check the status of the response.
function api_authentication_test_shortcode() { // Attempt API authentication. $token = authenticate_api(); if ($token) { return 'API authentication succeeded. Bearer token: ' . esc_html($token); } else { return 'API authentication failed. Please check your credentials.'; } } // Register the shortcode. add_shortcode('api_authentication_test', 'api_authentication_test_shortcode');
Unfortunately when I use the shortcode [api_authentication_test]
on a test page, I am shown the following
API authentication succeeded. Bearer token: API authentication failed. HTTP status code: 401
I have tried removing the $post_data
and put them in the URL as it is when making the request using Postman. I have also tried using explode() to get just the bearer token and still the same output. I appreciate any help.