How to SEND/Retrieve SMS from GOIP - sms

Is there a way for a PHP or VB.net to retrieve/send sms on GOIP (sms-gateway) without accessing it built in Web Manager?.
The said device is using UDP port 44444.

This script is only to send SMS via php on a GOIP VOIP GATEWAY
<?php
$rand = rand();
$url = 'http://goip-ip-adress-here/default/en_US/sms_info.html';
$line = '1'; // sim card to use in my case #1
$telnum = '1230000000'; // phone number to send sms
$smscontent = 'this is a test sms'; //your message
$username = "admin"; //goip username
$password = "1234"; //goip password
$fields = array(
'line' => urlencode($line),
'smskey' => urlencode($rand),
'action' => urlencode('sms'),
'telnum' => urlencode($telnum),
'smscontent' => urlencode($smscontent),
'send' => urlencode('send')
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_PORT, 80);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
echo curl_exec($ch);
echo curl_getinfo($ch);
//close connection
curl_close($ch);
?>

Premised on #paisapimp answer I wrote this class for sending SMS in PHP and it works. Only issue is returning a sent or failed response. I'll fix that and update this answer sometime.. soon I hope. Compliments of the season!
<?php
class GoIP{
public $ip = 'http://your.server.ip/default/en_US/sms_info.html';
public $uname = 'GoIPusername';
public $pwd = 'GoIPpassword';
function sendSMS($num, $msg, $line=1){
$rand = rand();
$fields = [
'line' => urlencode($line),
'smskey' => urlencode($rand),
'action' => urlencode('sms'),
'telnum' => urlencode($num),
'smscontent' => urlencode($msg),
'send' => urlencode('send')
];
//url-ify the data for the POST
$fields_string = "";
foreach($fields as $key=>$value) {
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->ip);
curl_setopt($ch, CURLOPT_USERPWD, "{$this->uname}:{$this->pwd}");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_PORT, 80);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_exec($ch);
curl_getinfo($ch);
curl_close($ch);
}
function sendBulkSMS($nums=[], $msg, $line=1){
foreach($nums as $i=>$num){
self::sendSMS($num, $msg, $line);
}
}
}

send sms http://192.168.0.31/default/en_US/send.html?u=admin&p=passssssss&l=2&n=911&m=messagebody
Retrieve SMS from GOIP: https://github.com/cjzamora/goip-sms-gateway
status and read ussd: http://192.168.0.31/default/en_US/send_status.xml?u=admin&p=passssssss
send ussd:
file_get_contents('http://'.$goip4_user.':'.$goip4_pass.'#192.168.0.31/default/en_US/ussd_info.html', false, stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded",
'content' => http_build_query([
'line2' => '1', 'smskey' => '57872222', 'action' => 'USSD', 'telnum' => '*111#', 'send' => 'Send'
])
]
]));
'smskey' you can invent your own/
read answer ussd: http://192.168.0.31/default/en_US/send_status.xml?u=admin&p=passssssss
Additional Information: https://github.com/dudumiquim/GOIP-PHP/blob/master/doc/goip_sms_Interface_en.pdf

