Step 5 - Using the OAuth Token (Making API calls?)

Hello!

I’m having some trouble making calls with the API. I am able to get back the access token but when I try to make a GET request to make API calls I’m getting this error.

body: `{"errors":[{"code":1,"code_name":"Unauthorized","detail":"The server could not verify that you are authorized to access the URL requested. You either supplied the wrong credentials (e.g. a bad password), or your browser doesn't understand how to supply the credentials required.","id":"f551adf8-d096-46cc-90a5-d67ceeb87638","status":"401","title":"Unauthorized"}]}`,
  statusCode: 401

I’m doing all of this in a JavaScript Node environment. I suspect that I’m not constructing the GET request correctly but I’m not exactly sure how it should be done.
Here is the code I’m using to make all of this work.

const tiny = require('tiny-json-http')

let client_id = process.env.CLIENT_ID
let client_secret = process.env.CLIENT_SECRET
let redirect_uri = process.env.REDIRECT_URI

module.exports = async function patreon(req) {
    let code = req.query.code
    console.log('code', code)
    console.log("made it to patreon.js")
    try {
        let result = await tiny.post({
            url: `https://www.patreon.com/api/oauth2/token?code=${code}&grant_type=authorization_code&client_id=${client_id}&client_secret=${client_secret}&redirect_uri=${redirect_uri}`,
            headers: {
                'content-type': 'application/x-www-form-urlencoded'
            }
        }) 
        console.log("RESULT:", result)
      
      let token = result.body.access_token
      console.log("TOKEN:", token)

      let user = await tiny.get({
        url: `https://www.patreon.com/api/oauth2/v2/identity`,
        headers: {
          Authorization: `${token}`,
          Accept: 'application/json'
        }
      })
      console.log("made it to part2")
      console.log(user)
      return {
        token
      }
    } catch (err) {
        console.error(err);
      return {
        error: err.message
      } 
    } 
  }

The first half of this code runs and I’m able to use a POST to receive the access token but the GET is giving me the error.

Any help or direction would be appreciated. Thank you!

At a first glance, it looks like your Authorizations statement is invalid. I’m not sure on the language you’re using but try:

Authorization: `Bearer `${token}`,
For more info, see: API Reference

It could be the capitalization of Authorization even, given it shows as lower case in the API docs, but I don’t know how particular their system actually is.

Past that, did you request the identity scope when that user authenticated with Patreon?

1 Like

This was exactly it. I’m authorized and getting back a response now! Thank you so much for your help. I was stuck on this for the past few days. I should be able to grok these scopes and API calls now. Thanks again Zanaras.

1 Like

Happy to help! If you have any future questions about API stuff, hit me up. I don’t have many patrons myself to really test things out with but I’ve done a bunch of work figuring out how the API actually works.

2 Likes

Hey @Zanaras, could I get your help with understanding how to create the correct call to pull campaign posts from the creator token?

I’m able to get my user info with this URL:

url:https://www.patreon.com/api/oauth2/v2/identity?include=memberships.currently_entitled_tiers,memberships.campaign&fields${encodeURIComponent(’[user]’)}=email,first_name,full_name,image_url,last_name,thumb_url,url,vanity,is_email_verified&fields${encodeURIComponent(’[post]’)}=title,content,is_paid,is_public,published_at,url,embed_data,embed_url,app_id,app_status

Which returns:

body: {
    data: {
      attributes: [Object],
      id: '64541522',
      relationships: [Object],
      type: 'user'
    },
    links: { self: 'https://www.patreon.com/api/oauth2/v2/user/64541522' }

The problem occurs when I try to call for posts using this URL:

url:https://www.patreon.com/api/oauth2/v2/campaigns/64541522/posts?fields${encodeURIComponent(’[post]’)}=url,title,content,published_at

I get back this array:

body: { data: [], meta: { pagination: [Object] } }

Would you happen to know the correct way to pull campaign posts? Any direction would be greatly appreciated. I found several similar issues in the forum but no solution.

While it’d make sense if it was so, your patreon user ID and the campaign you run with that user profile have different IDs. So if there is a campaign ID 64541522, you probably don’t have access to it and it likely isn’t yours. I’d expect your campaign ID to be a significantly smaller number than your user ID–mine vary by millions.

Anyways, If you add ‘campaign’ to your include list, it’ll return the ID of your campaign since it looks like you’re using your own user token, even without declaring any fields for that object type. You could of course also add &fields${encodeURIComponent('[campaign]')}= and list fields you want from those listed here: API Reference

An easy way to be absolutely sure would be to request the URL field of the campaign object, &fields${encodeURIComponent('[campaign]')}=url which should match the public URL of your campaign.

After that it’s just the campaigns/[campaignID]/posts?fields$encodeURICompoent(['post'])}=url,title,content,published_at you’re already using.

Hopefully this helps!

2 Likes

Yo @Zanaras, thank you once again! This was helpful and is pulling the exact information I need. I appreciate the lesson!

Patreon WordPress plugin has a pretty fleshed out implementation of post syncing. You can check out its code.

1 Like

Thanks @codebard! I’ve looked over this a few times and I think it will be helpful to me now that I’ve learned a bit more about the API from you and @Zanaras. I was having trouble converting it from PHP to JS but I think I’ve got the hang of it now.

1 Like