quickbooks online interaction - integration

I have a web app that I need to communicate with quickbooks online edition. I am able connect and receive data. The problem is is that the responce back that i get is not in a xml format or even better would be in json formate. How can I get it to respond back in one of those formats? Here is my code:
function request($xml, $certificate = null, $debug = false){
$ch = curl_init();
$header[] = 'Content-Type: application/x-qbxml';
$header[] = 'Content-Length: ' . strlen($xml);
$params = array();
$params[CURLOPT_HTTPHEADER] = $header;
$params[CURLOPT_POST] = true;
$params[CURLOPT_RETURNTRANSFER] = true;
$params[CURLOPT_URL] = $this->gateway;
$params[CURLOPT_TIMEOUT] = 30;
$params[CURLOPT_POSTFIELDS] = $xml;
$params[CURLOPT_VERBOSE] = $debug;
$params[CURLOPT_HEADER] = true;
// This is only for the HOSTED security model
if (file_exists($certificate))
{
$params[CURLOPT_SSL_VERIFYPEER] = false;
$params[CURLOPT_SSLCERT] = $certificate;
}
// Some Windows servers will fail with SSL errors unless we turn this off
$params[CURLOPT_SSL_VERIFYPEER] = false;
$params[CURLOPT_SSL_VERIFYHOST] = 0;
// Diagnostic information: https://merchantaccount.quickbooks.com/j/diag/http
// curl_setopt($ch, CURLOPT_INTERFACE, '<myipaddress>');
$ch = curl_init();
curl_setopt_array($ch, $params);
$response = curl_exec($ch);
if (curl_errno($ch))
{
$errnum = curl_errno($ch);
$errmsg = curl_error($ch);
_log('CURL error: ' . $errnum . ': ' . $errmsg, $debug);
return false;
}
// Close the connection
#curl_close($ch);
// Remove the HTTP headers from the response
$pos = strpos($response, "\r\n\r\n");
$response = ltrim(substr($response, $pos));
return $response;
}
function item_list(){
$xml =
'<?xml version="1.0"?>
<?qbxml version="6.0"?>
<QBXML>
<SignonMsgsRq>
<SignonTicketRq>
<ClientDateTime>' . date('Y-m-d') . 'T' . date('H:i:s') . '</ClientDateTime>
<SessionTicket>' . $this->session . '</SessionTicket>
<Language>English</Language>
<AppID>' . $this->application_id . '</AppID>
<AppVer>1</AppVer>
</SignonTicketRq>
</SignonMsgsRq>
<QBXMLMsgsRq onError="stopOnError">
<ItemQueryRq>
<OwnerID>0</OwnerID>
</ItemQueryRq>
</QBXMLMsgsRq>
</QBXML>';
$response = $this->request($xml, null, true);
echo $response;
}
Thanks
Here my xml request:
$xml =
'
' . date('Y-m-d') . 'T' . date('H:i:s') . '
' . $this->session . '
English
' . $this->application_id . '
1
0
</QBXMLMsgsRq>
</QBXML>';
Here is my responce:
2013-04-12T12:28:11 V1-115-Q03kydq32h22tnfqnd5izf:689712285 1 2013-04-10T06:02:40 2013-04-10T06:02:40 0 Sales Sales 0 0 1 Sales 2 2013-04-10T21:20:43 2013-04-10T21:20:43 0 test product test product 0 0 1 Sales

My stupid mistake. I was echoing my result to browser which interpreted xml tags as html tags. I used $xml = simplexml_load_string($response); print_r($xml); to view response in browser.

Related

Using Google Open ID Connect to Access User's Gmail Account