For My Case I Set Up GO-IP server and the hardware at my self hosted server. I wrote the programme in Elixir as follow:
#! /usr/bin/env elixir
# +-------------+------------------+--+-----------------+-------------------------------------+
# | channel: | "1" | | auth: | "the password" |
# +-------------+------------------+--+-----------------+-------------------------------------+
# | action: | "sms" | | accept: | "*/*" |
# +-------------+------------------+--+-----------------+-------------------------------------+
# | telnum: | "#{user_define}" | | content-type: | "application/x-www-form-urlencoded" |
# +-------------+------------------+--+-----------------+-------------------------------------+
# | smscontent: | "#{user_define}" | | content-length: | "125" |
# +-------------+------------------+--+-----------------+-------------------------------------+
# | smskey: |#{user Define} | | | |
# +-------------+------------------+--+-----------------+-------------------------------------+
# defmodule SMS Send OTP SMS to Phone Number Specified
defmodule SMS do
require Logger
def send do
# Virtual Code Generate By Random
vcode = Enum.random(1_00000..9_99999)
# Host of the SMS Gateway
host = "127.0.0.1"
# Port of the Gateway
port = 80
# Line Channel number
line = "1"
# Action service
action = "sms"
# Get User Telephone Number
telnum = IO.gets("Enter your phone number: ") |> String.trim()
# my OTP Message with Generated Code
smscontent = "APPNAME Your Account Verification Code is #{vcode}"
# HTTP "POST" REQUEST
{:ok, conn} = Mint.HTTP1.connect(:http, "#{host}", 80)
{:ok, conn, request_ref} =
Mint.HTTP1.request(
conn,
"POST",
"/default/en_US/sms_info.html?",
[
{"Authorization", "Basic YWRtaW46YWRtaW4="},
{"Accept", "*/*"},
{"Content-Type", "application/x-www-form-urlencoded"},
{"Content-Length", "125"}
],
"line=1&action=#{action}&telnum=#{telnum}&smscontent=#{smscontent}&smskey=${userdefine}"
)
# Checks wether it work
if conn == nil do
Logger.info("Connection to #{host} at #{port} {:failed}")
else
Logger.info("Connected to #{host} at #{port} {:success}")
end
# On Receiving Responses, IO print out Reponse
receive do
message ->
{:ok, conn, responses} = Mint.HTTP1.stream(conn, message)
# Checks is there such Files && Write File and Append
dir_log = "log/something.log"
file_existence = File.exists?(dir_log)
today = Date.utc_today()
if file_existence == true do
Logger.debug("File Requested Do Exist, append to file now ")
my_server_writer = fn filename, data ->
File.open(filename, [:append])
|> elem(1)
|> IO.binwrite(data)
|> to_string()
end
Enum.each(0..0, fn x ->
## {dir_log}_#{DateTime.utc_now}
my_server_writer.(
"#{dir_log}",
"For #{telnum} Received \"#{smscontent} \" at #{today} : #{
DateTime.to_unix(DateTime.utc_now())
} \n"
)
end)
else
Logger.debug("File Requested Do not Exist \n Creating file...")
my_server_writer = fn filename, data ->
File.open(filename, [:append])
|> elem(1)
|> IO.binwrite(data)
|> to_string()
end
Enum.each(0..0, fn x ->
my_server_writer.(
"#{dir_log}",
"For #{telnum} Received \"#{smscontent} \" at #{today} : #{
DateTime.to_unix(DateTime.utc_now())
} \n"
)
end)
end
end
{:ok, conn} = Mint.HTTP.close(conn)
end
end

Related

How can I send sms using codeigniter 4?

I'm trying to send SMS using CodeIgniter 4 but something went wrong any help or another way to send?
This is my code:
public function message()
{
/*Check submit button */
if ($this->request->getPost()) {
$email = $this->input->post('email');
$data=$this->users_model->getUserByEmail($email);
$phone=$data['phone'];
$authKey = "3456655757gEr5a019b18";
/*Multiple mobiles numbers separated by comma*/
$mobileNumber = $phone;
/*Sender ID,While using route4 sender id should be 6 characters long.*/
$senderId = "ABCDEF";
/*Your message to send, Add URL encoding here.*/
$message = "From Codeigniter 4";
/*Define route */
$route = "route=4";
/*Prepare you post parameters*/
$postData = array(
'authkey' => $authKey,
'mobiles' => $mobileNumber,
'message' => $message,
'sender' => $senderId,
'route' => $route
);
/*API URL*/
$url="https://control.msg91.com/api/sendhttp.php";
/* init the resource */
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData
/*,CURLOPT_FOLLOWLOCATION => true*/
));
/*Ignore SSL certificate verification*/
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
/*get response*/
$output = curl_exec($ch);
/*Print error if any*/
if (curl_errno($ch)) {
echo 'error:' . curl_error($ch);
}
curl_close($ch);
echo "Message Sent Successfully !";
}
}
After run the code above my web page return "Message Sent Successfully!", but nothing received in my phone. What is the problem?
What does the cURL call responds in the $output variable?
You already put the output in it and i think it will guide you to the reason why the SMS is not sending out to your phone.

Codeigniter reCaptcha v3 with cUrl

