Using Curl in PHP

I am working on a project to help me learn how to use curl

through PHP

. I am trying to get data from Twitch-API

using my own account for testing.

I have successfully authenticated my account to my domain using:

https://api.twitch.tv/kraken/oauth2/authorize?response_type=code&client_id=...&redirect_uri=...&scope=user_read+channel_read+channel_subscriptions+user_subscriptions+channel_check_subscription&state=...

      

I removed client_id

, redirect_uri

and state

to show the link I was using.

After successful authentication, it goes back to the domain that I specify ( redirect_uri

), after it goes back to that domain, the website only knows the authentication key that is generated after it is accepted by the user, from under the yoke.

Auth example: 3ofbaoidzkym72ntjua1gmrr66o0nd

Now I would like to be able to get the username, there is documentation there :

curl -H 'Accept: application/vnd.twitchtv.v3+json' -H 'Authorization: OAuth <access_token>' \
-X GET https://api.twitch.tv/kraken/user

      

I'm trying to do it in PHP, but I don't understand the curl function ... Here's what I have so far:

<?php if(isset($_GET['code']) && isset($_GET['scope'])) { ?>

<pre>
<?php
    $auth = $_GET['code'];
    $twitch = curl_init();

    $headers = array();
    $headers[] = 'Accept: application/vnd.twitchtv.v3+json';
    $headers[] = 'Authorization: OAuth ' .$auth;
    curl_setopt($twitch, CURLOPT_HEADER, $headers);
    curl_setopt($twitch, CURLOPT_URL, "https://api.twitch.tv/kraken/user");

    curl_exec($twitch);
?>
</pre>

<?php }; ?>

      

When I try to run this section of code, I get some errors:

HTTP/1.1 401 Unauthorized
Server: nginx
Date: Sat, 08 Aug 2015 13:43:51 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 89
Connection: keep-alive
Status: 401 Unauthorized
X-API-Version: 3
WWW-Authenticate: OAuth realm='TwitchTV'
Cache-Control: max-age=0, private, must-revalidate
Vary: Accept-Encoding
X-UA-Compatible: IE=Edge,chrome=1
X-Request-Id: 4bc2e0bfadf6817366b4eb19ab5751bf
X-Runtime: 0.007862
Accept-Ranges: bytes
X-Varnish: 1641121794
Age: 0
Via: 1.1 varnish
X-MH-Cache: rails-varnish-5cb970; M

{"error":"Unauthorized","status":401,"message":"Token invalid or missing required scope"}

      

But I'm not sure how to fix this issue, as it seems to me that I / did everything the documentation says to do ...

How can I solve this problem?

Edit:

It seems to work if I ask to use the twitch username :

curl -H 'Accept: application/vnd.twitchtv.v3+json' \
-X GET https://api.twitch.tv/kraken/users/test_user1

      

My code for using username:

<?php
$auth = urlencode($_GET['code']);
$twitch = curl_init();

$headers = array();
$headers[] = 'Accept: application/vnd.twitchtv.v3+json';
#$headers[] = 'Authorization: OAuth ' .$auth;
curl_setopt($twitch, CURLOPT_HTTPHEADER , $headers);
curl_setopt($twitch, CURLOPT_URL, "https://api.twitch.tv/kraken/users/...");

curl_exec($twitch);
?>

      

But I wouldn't know the user's username, unless I get it from the statement that generates the error and stores it in the database.

Edit:

Reading in the documentation is more, it requires a scope as well as an access token. I was able to get the following:

Example:

Array
(
    [0] => Accept: application/vnd.twitchtv.v3+json
    [1] => Authorization: OAuth code=scn89zerug002sr6r95z9ngbxmd0d2&scope=user_read+channel_read+channel_subscriptions+user_subscriptions+channel_check_subscription
)

      

But I am still getting the error ...

Edit:

So I read the documentation EVEN MORE and now I figured out:

class twitch {
    var $base_url = "https://api.twitch.tv/kraken/";
    var $client_id = "...";
    var $client_secret = "...";
    var $return_url = "...";
    var $scope_array = array('user_read','channel_read','channel_subscriptions','user_subscriptions','channel_check_subscription');

    public function get_access_token($code,$state) {
        $ch = curl_init($this->base_url . "oauth2/token");
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        $fields = array(
             'client_id' => $this->client_id,
             'client_secret' => $this->client_secret,
             'grant_type' => 'authorization_code',
             'redirect_uri' => $this->redirect_url,
             'code' => $code
        );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
        $data = curl_exec($ch);
        $response = json_decode($data, true);
        curl_close($ch);

        echo "<pre>".print_r($this->redirect_url,true)."</pre>";
        echo "<pre>".print_r($response,true)."</pre>";

        return $response["access_token"];
    }
};