How can I run a google apps script API on multiple gmail accounts? I currently have a script that accesses a user's gmail when it is authorized by the two files shown below. I store the refresh token for the client once the code asks for authorization. However, how can I use Open ID to get authorization for various users' accounts? Do I need to store a client id in addition to a refresh token to gain authorization for a user's gmail account? Thanks for taking the time to help in advance!
read_email.php
<?php
require_once '../google-api-php-client/src/Google/autoload.php';
function getEmails (){
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->setScopes(array(
'https://mail.google.com/'
));
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
if($client->isAccessTokenExpired()){
header('Location: http://' . $_SERVER['HTTP_HOST'] . '/email_database/php/oauth2callback.php');
}
// Get the API client and construct the service object.
$service = new Google_Service_Script($client);
$scriptId = '**********************';
// Create an execution request object.
$request = new Google_Service_Script_ExecutionRequest();
set_time_limit(0);
$request->setFunction('test');
$response = $service->scripts->run($scriptId, $request);
$response = $response->getResponse();
$response = $response['result'];
return ($response);
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/email_database/php/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
}
?>
oauth2callback.php
<?php
require_once '../google-api-php-client/src/Google/autoload.php';
include 'functions.php';
$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/email_database/dashboard/php/oauth2callback.php');
$client->setScopes(array(
'https://mail.google.com/'
));
$client->setAccessType('offline');
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/email_database/dashboard/php/read_email.php';
$username = $_SESSION['username'];
$user = getUser($username);
if($user['refresh_token'] == null){
if (! isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
//echo $_GET['code'];
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$google_token = json_decode($_SESSION['access_token']);
print_r($google_token);
$refresh_token = $google_token->refresh_token;
addRefreshToken($username,$refresh_token);
//header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
}
else {
$refresh_token = $user['refresh_token'];
$client->refreshToken($refresh_token);
$_SESSION['access_token']= $client->getAccessToken();
// header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
?>

LinkedIn API - Setting user status saying unauthorised

So I've been following through various tutorials and documents to get this working and am really struggling. These are the files required for it to work:
Required Files
auth.php
<?php
session_start();
$config['base_url'] = '';
$config['callback_url'] = '';
$config['linkedin_access'] = '';
$config['linkedin_secret'] = '';
include_once "linkedin.php";
# The first step is to initialize with your consumer key and secret. We'll use an out-of-band oauth_callback.
$linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['callback_url'] );
//$linkedin->debug = true;
# Now we retrieve a request token. It will be set as $linkedin->request_token.
$linkedin->getRequestToken();
$_SESSION['requestToken'] = serialize($linkedin->request_token);
# With a request token in hand, we can generate an authorization URL, which we'll direct the user to.
//echo "Authorization URL: " . $linkedin->generateAuthorizeUrl() . "\n\n";
header("Location: " . $linkedin->generateAuthorizeUrl()); ?>
demo.php
This is the script that I get after signup:
<?php
session_start();
$config['base_url'] = 'http://xxx/linkedin/auth.php';
$config['callback_url'] = 'http://xxx/linkedin/demo.php';
$config['linkedin_access'] = '';
$config['linkedin_secret'] = '';
include_once "linkedin.php";
# The first step is to initialize with your consumer key and secret. We'll use an out-of-band oauth_callback.
$linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['callback_url'] );
//$linkedin->debug = true; if (isset($_REQUEST['oauth_verifier'])){
$_SESSION['oauth_verifier'] = $_REQUEST['oauth_verifier'];
$linkedin->request_token = unserialize($_SESSION['requestToken']);
$linkedin->oauth_verifier = $_SESSION['oauth_verifier'];
$linkedin->getAccessToken($_REQUEST['oauth_verifier']);
$_SESSION['oauth_access_token'] = serialize($linkedin->access_token);
header("Location: " . $config['callback_url']);
exit;} else{
$linkedin->request_token = unserialize($_SESSION['requestToken']);
$linkedin->oauth_verifier = $_SESSION['oauth_verifier'];
$linkedin->access_token = unserialize($_SESSION['oauth_access_token']);}
# You now have a $linkedin->access_token and can make calls on behalf of the current member.
$xml_response = $linkedin->getProfile("~:(id,first-name,last-name,headline,picture-url)");
$id = $linkedin->getProfile('~:(id)');
$fname = $linkedin->getProfile('~:(first-name)');
$lname = $linkedin->getProfile('~:(last-name)');
$headline = $linkedin->getProfile('~:(headline)');
$picture = $linkedin->getProfile('~:(picture-url)');
$id = trim(strip_tags($id));
$fname = trim(strip_tags($fname));
$lname = trim(strip_tags($lname));
$headline = trim(strip_tags($headline));
$picture = trim(strip_tags($picture)); ?>
linkedin.php
This is linkedin library:
<?php require_once("OAuth.php"); class LinkedIn {
public $base_url = "http://api.linkedin.com";
public $secure_base_url = "https://api.linkedin.com";
public $oauth_callback = "oob";
public $consumer;
public $request_token;
public $access_token;
public $oauth_verifier;
public $signature_method;
public $request_token_path;
public $access_token_path;
public $authorize_path;
function __construct($consumer_key, $consumer_secret, $oauth_callback = NULL)
{
if($oauth_callback) {
$this->oauth_callback = $oauth_callback;
}
$this->consumer = new OAuthConsumer($consumer_key, $consumer_secret, $this->oauth_callback);
$this->signature_method = new OAuthSignatureMethod_HMAC_SHA1();
$this->request_token_path = $this->secure_base_url . "/uas/oauth/requestToken";
$this->access_token_path = $this->secure_base_url . "/uas/oauth/accessToken";
$this->authorize_path = $this->secure_base_url . "/uas/oauth/authorize";
}
function getRequestToken()
{
$consumer = $this->consumer;
$request = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $this->request_token_path);
$request->set_parameter("oauth_callback", $this->oauth_callback);
$request->sign_request($this->signature_method, $consumer, NULL);
$headers = Array();
$url = $request->to_url();
$response = $this->httpRequest($url, $headers, "GET");
parse_str($response, $response_params);
$this->request_token = new OAuthConsumer($response_params['oauth_token'], $response_params['oauth_token_secret'], 1);
}
function generateAuthorizeUrl()
{
$consumer = $this->consumer;
$request_token = $this->request_token;
return $this->authorize_path . "?oauth_token=" . $request_token->key;
}
function getAccessToken($oauth_verifier)
{
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->request_token, "GET", $this->access_token_path);
$request->set_parameter("oauth_verifier", $oauth_verifier);
$request->sign_request($this->signature_method, $this->consumer, $this->request_token);
$headers = Array();
$url = $request->to_url();
$response = $this->httpRequest($url, $headers, "GET");
parse_str($response, $response_params);
$this->access_token = new OAuthConsumer($response_params['oauth_token'], $response_params['oauth_token_secret'], 1);
}
function getProfile($resource = "~")
{
$profile_url = $this->base_url . "/v1/people/" . $resource;
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "GET", $profile_url);
$request->sign_request($this->signature_method, $this->consumer, $this->access_token);
$auth_header = $request->to_header("https://api.linkedin.com"); # this is the realm
# This PHP library doesn't generate the header correctly when a realm is not specified.
# Make sure there is a space and not a comma after OAuth
// $auth_header = preg_replace("/Authorization\: OAuth\,/", "Authorization: OAuth ", $auth_header);
// # Make sure there is a space between OAuth attribute
// $auth_header = preg_replace('/\"\,/', '", ', $auth_header);
// $response will now hold the XML document
$response = $this->httpRequest($profile_url, $auth_header, "GET");
return $response;
}
function setStatus($status)
{
$profile_url = $this->base_url . "/v1/people/~";
$status_url = $this->base_url . "/v1/people/~/current-status";
echo "Setting status...\n";
$xml = "<current-status>" . htmlspecialchars($status, ENT_NOQUOTES, "UTF-8") . "</current-status>";
echo $xml . "\n";
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "PUT", $status_url);
$request->sign_request($this->signature_method, $this->consumer, $this->access_token);
$auth_header = $request->to_header("https://api.linkedin.com");
$response = $this->httpRequest($profile_url, $auth_header, "GET");
return $response;
}
# Parameters should be a query string starting with "?"
# Example search("?count=10&start=10&company=LinkedIn");
function search($parameters)
{
$search_url = $this->base_url . "/v1/people-search:(people:(id,first-name,last-name,picture-url,site-standard-profile-request,headline),num-results)" . $parameters;
//$search_url = $this->base_url . "/v1/people-search?keywords=facebook";
echo "Performing search for: " . $parameters . "<br />";
echo "Search URL: $search_url <br />";
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "GET", $search_url);
$request->sign_request($this->signature_method, $this->consumer, $this->access_token);
$auth_header = $request->to_header("https://api.linkedin.com");
$response = $this->httpRequest($search_url, $auth_header, "GET");
return $response;
}
function httpRequest($url, $auth_header, $method, $body = NULL)
{
if (!$method) {
$method = "GET";
};
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array($auth_header)); // Set the headers.
if ($body) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_HTTPHEADER, array($auth_header, "Content-Type: text/xml;charset=utf-8"));
}
$data = curl_exec($curl);
curl_close($curl);
return $data;
}}
The Problem
Trying to set the status
To set the status update I have tried using this in the demo.php file:
$setStatus = "Testing API";
$statusResponse = $linkedin->setStatus("~:($setStatus)");
echo '<pre>';
var_dump($statusResponse);
echo '</pre>';
But it is giving me this error:
Setting status... ~:(Testing API)
string(343) "
401
1407931633217
DW74ALZZVN
0
[unauthorized]. OAU:xxxxxxxxxxxxxxxxxx|xxxxxxxxxxxxx|*01|*01:1407931633:eyA6PiJzKUJixQLLtaQL90wppHI=
"
P.S: I x'd out the key there, but they are correct and the rest of the script works with them.
How do I set the status of the authorised account? So I've been following through various tutorials and documents to get this working and am really struggling. These are the files required for it to work:
Required Files
auth.php
<?php
session_start();
$config['base_url'] = '';
$config['callback_url'] = '';
$config['linkedin_access'] = '';
$config['linkedin_secret'] = '';
include_once "linkedin.php";
# The first step is to initialize with your consumer key and secret. We'll use an out-of-band oauth_callback.
$linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['callback_url'] );
//$linkedin->debug = true;
# Now we retrieve a request token. It will be set as $linkedin->request_token.
$linkedin->getRequestToken();
$_SESSION['requestToken'] = serialize($linkedin->request_token);
# With a request token in hand, we can generate an authorization URL, which we'll direct the user to.
//echo "Authorization URL: " . $linkedin->generateAuthorizeUrl() . "\n\n";
header("Location: " . $linkedin->generateAuthorizeUrl()); ?>
demo.php
This is the script that I get after signup:
<?php
session_start();
$config['base_url'] = 'http://xxx/linkedin/auth.php';
$config['callback_url'] = 'http://xxx/linkedin/demo.php';
$config['linkedin_access'] = '';
$config['linkedin_secret'] = '';
include_once "linkedin.php";
# The first step is to initialize with your consumer key and secret. We'll use an out-of-band oauth_callback.
$linkedin = new LinkedIn($config['linkedin_access'], $config['linkedin_secret'], $config['callback_url'] );
//$linkedin->debug = true; if (isset($_REQUEST['oauth_verifier'])){
$_SESSION['oauth_verifier'] = $_REQUEST['oauth_verifier'];
$linkedin->request_token = unserialize($_SESSION['requestToken']);
$linkedin->oauth_verifier = $_SESSION['oauth_verifier'];
$linkedin->getAccessToken($_REQUEST['oauth_verifier']);
$_SESSION['oauth_access_token'] = serialize($linkedin->access_token);
header("Location: " . $config['callback_url']);
exit;} else{
$linkedin->request_token = unserialize($_SESSION['requestToken']);
$linkedin->oauth_verifier = $_SESSION['oauth_verifier'];
$linkedin->access_token = unserialize($_SESSION['oauth_access_token']);}
# You now have a $linkedin->access_token and can make calls on behalf of the current member.
$xml_response = $linkedin->getProfile("~:(id,first-name,last-name,headline,picture-url)");
$id = $linkedin->getProfile('~:(id)');
$fname = $linkedin->getProfile('~:(first-name)');
$lname = $linkedin->getProfile('~:(last-name)');
$headline = $linkedin->getProfile('~:(headline)');
$picture = $linkedin->getProfile('~:(picture-url)');
$id = trim(strip_tags($id));
$fname = trim(strip_tags($fname));
$lname = trim(strip_tags($lname));
$headline = trim(strip_tags($headline));
$picture = trim(strip_tags($picture)); ?>
linkedin.php
This is linkedin library:
<?php require_once("OAuth.php"); class LinkedIn {
public $base_url = "http://api.linkedin.com";
public $secure_base_url = "https://api.linkedin.com";
public $oauth_callback = "oob";
public $consumer;
public $request_token;
public $access_token;
public $oauth_verifier;
public $signature_method;
public $request_token_path;
public $access_token_path;
public $authorize_path;
function __construct($consumer_key, $consumer_secret, $oauth_callback = NULL)
{
if($oauth_callback) {
$this->oauth_callback = $oauth_callback;
}
$this->consumer = new OAuthConsumer($consumer_key, $consumer_secret, $this->oauth_callback);
$this->signature_method = new OAuthSignatureMethod_HMAC_SHA1();
$this->request_token_path = $this->secure_base_url . "/uas/oauth/requestToken";
$this->access_token_path = $this->secure_base_url . "/uas/oauth/accessToken";
$this->authorize_path = $this->secure_base_url . "/uas/oauth/authorize";
}
function getRequestToken()
{
$consumer = $this->consumer;
$request = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $this->request_token_path);
$request->set_parameter("oauth_callback", $this->oauth_callback);
$request->sign_request($this->signature_method, $consumer, NULL);
$headers = Array();
$url = $request->to_url();
$response = $this->httpRequest($url, $headers, "GET");
parse_str($response, $response_params);
$this->request_token = new OAuthConsumer($response_params['oauth_token'], $response_params['oauth_token_secret'], 1);
}
function generateAuthorizeUrl()
{
$consumer = $this->consumer;
$request_token = $this->request_token;
return $this->authorize_path . "?oauth_token=" . $request_token->key;
}
function getAccessToken($oauth_verifier)
{
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->request_token, "GET", $this->access_token_path);
$request->set_parameter("oauth_verifier", $oauth_verifier);
$request->sign_request($this->signature_method, $this->consumer, $this->request_token);
$headers = Array();
$url = $request->to_url();
$response = $this->httpRequest($url, $headers, "GET");
parse_str($response, $response_params);
$this->access_token = new OAuthConsumer($response_params['oauth_token'], $response_params['oauth_token_secret'], 1);
}
function getProfile($resource = "~")
{
$profile_url = $this->base_url . "/v1/people/" . $resource;
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "GET", $profile_url);
$request->sign_request($this->signature_method, $this->consumer, $this->access_token);
$auth_header = $request->to_header("https://api.linkedin.com"); # this is the realm
# This PHP library doesn't generate the header correctly when a realm is not specified.
# Make sure there is a space and not a comma after OAuth
// $auth_header = preg_replace("/Authorization\: OAuth\,/", "Authorization: OAuth ", $auth_header);
// # Make sure there is a space between OAuth attribute
// $auth_header = preg_replace('/\"\,/', '", ', $auth_header);
// $response will now hold the XML document
$response = $this->httpRequest($profile_url, $auth_header, "GET");
return $response;
}
function setStatus($status)
{
$profile_url = $this->base_url . "/v1/people/~";
$status_url = $this->base_url . "/v1/people/~/current-status";
echo "Setting status...\n";
$xml = "<current-status>" . htmlspecialchars($status, ENT_NOQUOTES, "UTF-8") . "</current-status>";
echo $xml . "\n";
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "PUT", $status_url);
$request->sign_request($this->signature_method, $this->consumer, $this->access_token);
$auth_header = $request->to_header("https://api.linkedin.com");
$response = $this->httpRequest($profile_url, $auth_header, "GET");
return $response;
}
# Parameters should be a query string starting with "?"
# Example search("?count=10&start=10&company=LinkedIn");
function search($parameters)
{
$search_url = $this->base_url . "/v1/people-search:(people:(id,first-name,last-name,picture-url,site-standard-profile-request,headline),num-results)" . $parameters;
//$search_url = $this->base_url . "/v1/people-search?keywords=facebook";
echo "Performing search for: " . $parameters . "<br />";
echo "Search URL: $search_url <br />";
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->access_token, "GET", $search_url);
$request->sign_request($this->signature_method, $this->consumer, $this->access_token);
$auth_header = $request->to_header("https://api.linkedin.com");
$response = $this->httpRequest($search_url, $auth_header, "GET");
return $response;
}
function httpRequest($url, $auth_header, $method, $body = NULL)
{
if (!$method) {
$method = "GET";
};
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array($auth_header)); // Set the headers.
if ($body) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_HTTPHEADER, array($auth_header, "Content-Type: text/xml;charset=utf-8"));
}
$data = curl_exec($curl);
curl_close($curl);
return $data;
}}
The Problem
Trying to set the staus
To set the status update I have tried using this in the demo.php:
$setStatus = "Testing API";
$statusResponse = $linkedin->setStatus("~:($setStatus)");
echo '<pre>';
var_dump($statusResponse);
echo '</pre>';
But it is giving me this error:
Setting status... ~:(Testing API)
string(343) "
401
1407931633217
DW74ALZZVN
0
[unauthorized]. OAU:xxxxxxxxxxxxxxxxxx|xxxxxxxxxxxxx|*01|*01:1407931633:eyA6PiJzKUJixQLLtaQL90wppHI=
"
P.S: I x'd out the key there, but they are correct and the rest of the script works with them.
How do I set the status of the authorised account?
Not sure if it is still relevant, and the current-status API is deprecated, but the line:
$xml = "<current-status>" . htmlspecialchars($status, ENT_NOQUOTES, "UTF-8") . "</current-status>";
needs to be changed to:
$xml = "" . htmlspecialchars($status, ENT_NOQUOTES, "UTF-8") . "";

Changing from Google maps api v2 to v3

I've been using Google geocoding v3 for about 6 months but all of a sudden it's stopped working (I get a 610 error). It's only stopped in the last week or so.
Then I came across this (see the pink box at the top of the page!): https://developers.google.com/maps/documentation/geocoding/v2/
I've read through all the documentation and not sure where to start!
I'm hoping it's a small change as it's taken a long time to get this far, can anyone help?
[See the full site here][1]
UPDATE:
require("database.php");
// Opens a connection to a MySQL server
$con = mysql_connect("localhost", $username, $password);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("teamwork_poh", $con);
$company = get_the_title();
$address = get_field('address_line_1');
$city = get_field('town_/_city');
$post_code = get_field('post_code');
$link = get_permalink();
$type = get_field('kind_of_organisation');
$sql = sprintf("select count('x') as cnt from markers where `name` = '%s'", mysql_real_escape_string($company));
$row_dup = mysql_fetch_assoc(mysql_query($sql,$con));
if ($row_dup['cnt'] == 0) {
mysql_query("INSERT INTO markers (`name`, `address`, `lat`, `lng`, `type`, `link`) VALUES ('".$company."', '".$address.", ".$city.", ".$post_code."', '0.0', '0.0', '".$type."', '".$link."')");
}
wp_reset_query();
require("database.php");
define("MAPS_HOST", "maps.googleapis.com");
define("KEY", "(my key)");
// Opens a connection to a MySQL server
$connection = mysql_connect("localhost", $username, $password);
if (!$connection) {
die("Not connected : " . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die("Can\'t use db : " . mysql_error());
}
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die("Invalid query: " . mysql_error());
}
//Initialize delay in geocode speed
$delay=0;
$base_url = "http://" . MAPS_HOST . "/maps/api/geocode/json?address=";
while ($row = #mysql_fetch_assoc($result)) {
if (!($row['lat'] * 1)) {
$geocode_pending = true;
while ($geocode_pending){
$address = $row["address"];
$id = $row["id"];
$request_url = $base_url . "" . urlencode($address) ."&sensor=false";
sleep(0.1);
$json = file_get_contents($request_url);
$json_decoded = json_decode($json);
$status = $json_decoded->status;
if (strcmp($json_decoded->status, "OK") == 0) {
$geocode_pending = false;
$lat = $json_decoded->results[0]->geometry->location->lat;
$lng = $json_decoded->results[0]->geometry->location->lng;
// echo 'here';
$query = sprintf("UPDATE markers " .
" SET lat = '%s', lng = '%s' " .
" WHERE id = '%s' LIMIT 1;",
mysql_real_escape_string($lat),
mysql_real_escape_string($lng),
mysql_real_escape_string($id));
$update_result = mysql_query($query);
echo $id;
if (!$update_result) {
die("Invalid query: " . mysql_error());
}
}
else {
// failure to geocode
$geocode_pending = false;
echo "Address " . $address . " failed to geocode. ";
echo "Received status " . $status . "\n";
}
// usleep($delay);
}
}
}
As you are storing the coordinates in database it would be best to geocode when you insert new record.
ie
require("dbinfo.php");//Your database parameters
//Connect to database
$dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
//Prepare query
$name = "%".$company."%";//Wildcard for PDO paramerter
$countSql = "SELECT COUNT(*) FROM markers WHERE `name` LIKE ?";
$countStmt = $dbh->prepare($countSql);
// Assign parameter
$countStmt->bindParam(1,$name);
//Execute query
$countStmt->execute();
// check the row count
if ($countStmt->fetchColumn() == 0) { #1 EDIT changed >0 to ==0
echo "No row matched the query."; //EDIT From Row
$q =$address.','.$city.','.$post_code.',UK';
echo "\n";
$base_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=";
$request_url = $base_url.urlencode($q)."&sensor=false";
$xml = simplexml_load_file($request_url) or die("url not loading");
if($xml->status=="OK"){#2
// Successful geocode
$lat = $xml->result->geometry->location->lat;
$lng = $xml->result->geometry->location->lng;
$insertSql ="INSERT INTO markers (`name`, `address`, `lat`, `lng`, `type`, `link`) VALUES (?,?,?,?,?,?)";
$insertStmt = $dbh->prepare($insertSql);
// Assign parameter
$insertStmt->bindParam(1,$company);
$insertStmt->bindParam(2,$address);
$insertStmt->bindParam(3,$lat);
$insertStmt->bindParam(4,$lng);
$insertStmt->bindParam(5,$type);
$insertStmt->bindParam(6,$link);
//Execute query
$insertStmt->execute();
} #2
else{
"No rows inserted.";
}#2
} #1
else {#1
echo "Rows matched the query."; //EDIT From No row
} #1
}// End try
catch(PDOException $e) {
echo "I'm sorry I'm afraid you can't do that.". $e->getMessage() ;// Remove or modify after testing
file_put_contents('PDOErrors.txt',date('[Y-m-d H:i:s]').", myFile.php, ". $e->getMessage()."\r\n", FILE_APPEND);
}
I have converted your code to PDO as it is advisable to stop using mysql_functions as these a deprecated.
I have left you to implement how you will deal with geocoding not returning coordinates. You can also check and deal with the following status codes
OVER_QUERY_LIMIT
ZERO_RESULTS
REQUEST_DENIED
INVALID_REQUEST
See pastebin For status code implementation
Going by our earlier comments, there are just a couple of changes required that should get you back on your feet.
These are, changing the address for v3 geocoding
define("MAPS_HOST", "maps.googleapis.com");
$base_url = "http://" . MAPS_HOST . "/maps/api/geocode/xml?";
$request_url = $base_url . "address=" . urlencode($address) . "&sensor=false";
And secondly changing the path in the returned xml file for setting lat/long
$coordinates = $xml->Response->Placemark->Point->coordinates;
$coordinatesSplit = split(",", $coordinates);
// Format: Longitude, Latitude, Altitude
$lat = $coordinatesSplit[1];
$lng = $coordinatesSplit[0];
Can be completely replaced with
$lat = $xml->result->geometry->location->lat;
$lng = $xml->result->geometry->location->lng;
The next piece about stopping it from going over geocoding limits. What you need to do is set a simple check before you run through the geocoding.
while ($row = #mysql_fetch_assoc($result)) {
if (!($row['lat'] * 1)) {// add this line
$geocode_pending = true;
while ($geocode_pending){
//do geocoding stuff
}
}
}// add this close
}

Google API for analytics invalid grant but works sometimes

I've been on this problem now for 2 days and have tried looking under google code and stackoverflow but still can come up with an answer.
My problem is when I try my google analytics api I get "Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'"
But the weird part is that some times it will work. rarely but if I refresh and keep trying it, it will output.
The only thing I could find is that it could be the refresh token limit has been exceeded
Attached is my code if someone could help me out or point me to the right direction.
Thanks!
<?php
session_start();
require_once 'Google_Client.php';
require_once 'Google_AnalyticsService.php';
require_once 'config.php';
$keyFile = 'key.p12';
$client = new Google_Client();
$client->setApplicationName("test");
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
$client->setAssertionCredentials(new Google_AssertionCredentials(
GOOGLE_SERVICE_ACCOUNT,
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($keyFile))
);
$client->setClientId(GOOGLE_CLIENT_ID);
$client->setAccessType('offline');
$client->setUseObjects(true);
$service = new Google_AnalyticsService($client);
try {
$results = $service->data_ga->get(
'ga:44444444',
date('Y-m-d', strtotime('-30 days '.date('Y-m-d', strtotime('-1 day '.date('Y-m- d'))))),
date('Y-m-d', strtotime('-1 day '.date('Y-m-d'))),
'ga:visits,ga:newVisits',
/*array(
'dimensions' => 'ga:source,ga:keyword',
'sort' => '-ga:visits,ga:keyword',
'filters' => 'ga:medium==organic',
'max-results' => '25'
)*/
array('dimensions' => 'ga:date')
);
} catch (Google_ServiceException $e) {
// echo $e->getMessage();
}
if ($client->getAccessToken()) {
$_SESSION['token'] = $client->getAccessToken();
}
$dateParsePattern = '/"Date.parse\(\\\"((\d{4})-(\d{2})-(\d{2})) UTC\\\"\)"/';
$dateParseReplacement = 'Date.parse("$1 UTC")';
$allVisitsItems = array();
$newVisitorsItems = array();
if ($results && count($results->getRows()) > 0) {
foreach ($results->getRows() as $row) {
$date = 'Date.parse("'.date("Y-m-d", strtotime($row[0])).' UTC")';
$allVisitsItems[] = array($date, intval(htmlspecialchars($row[1], ENT_NOQUOTES)));
$newVisitorsItems[] = array($date, intval(htmlspecialchars($row[2], ENT_NOQUOTES)));
}
}
header('Content-Type: application/json');
?>
<?php echo preg_replace($dateParsePattern, $dateParseReplacement, json_encode($allVisitsItems)) ?>
Edit - It's not the NTP, when I echoed date('l jS \of F Y h:i:s A'); it matched up.
The following works to generate output - make sure you are running PHP 5.3 or higher.
<?php
require_once './src/Google_Client.php';
require_once './src/contrib/Google_AnalyticsService.php';
$path_to_keyfile = '.p12';
$service_account_email = '7#developer.gserviceaccount.com';
$client_id = '7.apps.googleusercontent.com';
$analytics_profile_id = 'ga:IN URL OF ANALYTICS';
$client = new Google_Client();
$client->setApplicationName("API TEST");
$client->setAssertionCredentials(
new Google_AssertionCredentials(
$service_account_email,
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($path_to_keyfile)
)
);
$client->setClientId($client_id);
$client->setAccessType('offline_access');
$service = new Google_AnalyticsService($client);
$from = date('Y-m-d', strtotime('-30 days '.date('Y-m-d', strtotime('-1 day '.date('Y-m-d'))))); // 30 days
$to = date('Y-m-d', strtotime('-1 day '.date('Y-m-d'))); // yesterday
$dateParsePattern = '/"Date.parse\(\\\"((\d{4})-(\d{2})-(\d{2})) UTC\\\"\)"/';
$dateParseReplacement = 'Date.parse("$1 UTC")';
$allVisitsItems = array();
$newVisitorsItems = array();
try {
$data = $service->data_ga->get(
//
$analytics_profile_id,
$from,
$to,
'ga:visits,ga:newVisits',
array('dimensions' => 'ga:date')
);
if($data && $data['totalResults'] > 0) {
foreach($data['rows'] as $row) {
$date = 'Date.parse("'.date("Y-m-d", strtotime($row[0])).' UTC")';
$allVisitsItems[] = array($date, intval(htmlspecialchars($row[1], ENT_NOQUOTES)));
$newVisitorsItems[] = array($date, intval(htmlspecialchars($row[2], ENT_NOQUOTES)));
}
}
header('Content-Type: application/json');
?>
<?php echo preg_replace($dateParsePattern, $dateParseReplacement, json_encode($allVisitsItems)) ?>
<?php echo preg_replace($dateParsePattern, $dateParseReplacement, json_encode($newVisitorsItems)) ?>
<?php
} catch(Exception $e) {
echo 'There was an error : - ' . $e->getMessage();
}