I have a form integrated with invisible reCaptcha.
Verification is performed on a function within the Controller.
The call to google is made using file_get_content and if no response is obtained, the call is made using curl.
This is the function
public function verify_captcha()
{
$recaptcha_response = $_POST['recaptchaResponse'];
log_message('info', $recaptcha_response);
// Build POST request:
$recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify';
$recaptcha_secret = 'My KEY';
$recaptcha_response = $_POST['recaptchaResponse'];
$recaptcha = file_get_contents($recaptcha_url . '?secret=' . $recaptcha_secret . '&response=' . $recaptcha_response);
$recaptcha = json_decode($recaptcha,true);
if(!$recaptcha)
{
// call curl to POST request
log_message('info', 'Call CURL');
$data = array( 'secret' => $recaptcha_secret, 'response' => $recaptcha_response);
//$curlConfig = array( CURLOPT_URL => $recaptcha_url, CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_POSTFIELDS => $data );
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $recaptcha_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$recaptcha = json_decode($response, true);
ob_start();
var_dump($recaptcha);
$result = ob_get_contents(); //or ob_get_clean()
log_message('info', $result);
if (array_key_exists('error-codes', $recaptcha))
{
log_message('error', 'Error reCaptcha '.$recaptcha['error-codes'][0]);
}
if ($recaptcha["success"] == '1')
{
if ($recaptcha["score"] >= 0.5)
{
}
}
else
{
log_message('error', 'Error reCaptcha no Success');
}
else
{
log_message('info', 'Call file_get_content');
}
}
These are the messages of the log file
ERROR - 2020-03-18 09:54:31 --> Severity: Warning --> file_get_contents(): php_network_getaddresses: getaddrinfo failed: Name or service not known /mysite/application/controllers/captcha.php 1362
ERROR - 2020-03-18 09:54:31 --> Severity: Warning --> file_get_contents(https://www.google.com/recaptcha/api/siteverify?secret=6LfP26QUAAAAAHilJfguEgIcgOBkTg2soD7oCQIh&response=03AERD8XpOL7956DMd7dhiqasH4fK2iNjtBFBJdw3OynXGeAFBMmSqqtjsqXFW97rv-kD_H-y6aLrL1VLMkwg222Y7BoNnaB_zQ7y2NzXVtlIsWYwIw9BSbUdFdSylq4dNjO5j5Jo1xvjPotvMFuddnC5YVRC1wnk7HESqv8hvRU40x9pNpoQ-sIaXcAN8BdBgleXFufmmNoMzuh3PCvgT3RkIj1TsTs-ltM9LyVbLtFnFPbTkHZqpQjppMkHCcw87u3xqbr23EJkusR_U2vFwJTAJU9p-Z27sDuiKmEMsjJ2O1i3Wnxm9yq4HiEI2vnh420VDnPZEYRbXuLLSGhGuPciGQ3mtp07tjn265oyYbcFp2s9GentdUpPWRCxWfySTa6du7dzzSHkqPMKcPf6LmfVtICkTJf4y-w): failed to open stream: php_network_getaddresses: getaddrinfo failed: Name or service not known /mysite/application/controllers/captcha.php 1362
INFO - 2020-03-18 09:54:31 --> Call CURL
INFO - 2020-03-18 09:54:31 --> NULL
The call to file_get_content shows error and returns nothing with curl.
What may be happening?
Thanks
If you totally, absolutely need to use file_get_contents, I'll share with you a helper function I have, which you can adapt to your own needs
function validate_recaptcha_response($recaptcha_response)
{
$api_url = 'https://www.google.com/recaptcha/api/siteverify';
$api_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$remoteip = '';
$data = array('secret' => $api_secret, 'response' => $recaptcha_response);
$options = array(
'http' => array(
'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($api_url, false, $context);
$captcha_response = json_decode($result, true);
$r = array(
'success' => $captcha_response['success'],
'timestamp' => $captcha_response['challenge_ts'],
'hostname' => $captcha_response['hostname'],
'error_codes' => (isset($captcha_response['error-codes'])) ? $captcha_response['error-codes'] : null,
);
return $r;
}
I call this from any controller that gets the recaptcha response (the helper is autoloaded) using something like
$recaptcha_check = validate_recaptcha_response($var_where_you_store_the_recaptcha_response);
Please note that I'm adding the $options array to build a POST, defining a header, the method and use http_build_query() and stream_context_create() before file_get_contents() in order to query the data.
Please Follow the bellow Steps to integrate Recaptcha v3 in Codeigniter versions bellow 4 (3.1.9) or others.
Step #1: Create Recaptcha v3 for your domain and keep the site_key & secret_key.
[https://cloud.google.com/recaptcha-enterprise/docs/create-key][1]
Step #2: Add the bellow Javascirpt codes with replacement of your site_key & secret_key inside Head section of your Form page.
<script type="text/javascript">
var review_recaptcha_widget;
var onloadCallback = function() {
if($('#review_recaptcha').length) {
review_recaptcha_widget = grecaptcha.render('review_recaptcha', {
'sitekey' : 'recaptcha_site_key_v3',
'secretkey' : 'recaptcha_secret_key_v3'
});
}
};
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
Step #3:Browse the page, you will see the new recaptcha in right bottom corner of page, Done, thats it.

Megento 2 stdClass Object ( [message] => Consumer is not authorized to access %resources [parameters] => stdClass Object ( [resources] => self ) )

I have magento2.1 installed in my server under folder magento2. So base Url is
http://$domain/magento2/
After this I have created a new role as admin and under permission clicked All.Then I created a new user with username, password and other details. Then connected the new user to new role.
After that i call the admin/token by passing username and password as
$apiURL="http://".$domain."/magento2/index.php/rest/V1/integration/admin/token";
//parameters passing with URL
$data = array("username" => "username", "password" => "!pass");
$data_string = json_encode($data);
$ch = curl_init($apiURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Content-Length: ".strlen($data_string)));
print_r(curl_getinfo($ch));
$token = curl_exec($ch);
//decoding generated token and saving it in a variable
echo $token= json_decode($token,true);
This gave a token but on print the http_code it gives 0. I tried through Postman too.
dadtaqm9b5bjqr6tk35hj8b6iy8a6hou //token
Then i called the customer/me endpoint
$token= trim($token);
//Using above token into header
$headers = array("Authorization: Bearer ".$token,"Accept:application/json");
//API URL to get all Magento 2 modules
$requestUrl='http://'.$domain.'/magento2/index.php/rest/V1/customers/me';
$ch = curl_init($requestUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//print_r(curl_getinfo($ch));
$result = curl_exec($ch);
//decoding result
$result= json_decode($result);
//printing result
print_r($result);
This gave output as
stdClass Object ( [message] => Consumer is not authorized to access %resources [parameters] => stdClass Object ( [resources] => self ) )
Any solution to this problem?

How can send sms by url codeigntor

http://52.36.50.145:8080/MainServlet?orgName=XXX&userName=XXX&password=XXX&mobileNo=967777662112&text=
msg + "&coding=2"
I have that's url how can send send sms by for mulit user codeigntor
You must use cURL in CodeIgniter. this function works fine for Sending SMS.
function sms_code_send($number='',$message='')
{
$username = 'username';
$password = '*******';
$originator = 'sender name';
$message = 'Welcom to ......, your activation code is : '.$message;
//set POST variables
$url = 'http://exmaple.com/bulksms/go?';
$fields = array(
'username' => urlencode($username),
'password' => urlencode($password),
'originator' => urlencode($originator),
'phone' => urlencode($number),
'msgtext' => urlencode($message)
);
$fields_string = '';
//url-ify the data for the POST
foreach($fields as $key=>$value)
{
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
return $result;
}

Start point for google analytics and webmaster api

I have about 50 websites in my google analytics account.
I want to do some research, create notification system and compare analytics data with data from other sources.
That means I want to get a dozen of reports for every site twice a day. I parse them and store in mysql. What's the simplest way do do that?
I registered an application and turned on analytics api in it, but there's no webmaster api. Also I have not a clear understanding of oAuth. Is there a way without redirecting and requesting new access token every time? That's something like granting permanent access for my application in my account from my ip without further confirmations.
So, is there a good tutorial for the beginner about retrieving data from analytics and webmaster written in php, perl or ruby?
Following code will help you to retrieve "refresh token" using offline access of oauth flow.
you can use this refresh token to get an access token without bothering user.
Make sure that the Redirect Uri that you have mentioned in your API console should be same as the filename in which you will place the following code.
For eg.
If the redirect uri is:-http://test.com/google_oauth.php
then following script should be placed in :- google_oauth.php (path:http://test.com/google_oauth.php)
<?php
$OAuth = array(
'oauth_uri' => 'https://accounts.google.com/o/oauth2/auth',
'client_id' => '#clientId',
'client_secret' => '#clientSecret',
'access_type' => 'offline',
'redirect_uri' => 'http://test.com/google_oauth.php', //this url should be same as you had registered in your api console as redirect uri()
'oauth_token_uri' => 'https://accounts.google.com/o/oauth2/token'
);
$token = array(
'access_token' => '',
'token_type' => '',
'expires_in' => '',
'refresh_token' => ''
);
$title = 'No Code';
$AuthCode = 'Null';
// see if error parameter exisits
$error = _get_url_param($_SERVER['REQUEST_URI'], 'error');
if ($error != NULL)
{ // this means the user denied api access to GWMTs
$title = $error;
}
else
{ // does the code parameter exist?
$AuthCode = _get_url_param($_SERVER['REQUEST_URI'], 'code');
if ($AuthCode == NULL)
{ // get authorization code
$OAuth_request = _formatOAuthReq($OAuth, "https://www.googleapis.com/auth/analytics.readonly");
header('Location: ' . $OAuth_request);
exit; // the redirect will come back to this page and $code will have a value
}
else
{
$title = 'Got Authorization Code';
// now exchange Authorization code for access token and refresh token
$token_response = _get_auth_token($OAuth, $AuthCode);
$json_obj = json_decode($token_response);
$token['access_token'] = $json_obj->access_token;
$token['token_type'] = $json_obj->token_type;
$token['expires_in'] = $json_obj->expires_in;
$token['refresh_token'] = $json_obj->refresh_token;
echo 'access_token = ' . $json_obj->access_token;
}
}
function _get_auth_token($params, $code)
{
$url = $params['oauth_token_uri'];
$fields = array(
'code' => $code,
'client_id' => $params['client_id'],
'client_secret' => $params['client_secret'],
'redirect_uri' => $params['redirect_uri'],
'grant_type' => 'authorization_code'
);
$response = _do_post($url, $fields);
return $response;
}
function _do_post($url, $fields)
{
$fields_string = '';
foreach ($fields as $key => $value)
{
$fields_string .= $key . '=' . $value . '&';
}
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
function _formatOAuthReq($OAuthParams, $scope)
{
$uri = $OAuthParams['oauth_uri'];
$uri .= "?client_id=" . $OAuthParams['client_id'];
$uri .= "&redirect_uri=" . $OAuthParams['redirect_uri'];
$uri .= "&scope=" . $scope;
$uri .= "&response_type=code";
$uri .= "&access_type=offline";
return $uri;
}
function _get_url_param($url, $name)
{
parse_str(parse_url($url, PHP_URL_QUERY), $params);
return isset($params[$name]) ? $params[$name] : null;
}
function _get_refresh_token($params, $code)
{
$url = $params['oauth_token_uri'];
$fields = array(
'code' => $code,
'client_id' => $params['client_id'],
'client_secret' => $params['client_secret'],
'refresh_token' => $token['refresh_token'],
'grant_type' => 'refresh_token'
);
$response = _do_post($url, $fields);
return $response;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><?= $title; ?></title>
</head>
<body>
<h1>OAuth2 Authorization Code</h1>
<p>Authorization Code: <?= $AuthCode; ?></p>
<p>access token: <?= $token['access_token']; ?></p>
<p>expires in: <?= $token['expires_in']; ?></p>
<p>refresh token: <?= $token['refresh_token']; ?></p>
<p></p>
</body>
</html>
Once you get your refresh token you can use following code to get data from google analytics:-
<?php
$refresh_token='#refresh-token';
$fields_string = "client_id=#ClientId&client_secret=#clientSecret&refresh_token=$refresh_token&grant_type=refresh_token";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://accounts.google.com/o/oauth2/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
$token_response = curl_exec($ch);
$json_obj = json_decode($token_response);
$access_token = $json_obj->access_token;
curl_close($ch);
$url = "https://www.googleapis.com/analytics/v3/data/ga?ids=ga:30566906&start-date=2013-01-01&end-date=2013-04-16&dimensions=ga:medium&metrics=ga:visits,ga:bounces";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: Bearer $access_token"));
curl_setopt($ch, CURLOPT_URL, html_entity_decode($url));
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$json_obj = json_decode($output);
$test=$json_obj->columnHeaders;
foreach($test as $a){
var_dump($a);
}
curl_close($ch);
?>
In above scripts:-
#clientId and #clientSecret should be replaced by the client id and client secret that you have received while registering your web application.
For your use case I would suggest using a Google Service Account rather than the OAuth flow that requires human confirmation.
There are Client Libraries available for several languages that can make the OAuth part simpler. For example, in the ruby library includes a sample script showing how to use a service account with Google Analytics API. Essentially it's this:
#client = Google::APIClient.new(
:application_name => opts['application_name'],
:application_version => opts['application_version'])
## Load our credentials for the service account
key = Google::APIClient::KeyUtils.load_from_pkcs12(key_file, key_secret)
#client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
:audience => 'https://accounts.google.com/o/oauth2/token',
:scope => 'https://www.googleapis.com/auth/analytics.readonly',
:issuer => service_account_email,
:signing_key => key)
## Request a token for our service account
#client.authorization.fetch_access_token!
query_data = #client.execute(:api_method => #analytics.data.ga.get, :parameters => {
'ids' => "ga:" + #profileID,
'start-date' => #startDate,
'end-date' => #endDate,
'dimensions' => dimension,
'metrics' => metric,
'sort' => sort
})
There is a Webmaster API available although it does not have access to the query data. You can get that through this Google-published python script or through a similar one in PHP with more data.

Resources