Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LearnDash: How to authenticate API call?

I need to call LearnDash API from the WordPress for example like this:

wp_remote_request ('https://mywpsite/wp-json/ldlms/v1/groups', $arg);

LearnDash API is protected, so I'm getting 401 response:

{"code":"rest_forbidden","message":"Tut mir leid, aber Sie haben keine Berechtigung das zu tun.","data":{"status":401}}

In the LearnDash API docs, there is no information how one can authenticate call (Which auth header use, what kind of authentication, etc).

How can I authenticate the call to LearnDash ?

I'm not WordPress expert, but may be there is a standard way to make such authenticated call to plugins' API?

P.S.: LearnDash is installed in same WordPress installation I need to make a call from, I can't call functions directly, at least I didn't find required functions in LearnDash docs.

like image 522
Teimuraz Avatar asked Oct 22 '25 12:10

Teimuraz


1 Answers

This happens because you are not authenticated for that API route.

first install WP REST API plugin in wordpress

then you must use JWT token for example in PHP you can use firebase/php-jwt

composer require firebase/php-jwt

Code example:

<?php
require_once 'vendor/autoload.php'; // Include the JWT library

use Firebase\JWT\JWT;

// Your secret key for signing the token
$secret_key = 'your-secret-key';

// Payload data (you can customize this according to your needs)
$payload = array(
    "iss" => "mywpsite.com",
    "aud" => "mywpsite",
    "iat" => time(),
    "exp" => time() + 3600, // Token expiration time (1 hour from now)
    // Add any other relevant data here
);

// Generate the JWT token
$token = JWT::encode($payload, $secret_key);

// Prepare the request headers
$headers = array(
    'Authorization: Bearer ' . $token,
    'Content-Type: application/json',
);

// Make the API request
$api_url = 'https://mywpsite/wp-json/ldlms/v1/groups';
$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);

var_dump($response);

?>

Pay attention that the generated jwt token is placed in the Authorization header.

like image 145
eiliya keshtkar Avatar answered Oct 24 '25 19:10

eiliya keshtkar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!