how to handle call to method getElementsByTagname is null

i have this js piece of code:
<script language="JavaScript" type="text/javascript">
var sendReq = getXmlHttpRequestObject();
var receiveReq = getXmlHttpRequestObject();
var lastMessage = 0;
var mTimer;
function handleReceiveChat()
{
if (receiveReq.readyState == 4)
{
var chat_div = document.getElementById('div_chat');
var xmldoc = receiveReq.responseXML;
var message_nodes = xmldoc.getElementsByTagName("message");
//more code
}
}
function getChatText()
{
if (receiveReq.readyState == 4 || receiveReq.readyState == 0)
{
receiveReq.open("GET", 'getChat_xml.php?chat=1&last=' + lastMessage, true);
receiveReq.onreadystatechange = handleReceiveChat;
receiveReq.send(null);
}
}
</script>
and in getChat_xml i have this:
$xml = '<?xml version="1.0" ?><root>';
if(!isset($_GET['chat']))
{
$xml .='Your are not currently in a chat session. Enter a chat session here';
$xml .= '<message id="0">';
$xml .= '<user>Admin</user>';
$xml .= '<text>Your are not currently in a chat session. <a href="">Enter a chat session here</a></text>';
$xml .= '<time>' . date('h:i') . '</time>';
$xml .= '</message>';
}
else
{
$last = (isset($_GET['last']) && $_GET['last'] != '') ? $_GET['last'] : 0;
$sql = "SELECT message_id, user_name, message, date_format(post_time, '%h:%i') as post_time" .
" FROM message WHERE chat_id = " . db_input($_GET['chat']) . " AND message_id > " . $last;
$message_query = db_query($sql);
//Loop through each message and create an XML message node for each.
while($message_array = db_fetch_array($message_query))
{
$xml .= '<message id="' . $message_array['message_id'] . '">';
$xml .= '<user>' . htmlspecialchars($message_array['user_name']) . '</user>';
$xml .= '<text>' . htmlspecialchars($message_array['message']) . '</text>';
$xml .= '<time>' . $message_array['post_time'] . '</time>';
$xml .= '</message>';
}
}
$xml .= '</root>';
can anybody help here please?? dont understand how this works
thanks
After seeing the code you have posted, these problems come to mind...
You have not actually added an echo $xml; to output the generated XML.
Even after adding an 'echo' statement, you may get null responseXML (and hence an undefined getElementsByTagName) because of some errors in your PHP code (maybe the SQL query).
Even if your PHP code is right, you will get null responseXML because u have not sent proper content header (header('Content-Type: text/xml');).
Maybe a stupid question but are you actually echoing $xml in your getChat_xml.php file? I can see xmldoc.getElementsByTagName("message") returning null because it can't find any <message> elements because the DOM was never outputted by PHP. What happens when you view the file directly? : http://www.yoursite.com/getChat_xml.php?chat=1&last=xxx
Just a shot in the dark here, but try this:
function handleReceiveChat()
{
if (receiveReq.readyState == 4)
{
var chat_div = document.getElementById('div_chat');
var xmldoc = receiveReq.responseXML;
var message_nodes = xmldoc.getElementsByTagName("message");
if (message_nodes)
{
//more code
}
}
}