简体   繁体   English

从PHP中的cURL请求获取Foursquare access_token

[英]get Foursquare access_token from cURL request in PHP

I'm testing a cURL function to get back the access token for a given user on Foursquare. 我正在测试cURL函数,以获取Foursquare上给定用户的访问令牌。 The following function prints to the screen the access token in a json format 以下函数以json格式将访问令牌打印到屏幕上

{"access_token":"5B25GW5LF3L4W04PALHK32X5Z3YGNUUVDHM2TFBQOWZSQ121"} 

I'm having problems in extracting the value of the access token. 我在提取访问令牌的值时遇到问题。

This is the function I'm using: 这是我正在使用的功能:

function get_access_token($code){ 函数get_access_token($ code){

        $url = "https://foursquare.com/oauth2/access_token";

        $fields = array(
            'client_id' => urlencode($this->client_id),
            'client_secret' => urlencode($this->client_secret),
            'grant_type' => 'authorization_code',
            'redirect_uri' => urlencode($this->redirect_url),
            'code' => $code
        );

        //url-ify the data for the POST
        foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
        rtrim($fields_string, '&');

        //open connection
        $ch = curl_init();

        //set the url, number of POST vars, POST data
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_POST, count($fields));
        curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

        //execute post
        $result = curl_exec($ch);
        //close connection
        curl_close($ch);

        return var_dump($result) /* prints bool(true) */;
    }

How to I store this access token in a variable? 如何将此访问令牌存储在变量中?

Thank you 谢谢

By default curl_exec does not return the response, but a value indicating success or failure. 默认情况下,curl_exec不返回响应,而是一个指示成功或失败的值。 Visit http://php.net/manual/en/function.curl-exec.php for more information. 访问http://php.net/manual/en/function.curl-exec.php了解更多信息。

Just add one more line of code to tell curl to pass the return value back to curl_exec and to your $result variable: 只需再添加一行代码,告诉curl将返回值传递回curl_exec以及$ result变量即可:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

You may also want to check if an error occurred when the data comes back: For example: 您可能还需要检查返回数据时是否发生错误:例如:

$result = curl_exec($ch);
if (curl_errno($ch)) 
   echo (curl_error($ch));
else
   echo $result;
curl_close($ch);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM