Google Geocode with PHP - php

I'm trying to get latitude and longitude from Google's Geocode API. The $url I'm using outputs the correct JSON however something in my script isn't working correctly. It's not outputting the $lati & $longi variables. Please check see the script below:
PHP:
<?php
$address = 'Tempe AZ';
$address = urlencode($address);
$url = "https://maps.google.com/maps/api/geocode/json?sensor=false&address={$address}";
$resp_json = file_get_contents($url);
$resp = json_decode($resp_json, true);
if ($resp['status'] == 'OK') {
// get the important data
$lati = $resp['results'][0]['geometry']['location']['lat'];
$longi = $resp['results'][0]['geometry']['location']['lng'];
echo $lati;
echo $longi;
} else {
return false;
}
?>

I brought in the Guzzle http package at the top of my Laravel file/class: use GuzzleHttp\Client;
Then, to take an address and convert it to lat and lng to save with PHP/Laravel and Google Maps API, I added this code in my save() method:
// get latitude and longitude of address with Guzzle http package and Google Maps geocode API
$client = new Client(); // GuzzleHttp\Client
$baseURL = 'https://maps.googleapis.com/maps/api/geocode/json?address=';
$addressURL = urlencode(request('street')) . ',' . urlencode(request('city')) . ',' . urlencode(request('state')) . '&key=' . env('GOOGLE_MAPS_API_KEY');
$url = $baseURL . $addressURL;
$request = $client->request('GET', $url);
$response = $request->getBody()->getContents();
$response = json_decode($response);
$latitude = $response->results[0]->geometry->location->lat;
$longitude = $response->results[0]->geometry->location->lng;

It turned out to be a proxy issue. This thread helped: Using proxy with file_get_contents
Added this:
$opts = array(
'http' => array(
'method' => "GET",
'header' => "Accept-language: en\r\n".
"Cookie: foo=bar\r\n",
'proxy' => 'tcp://proxy.proxy.com:8080',
)
);
$context = stream_context_create($opts);
// open the file using the HTTP headers set above
$file = file_get_contents($url, false, $context);

Your script works for me too. Maybe you will get an error calling:
$resp_json = file_get_contents($url);.
If that happens you should do this:
$resp_json = #file_get_contents($url);
if ($resp_json === FALSE) {
///logic for exception
} else {
///do your logic hear
}

Related

ups tracking api - set response language

