1

我正在使用 Foursquare API,我需要向他们的服务器发出请求,以便接收 JSON 格式的访问令牌(https://developer.foursquare.com/overview/auth)。如何使用 PHP 做到这一点?

我还没有在网上找到任何权威的教程,这就是我在这里问的原因。我已经看到了一些我不太了解的与 cURL 相关的东西,那么有什么简单的方法可以做到这一点吗?我在使用 AJAX 之前已经完成了它,它非常不言自明,但它在 PHP 中似乎非常复杂,远远超过它的外观:(

任何人都可以帮忙吗?谢谢

4

2 回答 2

1
<?php

# url_get_contents function by Andy Langton: http://andylangton.co.uk/

function url_get_contents($url,$useragent='cURL',$headers=false,$follow_redirects=false,$debug=false) {

# initialise the CURL library
$ch = curl_init();

# specify the URL to be retrieved
curl_setopt($ch, CURLOPT_URL,$url);

# we want to get the contents of the URL and store it in a variable
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

# specify the useragent: this is a required courtesy to site owners
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);

# ignore SSL errors
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

# return headers as requested
if ($headers==true){
curl_setopt($ch, CURLOPT_HEADER,1);
}

# only return headers
if ($headers=='headers only') {
curl_setopt($ch, CURLOPT_NOBODY ,1);
}

# follow redirects - note this is disabled by default in most PHP installs from 4.4.4 up
if ($follow_redirects==true) {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
}

# if debugging, return an array with CURL's debug info and the URL contents
if ($debug==true) {
$result['contents']=curl_exec($ch);
$result['info']=curl_getinfo($ch);
}

# otherwise just return the contents as a variable
else $result=curl_exec($ch);

# free resources
curl_close($ch);

# send back the data
return $result;
}

?>
于 2012-07-31T23:35:07.860 回答
1

好吧,按照您提供的链接,试试这个:

重定向链接中的脚本(YOUR_REGISTERED_REDIRECT_URI)

if(isset($_GET['code']))
{
    $code = $_GET['code'];
    $url = "https://foursquare.com/oauth2/access_token?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=authorization_code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&code=$code";

    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_POST);

    $json = curl_exec($ch);

    var_dump($json);
}

注意:阅读您提供的教程后,我没有看到任何对 POST 请求的引用,只有请求,所以您可以试试这个(而不是 cURL)

$json = file_get_contents($url);

如果它是一个简单的 GET 请求,那么 file_get_contents 可能会起作用。

于 2012-07-31T23:42:02.187 回答