简体   繁体   English

在PHP中访问Yelp API

[英]Accessing Yelp API in PHP

I'm getting started with Yelp API v3 (Fusion). 我开始使用Yelp API v3(融合)。 I have created an app, got Client ID and Client Secret. 我创建了一个应用程序,获得了客户端ID和客户端密钥。

I understand that I need to get a token from Yelp API and then using business ID retrieve json data. 我了解我需要从Yelp API获取令牌,然后使用业务ID检索json数据。

I've found the following PHP code: 我发现以下PHP代码:

$postData = "grant_type=client_credentials&".
            "client_id=YOURCLIENTID&".
            "client_secret=SECRET";
$ch = curl_init();

//set the url
curl_setopt($ch,CURLOPT_URL, "https://api.yelp.com/oauth2/token");
//tell curl we are doing a post
curl_setopt($ch,CURLOPT_POST, TRUE);
//set post fields
curl_setopt($ch,CURLOPT_POSTFIELDS, $postData);
//tell curl we want the returned data
curl_setopt($ch,CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);

//close connection
curl_close($ch);

if($result){
   $data = json_decode($result);
   echo "Token: ".$data->access_token;
}

I've entered my ID and SECRET but got a blank page. 我已经输入了ID和SECRET,但页面空白。 What else am I missing? 我还想念什么?

there's 3 versions of the API, you don't specify which version you're targeting, V1, V2, or Yelp Fusion (V3?) , but seeing as V2 is in the process of being retired (for example, they wont allow new programmers to sign up for an access token for V2), i guess you mean Fusion. 该API有3个版本,您没有指定要定位的版本是V1,V2还是Yelp Fusion(V3?),但是看到V2正在淘汰中(例如,他们不允许使用新版本程序员注册V2的访问令牌),我想你的意思是Fusion。

according to the docs, it all starts by making a request to https://api.yelp.com/oauth2/token , using your client_id and client_secret (that you get when registering a new app), and a hardcoded grant_type = client_credentials - and your code does do that, but it doesn't properly url encode the client_id and client_secret, that may be why you're getting a blank page (and that in itself means that you're not debugging using CURLOPT_VERBOSE - when debugging curl requests, always use CURLOPT_VERBOSE - we dont know if it connected and got a http 204 OK No Content, or a 500 Internal Server Error, or if your connection was outright blocked, but CURLOPT_VERBOSE would tell you.), when you get the access_token from the oauth2/token url, it comes encoded in JSON format, use json_decode to decode it. 根据文档,这一切都始于使用您的client_id和client_secret(在注册新应用时获得)以及硬编码的grant_type = client_credentialshttps://api.yelp.com/oauth2/token发出请求-并且您的代码确实做到了这一点,但是它没有正确地对client_id和client_secret进行url编码,这可能就是为什么您得到空白页的原因(这本身意味着您没有在调试curl请求时使用CURLOPT_VERBOSE进行调试) ,请始终使用CURLOPT_VERBOSE-我们不知道它是否已连接并出现http 204 OK No Content或500 Internal Server Error,或者您的连接是否被完全阻止,但CURLOPT_VERBOSE会告诉您。),当您从oauth2 / token网址,以JSON格式编码,请使用json_decode对其进行解码。

when you got that token, for further API calls, set the http header Authorization: Bearer TOKEN for autentication. 当您获得该令牌时,为了进行进一步的API调用,请设置http标头Authorization: Bearer TOKEN进行认证。

here's my code, playing around with the API, logging in (getting an authorization_token), then getting business information on dentistry-for-kids-and-adults-canyon-country . 这是我的代码,使用API​​,登录(获取authorization_token),然后在“ dentistry-for-kids-and-adults-canyon-country上获取商业信息。 unfortunately, the business search API seems broken, as it only returns 500 Internal Server Errors for everything i try. 不幸的是,商业搜索API似乎已损坏,因为它为我尝试的所有操作仅返回500内部服务器错误。 also i'm using the hhb_curl from https://github.com/divinity76/hhb_.inc.php/blob/master/hhb_.inc.php as a convenience wrapper around curl (takes care of CURLOPT_VERBOSE and giving it a file to put debug info in, setting CURLOPT_ENCODING for faster transfers, checking the return value of each curl_setopt, throwing an exception if any of the curl options could not be set and telling me exactly which option failed to be set, etc) - and if you want to testrun this code, make sure to replace client_id and client_secret, as the ones i posted here are fake (but have the same length and general structure, generated by this code https://gist.github.com/divinity76/c43e8ceb803969def0c0369b8ec6de4b ) 我也使用来自https://github.com/divinity76/hhb_.inc.php/blob/master/hhb_.inc.php的hhb_curl作为curl的便捷包装器(照顾CURLOPT_VERBOSE并将其文件提供给放入调试信息,设置CURLOPT_ENCODING以便进行更快的传输,检查每个curl_setopt的返回值,如果无法设置任何curl选项,则抛出异常,并确切地告诉我哪个选项未能设置,等等)-以及是否需要要测试运行此代码,请确保替换client_id和client_secret,因为我在此处发布的内容是假的(但具有相同的长度和通用结构,由该代码https://gist.github.com/divinity76/c43e8ceb803969def0c0369b8ec6de4b生成)

