Search code examples
phpjqueryjsonoauthpocket

JSON POST request - Pocket API / OAuth2.0


I'm attempting to build an application that interfaces with Pocket using PHP and JQuery

Following the steps here http://getpocket.com/developer/docs/authentication I'm stuck on "Step 2: Obtain a request token"

The documentation tells me this:

POST /v3/oauth/request HTTP/1.1
Host: getpocket.com
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Accept: application/x-www-form-urlencoded

consumer_key=1234-abcd1234abcd1234abcd1234&
redirect_uri=pocketapp1234:authorizationFinished

This makes no sense to me. How do I format this OAuth JSON POST request to use PHP and/or JQuery?

Note, I've attempted to use https://github.com/jshawl/pocket-oauth-php, but it fails on the callback and seems to use GET while the documentation explicitly states POST. I'd also like to figure this out myself so I can learn how to use OAuth for other APIs.

Thank you.


Solution

  • this seems to work ok:

    <?php
    session_start();
    $redirect_uri = 'http://path/to/app/callback';
    $url = 'https://getpocket.com/v3/oauth/request';
    $data = array('consumer_key' => '*****', 'redirect_uri' => $redirect_uri);
    
    // use key 'http' even if you send the request to https://...
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded; charset=UTF-8",
            'method'  => 'POST',
            'content' => http_build_query($data),
        ),
    );
    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    
    $request_token = str_replace('code=','',$result);
    
    $_SESSION['request_token'] = $request_token;
    
    header("Location: https://getpocket.com/auth/authorize?request_token=$request_token&redirect_uri=$redirect_uri");
    die();
    
    ?>
    

    After which I use the request_token in the session to get my access token in a similar way.