$auth = new twitch();
print_r($auth->get_access_token($_GET['code'],$_GET['state']));

      

But this time there is another mistake, stating that mine 'redirect_uri' => $this->redirect_url

is different from the one held by the twitch.

Array
(
    [error] => Bad Request
    [status] => 400
    [message] => Parameter redirect_uri does not match registered URI
)

      

I even copied and pasted from the twitch site to my variable and vice versa, I still get the same error ... Now I'm even more stuck, but at least a step closer.

+3


source to share


1 answer


That's right, I'm going to do it with you the way I do it: d I could get one user so far, the reason you are getting errors is because you are not setting any curl parameters. I taught myself to use this https://github.com/paypal/rest-api-curlsamples/blob/master/execute_all_calls.php which I found MASSIVELY helpful when learning curl. The code itself is basic, but so easy to read. I managed to figure it out and make it 100% harder: D

First of all, I'll show you how I got the test user. What you want to do is set the parameters, I'll stick with a simple method first.

2 methods: CURLOPT_HEADER

and CURL_RETURNTRANSFER

. You can set your url using init function.

$twitch=curl_init('https://api.twitch.tv/kraken/users/test_user1');
curl_setopt($twitch,CURLOPT_HTTPHEADER,array('Accept: application/vnd.twitchtv.v3+json'));//must be an array.
curl_setopt($twitch,CURLOPT_RETURNTRANSFER,true);
$result=curl_exec($twitch);
$info=curl_getinfo($twitch);
print_r($result);

      

This will give you your test user and hopefully show you a little about what you are doing wrong. If you want to use an array method, then you must use your curl parameters as the array key so that the set function knows what to set how. (don't ask me how it all technically works: S)

I'll update to show you how to get authorization and details as soon as I process it. But basic principles: you need to send post data and set CURLOPT_POST

to true and include postdata CURLOPT_POSTFIELDS

, which should be a json array since your application requires json, I suppose?

Anyway the array:



curl_set_opts($twitch,array(CURLOPT_HEADER=>array('Accept: application/vnd.twitchtv.v3+json',CURLOPT_RETURNTRANSFER=true));

      

Seeing as you already know how to authorize a user, I will skip this bit, although I would recommend using something more secure than $_GET

. Maybe session variable would be a little better.

To get a specific user using the returned Auth. You want to do something like this: (Sorry, I can't test it myself, I don't have a twitch dev account)

$twitch=curl_init('https://api.twitch.tv/kraken/user');
curl_setopt($twitch,CURLOPT_HEADER,array('Accept: application/cvd.twitchtv.v3+json','Authorization: OAuth '.$_SESSION['token']));
curl_setopt($twitch,CURLOPT_RETURNTRANSFER,true);
$result=curl_exec($twitch);
print_r($result);
//don't forget to close! 
curl_close($twitch);
$user=json_decode($result);

echo$user->display_name;

      

This should work, although I have no idea how you get the oAuth token lol

if you want to be a really cool programmer 8 | I would recommend making several classes for this. Like this

class twitch{
    private$token,$twitch,$url="http://api.twitch.tv/kraken/";
    protected$code,$state,$report;
    private static$details;
    public function __construct($code,$state){
        $this->code=$code;
        $this->state=$state;
        self::$details=(object)array('client_id'=>'id','client_secret'=>'secret','return_url'=>'redirect');
        $result=$this->makeCall('oauth2/token',true);
        print_r($result);
    }
    protected function makeCall($extention,$auth=false,$object=true){
        $this->twitch=curl_init($this->url.$extention);
        //$opts=array(CURLOPT_)
        if($auth!==false){
            $opts=array(CURLOPT_FOLLOWLOCATION=>true,CURLOPT_RETURNTRANSFER=>true,CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>json_encode(array('client_id'=>self::$details->client_id,'client_secret'=>self::$details->client_secret,'grant_type'=>'authorization_code','code'=>$this->code,'redirect_uri'=>self::$details->return_url)));
        }else{
            $opts=array(CURLOPT_HEADER=>array('Accept: application/cvd.twitchtv.v3+json','Authorization: OAuth '.$this->token),CURLOPT_RETURNTRANSFER=>true);
        }
        curl_setopt_array($this->twitch,$opts);
        $result=curl_exec($this->twitch);
        $this->report=array('info'=>curl_getinfo($this->twitch),'error'=>curl_error($this->twitch));
        curl_close($this->twitch);
        return($object===true)?json_decode($result):$result;
    }
    protected function userDetails(){
        return$this->makeCall('user');
    }
    public function user(){
        return$this->userDetails();
    }
}       

      

+1


source







All Articles