I have a php solution for ups tracking.
The response which I get from UPS using the language "english"
Is there an way to get another language for the response?
This is my code from the ups developer documentation:
This is my code from the ups developer documentation:
This is my code from the ups developer documentation:
This is my code from the ups developer documentation:This is my code from the ups developer documentation:
// Configuration
$accessLicenseNumber = "xxx";
$userId = "xxx";
$password = "xxx";
$endpointurl = 'https://onlinetools.ups.com/ups.app/xml/Track';
try {
// Create AccessRequest XMl
$accessRequestXML = new SimpleXMLElement ( "<AccessRequest></AccessRequest>" );
$accessRequestXML->addChild ( "AccessLicenseNumber", $accessLicenseNumber );
$accessRequestXML->addChild ( "UserId", $userId );
$accessRequestXML->addChild ( "Password", $password );
// Create TrackRequest XMl
$trackRequestXML = new SimpleXMLElement ( "<TrackRequest></TrackRequest >" );
$request = $trackRequestXML->addChild ( 'Request' );
$request->addChild ( "RequestAction", "Track" );
$request->addChild ( "RequestOption", "activity" );
$trackRequestXML->addChild ( "TrackingNumber", "xxx" );
$requestXML = $accessRequestXML->asXML () . $trackRequestXML->asXML ();
$form = array (
'http' => array (
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $requestXML
)
);
// get request
$request = stream_context_create ( $form );
$browser = fopen ( $endpointurl, 'rb', false, $request );
if (! $browser) {
throw new Exception ( "Connection failed." );
}
// get response
$response = stream_get_contents ( $browser );
fclose ( $browser );
if ($response == false) {
throw new Exception ( "Bad data." );
} else {
// get response status
$resp = new SimpleXMLElement ( $response );
}
Header ( 'Content-type: text/xml' );
} catch ( Exception $ex ) {}
}
You can not do this via XML, you need to use WSDL (SOAP) or JSON.
You can use the Local TAG in /TrackRequest/Locale => <v3:Locale>it_IT</v3:Locale>
WSDL (SOAP) Request
url for test webservices https://wwwcie.ups.com/webservices/Track
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:v1="http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0"
xmlns:v3="http://www.ups.com/XMLSchema/XOLTWS/Track/v2.0"
xmlns:v11="http://www.ups.com/XMLSchema/XOLTWS/Common/v1.0">
<soapenv:Header>
<v1:UPSSecurity>
<v1:UsernameToken>
<v1:Username>USERID</v1:Username>
<v1:Password>PASSWORD</v1:Password>
</v1:UsernameToken>
<v1:ServiceAccessToken>
<v1:AccessLicenseNumber>API KEY</v1:AccessLicenseNumber>
</v1:ServiceAccessToken>
</v1:UPSSecurity>
</soapenv:Header>
<soapenv:Body>
<v3:TrackRequest>
<v11:Request>
<v11:RequestOption>1</v11:RequestOption>
<v11:TransactionReference>
<v11:CustomerContext>Your Test Case Summary Description</v11:CustomerContext>
</v11:TransactionReference>
</v11:Request>
<v3:Locale>it_IT</v3:Locale>
<v3:InquiryNumber>TRACKING NUMBER</v3:InquiryNumber>
</v3:TrackRequest>
</soapenv:Body>
</soapenv:Envelope>
I did some tests using the Tracking Number of tests and with those it does not work.
I then used a true tracking code sent to my country (Italy) and it works
RESPONSE WSDL(SOAP)
..........
<trk:Status>
<trk:Type>M</trk:Type>
<trk:Description>Ordine elaborato: Pronto per UPS</trk:Description>
<trk:Code>MP</trk:Code>
</trk:Status>
..........
I used Postman to make requests
You can also use JSON (See the guide on the UPS website)
This is the example of a soap client from the development kit UPS
<?php
//Configuration
$access = " Add License Key Here";
$userid = " Add User Id Here";
$passwd = " Add Password Here";
$wsdl = " Add Wsdl File Here ";
$operation = "ProcessTrack";
$endpointurl = ' Add URL Here';
$outputFileName = "XOLTResult.xml";
function processTrack()
{
//create soap request
$req['RequestOption'] = '15';
$tref['CustomerContext'] = 'Add description here';
$req['TransactionReference'] = $tref;
$request['Request'] = $req;
$request['InquiryNumber'] = '';
$request['TrackingOption'] = '02';
echo "Request.......\n";
print_r($request);
echo "\n\n";
return $request;
}
try
{
$mode = array
(
'soap_version' => 'SOAP_1_1', // use soap 1.1 client
'trace' => 1
);
// initialize soap client
$client = new SoapClient($wsdl , $mode);
//set endpoint url
$client->__setLocation($endpointurl);
//create soap header
$usernameToken['Username'] = $userid;
$usernameToken['Password'] = $passwd;
$serviceAccessLicense['AccessLicenseNumber'] = $access;
$upss['UsernameToken'] = $usernameToken;
$upss['ServiceAccessToken'] = $serviceAccessLicense;
$header = new SoapHeader('http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0','UPSSecurity',$upss);
$client->__setSoapHeaders($header);
//get response
$resp = $client->__soapCall($operation ,array(processTrack()));
//get status
echo "Response Status: " . $resp->Response->ResponseStatus->Description ."\n";
//save soap request and response to file
$fw = fopen($outputFileName , 'w');
fwrite($fw , "Request: \n" . $client->__getLastRequest() . "\n");
fwrite($fw , "Response: \n" . $client->__getLastResponse() . "\n");
fclose($fw);
}
catch(Exception $ex)
{
print_r ($ex);
}
?>

ExactOnline API en OData

I am struggling with the API of Exact Online.
Using this example code to retrieve information of the server:
$response = $exactApi->sendRequest("crm/Accounts?$filter=substringof('test', Name) eq true', 'get');
Above returns a Bad Request. Anyone got a clue how to fix this?
The function 'send request':
public function sendRequest($url, $method, $payload = NULL)
{
if ($payload && !is_array($payload)) {
throw new ErrorException('Payload is not valid.');
}
if (!$accessToken = $this->initAccessToken()) {
throw new ErrorException('Access token was not initialized');
}
$requestUrl = $this->getRequestUrl($url, array(
'access_token' => $accessToken
));
// Base cURL option
$curlOpt = array();
$curlOpt[CURLOPT_URL] = $requestUrl;
$curlOpt[CURLOPT_RETURNTRANSFER] = TRUE;
$curlOpt[CURLOPT_SSL_VERIFYPEER] = TRUE;
$curlOpt[CURLOPT_HEADER] = false;
if ($method == self::METHOD_POST) {
$curlOpt[CURLOPT_HTTPHEADER] = array(
'Content-Type:application/json',
'access_token:' . $accessToken,
'Content-length: ' . strlen(json_encode($payload))
);
$curlOpt[CURLOPT_POSTFIELDS] = json_encode($payload);
$curlOpt[CURLOPT_CUSTOMREQUEST] = strtoupper($method);
}
$curlOpt[CURLOPT_ENCODING] = '';
$curlHandle = curl_init();
curl_setopt_array($curlHandle, $curlOpt);
return curl_exec($curlHandle);
}
Tested this.
crm/Accounts?$select=Name&$filter=substringof('Lennert',Name) : OK
crm/Accounts?$select=Name&$filter=substringof('Lennert', Name) eq true : NOK, error 400
crm/Accounts?\$select=Name&$filter=substringof(Name, 'Lennert') eq true : NOK, error 400
First option works but is not according to OData v2 specifications which Exact Online uses. Will be discussed with development to see what can be done for this.

Google Tracks API "Bad Request" using PHP

I am using Google Tracks API to build a simple web based program to track a vehicle that has a tracking device sending latitude and longitude coordinates.
I am using PHP and the OAuth2 PHP library to make an authorized connection.
After authorizing and getting an access token I am making a request to create entities. Though I can't seem to get this working and keep getting a "400 Bad Request" response. Following all the steps shown in the documentation.
Here is my code:
$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);
Exact Error is: "failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request"
Why am I getting a bad request? What would be a good request that will register these entities and return id's?
Thank you
The answer given here is wrong. The documentation states that it must be a POST see here My issue was not with the Auth but with the Tracks API itself. I ended up moving to create the request with CURL and it works just fine.
Please. This is PHP with CURL. It works 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);
}

