PRO: oAuth Example

This pages shows how to get Access to JSON when a API uses the oAuth2 for authorization.

API-URL: http://api.json-content-importer.com/extra/api/bearer.php?a=w
This URL is expecting:

  • POST-Request
  • http-Header with “ACCESSTOKEN:token”

Why is that? bearer.php is build this way to demonstrate how this can be done with the JCI-Plugin.

Click on the above URL (this is GET, not POST) gives you a non-JSON response:

error: this API accepts POST-requests only!

This is not what we need to get access to the JSON-data.

Create a new JCI-Template with:

  • Name: oauth bearer request
  • URL: http://api.json-content-importer.com/extra/api/bearer.php?a=w
  • method: CURL-POST
  • httpstatuscodemustbe200=no tells the plugin to ignore http-errors (without only http-codes 200 are accepted) – if all is ok you can remove httpstatuscodemustbe200=no from the shortcode. Or leave it to catch errors.
[jsoncontentimporterpro nameoftemplate="oauth bearer request" httpstatuscodemustbe200=no]

twig-template:

{{_context | json_encode }}
<hr>Errormessage: {{_context.errormessage}} / time: {{_context.time}}

This gives us:

{"method":"POST","usedaccesstoken":"no token sent"} 
  • add to curloptions in the JCI-template:
    CURLOPT_HTTPHEADER=ACCESSTOKEN:whatever
  • API-response with this:
{"method":"POST","usedaccesstoken":"whatever","authorization":"failed"} 
[jsoncontentimporterpro nameoftemplate="gettoken"]

Received Token:

a029d0df84eb5549c641e04a9ef389e5

Now we use this Shortcode in the curloptions to replace “whatever” by the token: #BRO# and #BRC# stand for [ and ], which otherwise cause WordPress-Trouble…

CURLOPT_HTTPHEADER=ACCESSTOKEN:#BRO#jsoncontentimporterpro nameoftemplate=gettoken#BRC#

This gives us:

{"method":"POST","usedaccesstoken":"a029d0df84eb5549c641e04a9ef389e5","authorization":"ok","errormessage":"none","time":"Mon 06 2022, 09:59:07"}
Errormessage: none / time: Mon 06 2022, 09:59:07