Search code examples
phpjsonoauth-2.0google-oauthactions-on-google

Return a JSON object in the body of a HTTPS response


I have a OAUTH 2.0 Server, and i have succesfully implemented it up to the last level using PHP

Reference Link : https://developers.google.com/actions/identity/oauth2-code-flow

However, im am on the Last Step now which says

---> Return the following JSON object in the body of the HTTPS response

 {
 token_type: "bearer",
 access_token: "ACCESS_TOKEN",
 refresh_token: "REFRESH_TOKEN",
 expires_in: SECONDS_TO_EXPIRATION
 }

I have done the following

$json = array(
'token_type:' => "bearer",
'access_token:' => $ACCESS_TOKEN,
'refresh_token:' => $REFRESH_TOKEN,
'expires_in:' => '3600'

);
  $jsonstring = json_encode($json);
  echo $jsonstring;
  die(); 

In which $ACCESS_TOKEN and $REFRESH_TOKEN and two variables containing the necessary information.
My Question is how do i return the 'JSON object in the body of the HTTPS response: '?

Would mean a lot if anyone can help me figure this out
Thanks in Advance!
Please visit this site, and see you might understand what i'm trying to do then :)
https://developers.google.com/actions/identity/oauth2-code-flow


Solution

  • Most of your action appears to be correct. Sending JSON as the body requires two steps.

    First, you must set the content-type header to indicate the body is JSON. You must do this before any other data, including blank lines, are output. Having this right after the PHP header on the page is probably good practice to make sure nothing else included generates this. This header is done as something like

    <?php
    header("Content-type:application/json");
    

    The rest of your code looks correct. Sending a "JSON Object" means sending a specifically formatted text representation of the data. That formatting is done through json_encode().

    $json = array(
      'token_type:' => "bearer",
      'access_token:' => $ACCESS_TOKEN,
      'refresh_token:' => $REFRESH_TOKEN,
      'expires_in:' => '3600'
    );
    $jsonstring = json_encode($json);
    echo $jsonstring;