How to POST via Reddit API (addcomment)

I've been able to successfully log a user in and return their details. The next step is to get them to post a comment via my app.
I tried modifying code from the reddit-php-sdk -- https://github.com/jcleblanc/reddit-php-sdk/blob/master/reddit.php -- but I can't get it to work.
My code is as follows:
function addComment($name, $text, $token){
$response = null;
if ($name && $text){
$urlComment = "https://ssl.reddit.com/api/comment";
$postData = sprintf("thing_id=%s&text=%s",
$name,
$text);
$response = runCurl($urlComment, $token, $postData);
}
return $response;
}
function runCurl($url, $token, $postVals = null, $headers = null, $auth = false){
$ch = curl_init($url);
$auth_mode = 'oauth';
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_TIMEOUT => 10
);
$headers = array("Authorization: Bearer {$token}");
$options[CURLOPT_HEADER] = false;
$options[CURLINFO_HEADER_OUT] = false;
$options[CURLOPT_HTTPHEADER] = $headers;
if (!empty($_SERVER['HTTP_USER_AGENT'])){
$options[CURLOPT_USERAGENT] = $_SERVER['HTTP_USER_AGENT'];
}
if ($postVals != null){
$options[CURLOPT_POSTFIELDS] = $postVals;
$options[CURLOPT_CUSTOMREQUEST] = "POST";
}
curl_setopt_array($ch, $options);
$apiResponse = curl_exec($ch);
$response = json_decode($apiResponse);
//check if non-valid JSON is returned
if ($error = json_last_error()){
$response = $apiResponse;
}
curl_close($ch);
return $response;
}
$thing_id = 't2_'; // Not the actual thing id
$perma_id = '2daoej'; // Not the actual perma id
$name = $thing_id . $perma_id;
$text = "test text";
$reddit_access_token = $_SESSION['reddit_access_token'] // This is set after login
addComment($name, $text, $reddit_access_token);
The addComment function puts the comment together according to their API -- http://www.reddit.com/dev/api
addComment then calls runCurl to make the request. My guess is that the curl request is messed up because I'm not receiving any response whatsoever. I'm not getting any errors so I'm not sure what's going wrong. Any help would really be appreciated. Thanks!
If you are using your own oAuth solution, I would suggest using the SDK as I said in my comment, but extend it to overwrite the construct method.
class MyReddit extends reddit {
public function __construct()
{
//set API endpoint
$this->apiHost = ENDPOINT_OAUTH;
}
public function setAuthVars($accessToken, $tokenType)
{
$this->access_token = $accessToken;
$this->token_type = $tokenType;
//set auth mode for requests
$this->auth_mode = 'oauth';
}
}
You just need to make sure that you call setAuthVars before running any api calls.

bing search api php filter

i'm using the following php to connect to bing api:
how can i add filter (Size:Small)?
the code is from bing documentation and it works fine.
i'm using this code to connect to bing and redirect the response to an iOS app.
please help...
<?php
{
$accountKey = ‘XXXXXXXXX’;
$auth = base64_encode("$accountKey:$accountKey");
$data = array(
'http' => array(
'request_fulluri' => true,
'ignore_errors' => true,
'header' => "Authorization: Basic " . $auth));
$context = stream_context_create($data);
$query = isset($_GET['q']) ? $_GET['q'] : htmlspecialchars($_GET["searchtext"]);
$serviceOp = isset($_GET['sop']) ? $_GET['sop'] : 'Web';
$market = isset($_GET['market']) ? $_GET['market'] : 'en-us';
$ServiceRootURL = 'https://api.datamarket.azure.com/Bing/Search/';
$WebSearchURL = $ServiceRootURL . 'Image?$format=json&Image.Filters=+filterui:imagesize-large+filterui:photo-photo+filterui:face-face&Query=';
$request = $WebSearchURL . urlencode( '\'' . $query. '\'') ;
// Get the response from Bing.
$response = file_get_contents($request, 0, $context);
$jsonobj = json_decode($response);
// echo('<ul ID="resultList">');
header('Content-Type: application/json');
echo($response);
?>
First remove all image filters from $WebSearchURL variable,
and then add your image filters with this way:
$request = $WebSearchURL . urlencode( '\'' . $query. '\'').'&ImageFilters=';
$request = $request . urlencode( '\'' .'Size:Large+Face:Face'. '\'');
Hope it works with you :)

Categories