2

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.

Teimuraz
  • 8,795
  • 5
  • 35
  • 62

1 Answers1

1

you need to use a basic JWT auth, such as this one: https://cl.wordpress.org/plugins/jwt-authentication-for-wp-rest-api/

Then, you need to include your authentication as a middleware, to retrieve the corresponding token and send it with your request to the Learndash endpoint.

In nextjs, I use this code:

export async function getCourseContent(id) {
  try {
    const token = await AuthJWT()
    const url = `https://yourserver.com/wp-json/ldlms/v2/sfwd-lessons?course=${id}`

    const courseSteps = await axios.get(url, {
      headers: {
        Authorization: `Bearer ${token}`
      }
    })

    return courseSteps.data
  } catch (error) {
    console.log(error, 'error')
  }
}

export async function AuthJWT() {
  try {

    const credentials = {
      username: process.env.EMAIL_ADMIN,
      password: process.env.PASSWORD_ADMIN
    }
    // console.log(credentials, 'credentials')
    const headers = {
      "Content-Type": "application/json"
    }


    const getToken = await axios.post('https://yourserver.com/wp-json/jwt-auth/v1/token',
      credentials,
      headers)
    // console.log(getToken.data.token, 'from authjwt')
    return getToken.data.token

  } catch (error) {
    return console.log('error', error)
  }

}