user1452893
user1452893

Reputation: 868

OAuth response works as URL but can't get cURL to work in PHP

I'm trying to get an OAuth response to work with Slack but no joy.

I get to the point where I get a "code" var value returned from Slack that I need to include in my response.

I can manually build a URL using the returned value and send it as a response to complete the OAuth and install my app—that works every time. It looks like this:

https://slack.com/api/oauth.access?client_id=12345&code=123.456.789&client_secret=12345678&

The 'code' var is the variable bit, the other stuff is all static.

I know the PHP is getting the value of "code" I need because I can echo it.

Here's the PHP that doesn't work:

    <?php 

    $authCode = $_GET['code'];
    echo $authCode; //succeeds

    $client_id = '12345';
    $client_secret = '12345678';


    $data = array(
                'client_id' => $client_id,
                'client_secret' => $client_secret,
                'code' => $authCode
                    );
            $data_string = json_encode($data);


    $ch = curl_init('https://slack.com/api/oauth.access');

                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json',
                    'Content-Length: ' . strlen($data_string))
                );
            //Execute CURL

            $result = curl_exec($ch);
            return $result; 


     ?>

I would like to see a new page loaded after sending the response but first things first.

This is my first attempt at something like this so I suspect I've missed an important bit that I hope someone can help sort for me.

Any alternative approach that achieves a successful result is welcomed. Thanks!

Upvotes: 0

Views: 483

Answers (1)

Hans Z.
Hans Z.

Reputation: 54088

There are two things not quite right here:

  1. You are providing the input parameters in JSON format but, following the OAuth 2.0 specification, the Slack API requires parameters to be provided as GET or POST parameters as documented here: https://api.slack.com/web#basics. So you should use http_build_query($data) rather than json_encode($data), and omit setting any HTTP headers yourself.

  2. the redirect_uri parameter is missing from the request

Upvotes: 1

Related Questions