<?php
declare(strict_types = 1);
// hhb_.inc.php from https://github.com/divinity76/hhb_.inc.php/blob/master/hhb_.inc.php
require_once ('hhb_.inc.php');
$hc = new hhb_curl ( 'https://api.yelp.com/oauth2/token', true );
$hc->setopt_array ( array (
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query ( array (
                'grant_type' => 'client_credentials', // << hardcoded
                'client_id' => 'Q3sE0uuprHlZx3UbjPlnXX',
                'client_secret' => 'Q3sE0uuprHlZx3UbjPlnXXQ3sE0uuprHlZx3UbjPlnXXQ3sE0uuprHlZx3UbjPln' 
        ) ) 
) );
$hc->exec ();
hhb_var_dump ( $hc->getStdErr (), $hc->getStdOut () );
$json = $hc->getResponseBody ();
$parsed = json_decode ( $json, true );
if (! isset ( $parsed ['access_token'] )) {
    throw new \RuntimeException ( 'failed to get access token!' );
}
$access_token = $parsed ['access_token'];
$hc->setopt_array ( array (
        CURLOPT_HTTPGET => true,
        CURLOPT_URL => 'https://api.yelp.com/v3/businesses/' . urlencode ( 'dentistry-for-kids-and-adults-canyon-country' ),
        CURLOPT_HTTPHEADER => array (
                'Authorization: Bearer ' . $access_token 
        ) 
) );
$hc->exec ();
hhb_var_dump ( $hc->getStdErr (), $hc->getStdOut () );
$json = $hc->getResponseBody ();
$parsed = json_decode ( $json, true );
hhb_var_dump ( $parsed );

/*
 * the business search api seems to be severly broken, giving me 500 Internal Server Errors all the time...
 * $hc->setopt_array ( array (
 * CURLOPT_POST => true,
 * CURLOPT_POSTFIELDS => http_build_query ( array (
 * //'location' => "375 Valencia St, San Francisco"
 * //somewhere in San Francisco.
 * 'latitude'=>'37.7670169511878',
 * 'longitude'=>'-122.42184275'
 *
 * ) ),
 * CURLOPT_URL => 'https://api.yelp.com/v3/businesses/search',
 * CURLOPT_HTTPHEADER => array (
 * 'Authorization: Bearer ' . $access_token
 * )
 * ) );
 * $hc->exec ();
 * hhb_var_dump ( $hc->getStdErr (), $hc->getStdOut () );
 * $json = $hc->getResponseBody ();
 * $parsed = json_decode ( $json, true );
 * hhb_var_dump ( $parsed );
 */

also be aware that the 2nd parameter for hhb_curl::__construct is called $insecureAndComfortableByDefault - which disables SSL certificate validation (), and enables compressed transfers (as for why that may be a problem, google "ssl crime vulnerability"), and is disabled by default (in an attempt to be "secure by default"), but i generally keep it on for ease of development 还请注意,hhb_curl :: __ construct的第二个参数称为$insecureAndComfortableByDefault禁用SSL证书验证(),并启用压缩传输(至于为什么这可能是个问题,谷歌“ ssl犯罪漏洞”)并被禁用默认情况下(尝试“默认情况下是安全的”),但是我通常将其保持打开状态以便于开发

Not sure why but I was getting different errors about hhb_.inc.php so I ended-up cobbling something together myself. 不知道为什么,但是关于hhb_.inc.php我遇到了不同的错误,所以我最终自己把东西弄乱了。 It seems to work, in case there are other novices struggling out there. 如果有其他新手苦苦挣扎,这似乎很有效。 Just update client_id and client_secret with your own values. 只需使用您自己的值更新client_id和client_secret。 You get those when you register your app with Yelp as developer. 当您向Yelp注册应用程序作为开发人员时,就会得到这些。

 $postData = "grant_type=client_credentials&". "client_id=MyClientIDl94gqHAg&". "client_secret=SomEcoDehIW09e6BGuBi4NlJ43HnnHl4S7W5eoXUkB"; // GET TOKEN $curl = curl_init(); //set the url curl_setopt($curl,CURLOPT_URL, "https://api.yelp.com/oauth2/token"); //tell curl we are doing a post curl_setopt($curl,CURLOPT_POST, TRUE); //set post fields curl_setopt($curl,CURLOPT_POSTFIELDS, $postData); //tell curl we want the returned data curl_setopt($curl,CURLOPT_RETURNTRANSFER, TRUE); $result = curl_exec($curl); if($result){ $data = json_decode($result); } // GET RESTAURANT INFO curl_setopt_array($curl, array( CURLOPT_URL => "https://api.yelp.com/v3/businesses/north-india-restaurant-san-francisco", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET", CURLOPT_HTTPHEADER => array( "authorization: Bearer ".$data->access_token ), )); $response = curl_exec($curl); $err = curl_error($curl); //close connection curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { echo $response; } 

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

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