Google使用PHP跟踪API“错误请求”

时间:2015-02-26 10:16:56

标签: php google-maps google-geocoding-api

我正在使用Google Tracks API构建一个简单的基于网络的程序来跟踪具有发送纬度和经度坐标的跟踪设备的车辆。 我正在使用PHP和OAuth2 PHP library建立授权连接。

在授权并获取访问令牌后,我正在请求创建实体。虽然我似乎无法让这个工作,并继续得到一个" 400 Bad Request"响应。按照documentation中显示的所有步骤操作。

这是我的代码:

$url = 'https://www.googleapis.com/tracks/v1/entities/create/?access_token='.$parsedAuth['access_token'];

$data = array('entities' => array( "name"=> "Chevrolet" ));
$json_data = json_encode($data);
$data_length = http_build_query($data);

$options = array(
     'http' => array(
            'header'  => "Content-type: application/json\r\n". "Content-Length: " . strlen($data_length) . "\r\n",
            'method'  => 'POST',
            'content' => $json_data
        ),
    );

    $context  = stream_context_create($options);
    $response = file_get_contents($url, false, $context);

    var_dump($response);

确切错误是:"无法打开流:HTTP请求失败! HTTP / 1.0 400错误请求"

为什么我收到了错误的请求?注册这些实体并返回id的好请求是什么? 谢谢

2 个答案:

答案 0 :(得分:0)

这里给出的答案是错误的。该文档指出它必须是POST see here我的问题不在于Auth,而在于Tracks API本身。我最终开始用CURL创建请求,它运行得很好。

答案 1 :(得分:0)

请。这是带有CURL的PHP​​。它100%有效。

//Google maps tracks connection
//Get Files From PHP Library
require_once 'google-api-php-client/src/Google/autoload.php';
require_once 'google-api-php-client/src/Google/Service/MapsEngine.php';

//Set Client Credentials
$client_id = '*************.apps.googleusercontent.com'; //Client ID
$service_account_name = '************@developer.gserviceaccount.com'; //Email Address
$client_email = '*************@developer.gserviceaccount.com';
$private_key = file_get_contents('************.p12');
$scopes = array('https://www.googleapis.com/auth/tracks');

//Create Client
$client = new Google_Client();

$client->setApplicationName("Client_Library_Examples");

//Send Credentials
$credentials = new Google_Auth_AssertionCredentials(
    $client_email,
    $scopes,
    $private_key
);
$client->setAssertionCredentials($credentials);

if ($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($credentials);
}

if (isset($_SESSION['service_token'])) {
  $client->setAccessToken($_SESSION['service_token']);
}

$client->setAssertionCredentials($credentials);

$_SESSION['service_token'] = $client->getAccessToken();
foreach ($_SESSION as $key=> $value) {
    $vars = json_decode($value);
}
$parsedAuth = (array) $vars;
$token = $parsedAuth['access_token'];
//all functions in the program use this auth token- It should be global for easy accesses. 
global $token;


function createEntities(){
    global $token;
    $url = 'https://www.googleapis.com/tracks/v1/entities/create/?access_token='.$token;

    //FIX ME: fields is temporarily hard coded- should be brought from DB
    $fields = array(
                'entities' => array(
                    'name' => "DemoTruck",
                    'type' => "AUTOMOBILE"
                    ),
        );

    //json string the data for the POST
    $query_string = '';
    foreach($fields as $key => $array) {
        $query_string .= '{"' . urlencode($key).'":[{';
        foreach($array as $k => $v) {
            $query_string .= '"' . urlencode($k) . '":"' . urlencode($v) . '",';
        }
    }
    $str = rtrim($query_string , ',');
    $fstr = $str.'}]}';

    $length = strlen( $fstr );
    //open connection
    $ch = curl_init();
    //test connection
    if (FALSE === $ch)
    throw new Exception('failed to initialize');

    //set options
    $header = array('Content-type: application/json');
    curl_setopt($ch,CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch,CURLOPT_POSTFIELDS, $fstr);

    $result = curl_exec($ch);

    //dump in case of error
    if (FALSE === $result){
        var_dump( curl_error($ch) );
        var_dump( curl_getinfo($ch) ); 
    } 

    //close connection
    curl_close($ch);
}