How to get the Gross Sales from the Square Order API? - square

Qn1) I have tried getting the gross sales from the Order API. However, I could only be able to get each lineitem gross value concatenating with one and another ...
Gross value that is concatenating
Qn2) I tried to echo all the item name, qty and etc to insert it into my database although it works but I am getting an error message shown below
Error message
Here is my code: (Have replaced the access token and the location_id to 'XXXX')
<html>
<?php
require_once(__DIR__ . '/vendor/autoload.php');
use Square\SquareClient;
use Square\Environment;
$client = new SquareClient([
'accessToken' => 'XXXX',
'environment' => Environment::PRODUCTION,
]);
$location_ids = ['XXXX'];
$created_at = new \Square\Models\TimeRange();
$created_at->setStartAt('2021-05-17T00:00:00+08:00');
$created_at->setEndAt('2021-05-17T23:59:59+08:00');
$date_time_filter = new \Square\Models\SearchOrdersDateTimeFilter();
$date_time_filter->setCreatedAt($created_at);
$filter = new \Square\Models\SearchOrdersFilter();
$filter->setDateTimeFilter($date_time_filter);
$sort = new \Square\Models\SearchOrdersSort('CREATED_AT');
$sort->setSortOrder('DESC');
$query = new \Square\Models\SearchOrdersQuery();
$query->setFilter($filter);
$query->setSort($sort);
$body = new \Square\Models\SearchOrdersRequest();
$body->setLocationIds($location_ids);
$body->setQuery($query);
$body->setLimit(10000);
$body->setReturnEntries(false);
$api_response = $client->getOrdersApi()->searchOrders($body);
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
$orders = $result->getOrders();
foreach($orders as $x => $val) {
$lineItems = $result->getOrders()[$x]->getLineItems();
$orderid = $result->getOrders()[$x]->getId();
foreach($lineItems as $q => $val2){
$lineItemsID = $lineItems[$q]->getUid();
$itemName = $lineItems[$q]->getName();
$itemQty = $lineItems[$q]->getQuantity();
$catalogObjID = $lineItems[$q]->getCatalogobjectid();
$grossSales[] = $lineItems[$q]->getGrossSalesMoney()->getAmount();
echo (array_sum($grossSales)/100); //Qn1
echo($orderid. " ". $lineItemsID ." ".$catalogObjID." ".$itemName ." ".$itemQty." <br/>"); //Qn2
}
}
}
else
{
$errors = $api_response->getErrors();
}
?>
</html>

<html>
<?php
require_once(__DIR__ . '/vendor/autoload.php');
use Square\SquareClient;
use Square\Environment;
$client = new SquareClient([
'accessToken' => 'XXXX',
'environment' => Environment::PRODUCTION,
]);
$location_ids = ['XXXX'];
$created_at = new \Square\Models\TimeRange();
$created_at->setStartAt('2021-05-17T00:00:00+08:00');
$created_at->setEndAt('2021-05-17T23:59:59+08:00');
$date_time_filter = new \Square\Models\SearchOrdersDateTimeFilter();
$date_time_filter->setCreatedAt($created_at);
$filter = new \Square\Models\SearchOrdersFilter();
$filter->setDateTimeFilter($date_time_filter);
$sort = new \Square\Models\SearchOrdersSort('CREATED_AT');
$sort->setSortOrder('DESC');
$query = new \Square\Models\SearchOrdersQuery();
$query->setFilter($filter);
$query->setSort($sort);
$body = new \Square\Models\SearchOrdersRequest();
$body->setLocationIds($location_ids);
$body->setQuery($query);
$body->setLimit(10000);
$body->setReturnEntries(false);
$api_response = $client->getOrdersApi()->searchOrders($body);
if ($api_response->isSuccess()) {
$result = $api_response->getResult();
$orders = $result->getOrders();
$grossSales = array();
if (is_array($orders) || is_object($orders)) {
foreach($orders as $x => $val) {
$lineItems = $result->getOrders()[$x]->getLineItems();
$orderid = $result->getOrders()[$x]->getId();
if (is_array($lineItems) || is_object($lineItems)){
foreach($lineItems as $q => $val2){
$lineItemsID = $lineItems[$q]->getUid();
$itemName = $lineItems[$q]->getName();
$itemQty = $lineItems[$q]->getQuantity();
$catalogObjID = $lineItems[$q]->getCatalogobjectid();
$grossSales[] = $lineItems[$q]->getGrossSalesMoney()->getAmount();
}
}
}
}
$sum = 0;
foreach($grossSales as $key=>$value)
{
$sum+= $value;
}
echo ($sum/100);
}
else
{
$errors = $api_response->getErrors();
}
?>
</html>

Related

I can't access admin panel of my script : Invalid query You have an error in your SQL syntax

I have an error message when i try to access my script (php):
Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's marketing advertising'' at line 1
This is a admin php file contain mysql query
<?php
$stt_query = $ocdb->get_rows("SELECT * FROM ".$config->prefix."search order by id desc limit 13" );
if (count( $stt_query ) > 0) {
foreach ($stt_query as $row) :
?>
<li><?php echo $row['title'];?></li>
<?php
endforeach;
}
?>
the php query page:
<?php class OCDB { var $server = ""; var $port = ""; var $db = ""; var $user = ""; var $password = ""; var $prefix = ""; var $insert_id; var $link; function __construct($_server, $_port, $_db, $_user, $_password, $_prefix) { $this->server = $_server; $this->port = $_port; $this->db = $_db; $this->user = $_user; $this->password = $_password; $this->prefix = $_prefix; $host = $this->server; if (defined('DB_HOST_PORT') && !empty($this->port)) $host .= ':'.$this->port; $this->link = mysqli_connect($host, $this->user, $this->password) or die("Could not connect: " . mysqli_connect_error()); mysqli_select_db($this->link, $this->db) or die ('Can not use database : ' . mysqli_error($this->link)); mysqli_query($this->link, 'SET NAMES utf8'); } function get_row($_sql) { //$res = $this->link->query($_sql); //if ($this->link->error) { //try { //throw new Exception("MySQL error $mysqli->error <br> Query:<br> $query", $this->link->errno); //} catch(Exception $e ) { //echo "Error No: ".$e->getCode(). " - ". $e->getMessage() . "<br >"; //echo nl2br($e->getTraceAsString()); //} //} $result = mysqli_query($this->link, $_sql) or die("Invalid query: " . mysqli_error($this->link)); $row = mysqli_fetch_array($result, MYSQL_ASSOC); mysqli_free_result($result); return $row; mysqli_close($this->link); } function get_rows($_sql) { $rows = array(); $result = mysqli_query($this->link, $_sql) or die("Invalid query: " . mysqli_error($this->link)); while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) { $rows[] = $row; } mysqli_free_result($result); return $rows; } function get_var($_sql) { $result = mysqli_query($this->link, $_sql) or die("Invalid query: " . mysqli_error($this->link)); $row = mysqli_fetch_array($result, MYSQL_NUM); mysqli_free_result($result); if ($row && is_array($row)) return $row[0]; return false; } function query($_sql) { $result = mysqli_query($this->link, $_sql) or die("Invalid query: " . mysqli_error($this->link)); $this->insert_id = mysqli_insert_id($this->link); return $result; } function escape_string($_string) { return mysqli_real_escape_string($this->link, $_string); } } ?>
Please can you help me i can't access admin panel because of this error.
Thanks

How to update youtube annalytics to all previously registered youtube channels

I have a web app in which the users can register and connect their youtube channels. Next in the registration process I collect all the information I can get from youtube data api and youtube analytics and reporting api (with scopes and access tokens) and store it in the database. I show that info on their dashboards. I also display that info in the admin panel for the administrators to see.
The problem is, how can I refresh that info, lets say, once a day? I've tried with the access token but i get error 403 Forbidden message. I want to update the info to all of the registered youtube accounts, this is the function I use to update all but its not working
(In the bellow script, i send $code as a variable and the function is called on the redirect URI)
$youtube_channels = YouTubeChannels::get();
$key = env('NEW_YOUTUBE_API_KEY');
foreach($youtube_channels as $youtube_channel) {
$yt_channel_statistics = Http::get('https://www.googleapis.com/youtube/v3/channels', [
'part' => 'statistics,snippet',
'id' => $youtube_channel->youtube_channel_id,
'key' => $key
]);
$yt_channel_statistics_json = $yt_channel_statistics->json();
$update_yt = YouTubeChannels::where('youtube_channel_id', $youtube_channel->youtube_channel_id)->first();
if($update_yt != null) {
$update_yt->channel_name = $yt_channel_statistics_json['items'][0]['snippet']['title'];
$update_yt->channel_subscribers = $yt_channel_statistics_json['items'][0]['statistics']['subscriberCount'];
$update_yt->channel_total_views = $yt_channel_statistics_json['items'][0]['statistics']['viewCount'];
$update_yt->channel_videos_count = $yt_channel_statistics_json['items'][0]['statistics']['videoCount'];
$update_yt->save();
}
//test
$baseUrl = 'https://www.googleapis.com/youtube/v3/';
$apiKey = env('NEW_YOUTUBE_API_KEY');
$channelId = $youtube_channel->youtube_channel_id;
$params = [
'id'=> $channelId,
'part'=> 'contentDetails',
'key'=> $apiKey
];
$url = $baseUrl . 'channels?' . http_build_query($params);
$json = json_decode(file_get_contents($url), true);
$playlist = $json['items'][0]['contentDetails']['relatedPlaylists']['uploads'];
$params = [
'part'=> 'snippet',
'playlistId' => $playlist,
'maxResults'=> '50',
'key'=> $apiKey
];
$url = $baseUrl . 'playlistItems?' . http_build_query($params);
$json = json_decode(file_get_contents($url), true);
$videos = [];
foreach($json['items'] as $video)
$videos[] = $video['snippet']['resourceId']['videoId'];
while(isset($json['nextPageToken'])){
$nextUrl = $url . '&pageToken=' . $json['nextPageToken'];
$json = json_decode(file_get_contents($nextUrl), true);
foreach($json['items'] as $video)
$videos[] = $video['snippet']['resourceId']['videoId'];
}
$video_ids_string = collect($videos)->implode(',');
//
//endtest
//new test
//
$params = [
'part'=> 'snippet,contentDetails,statistics,status',
'id' => $video_ids_string,
'key'=> $apiKey
];
$url = $baseUrl . 'videos?' . http_build_query($params);
$json = json_decode(file_get_contents($url), true);
$videos_infos = $json;
//
YouTubeVideos::where('youtube_channel_id', $youtube_channel->id)->delete();
foreach ($videos as $video){
foreach($videos_infos['items'] as $info){
if ($info['id'] == $video) {
if($info['status']['privacyStatus'] == 'public') {
$youtube_video = new YouTubeVideos();
// if (!$live_error) {
// foreach ($live_videos as $live) {
// if ($live->youtube_id == $video) {
// $youtube_video->was_live = true;
// }
// }
// }
// dd($video);
$youtube_video->youtube_channel_id = $youtube_channel->id;
$youtube_video->yt_video_id = $video;
$youtube_video->yt_video_title = $info['snippet']['title'];
$youtube_video->yt_video_description = $info['snippet']['description'];
$youtube_video->yt_video_published_at = Carbon::parse($info['snippet']['publishedAt']);
if(isset($info['snippet']['defaultAudioLanguage'])) {
$youtube_video->yt_video_default_audio_language = $info['snippet']['defaultAudioLanguage'];
} else {
$youtube_video->yt_video_default_audio_language = '';
}
if (strcmp($info['contentDetails']['caption'], 'true') == 0) {
$youtube_video->is_video_captioned = true;
} else {
$youtube_video->is_video_captioned = false;
}
$youtube_video->yt_video_definition = $info['contentDetails']['definition'];
$youtube_video->yt_video_dislike_count = 0;
$youtube_video->yt_video_like_count = $info['statistics']['likeCount'];
$youtube_video->yt_video_views_count = $info['statistics']['viewCount'];
//proba type of views
//
$client = new Google_Client();
try{
$client->setAuthConfig(storage_path('app'.DIRECTORY_SEPARATOR. 'json'. DIRECTORY_SEPARATOR.'client_secret.json'));
}catch (\Google\Exception $e){
dd($e->getMessage());
}
// $client->addScope([GOOGLE_SERVICE_YOUTUBE::YOUTUBE_READONLY, 'https://www.googleapis.com/auth/yt-analytics.readonly', 'https://www.googleapis.com/auth/youtube.readonly']);
$client->addScope([GOOGLE_SERVICE_YOUTUBE::YOUTUBE_FORCE_SSL,GOOGLE_SERVICE_YOUTUBE::YOUTUBE_READONLY, GOOGLE_SERVICE_YOUTUBE::YOUTUBEPARTNER,'https://www.googleapis.com/auth/yt-analytics.readonly', 'https://www.googleapis.com/auth/yt-analytics-monetary.readonly']);
$client->setRedirectUri(env('APP_URL') . '/get_access_token_yt_test');
// offline access will give you both an access and refresh token so that
// your app can refresh the access token without user interaction.
$client->setAccessType('offline');
// Using "consent" ensures that your application always receives a refresh token.
// If you are not using offline access, you can omit this.
$client->setPrompt("consent");
$client->setApprovalPrompt('force');
$client->setIncludeGrantedScopes(true); // incremental auth
if (!isset($code)){
$auth_url = $client->createAuthUrl();
return redirect()->away($auth_url)->send();
}else{
if($code != null) {
$client->fetchAccessTokenWithAuthCode($code);
$client->setAccessToken($client->getAccessToken());
session()->push('refresh_token_youtube', $client->getRefreshToken());
session()->save();
}
}
$service = new Google_Service_YouTube($client);
$analytics = new Google_Service_YouTubeAnalytics($client);
$typeOfViews = $analytics->reports->query([
'ids' => 'channel==' . $youtube_channel->youtube_channel_id,
'startDate' => Carbon::parse($youtube_channel->channel_created_at)->format('Y-m-d'),
'endDate' => Carbon::today()->format('Y-m-d'),
'metrics' => 'views',
'dimensions' => 'liveOrOnDemand',
'filters' => 'video=='.$video
]);
foreach ($typeOfViews as $viewType) {
if ($viewType[0] == 'ON_DEMAND') {
$youtube_video->yt_video_on_demand_views_count = $viewType[1];
} else if ($viewType[0] == 'LIVE') {
$youtube_video->yt_video_live_views_count = $viewType[1];
}
}
$watch_times = $analytics->reports->query([
'ids' => 'channel=='.$youtube_channel->youtube_channel_id,
'startDate' => Carbon::parse($youtube_channel->channel_created_at)->format('Y-m-d'),
'endDate' => Carbon::today()->format('Y-m-d'),
'metrics' => 'estimatedMinutesWatched',
'dimensions' => 'day',
'filters' => 'video=='.$video
]);
// //update quotas
// // self::update_quotas(1);
$total = 0;
foreach ($watch_times as $watch_time){
$total += $watch_time[1];
}
$youtube_video->estimated_minutes_watch_time = $total;
$youtube_video->save();
//zacuvuva captions
$xmlString = file_get_contents("https://video.google.com/timedtext?type=list&v=" . $video);
$xmlObject = simplexml_load_string($xmlString);
$json = json_encode($xmlObject);
$phpArray = json_decode($json, true);
if (isset($phpArray['track'])) {
foreach ($phpArray['track'] as $array) {
$yt_video_captions = new YouTubeVideosCaptions();
$yt_video_captions->youtube_video_id = $youtube_video->id;
$yt_video_captions->language = $array['lang_code'];
$yt_video_captions->save();
}
}
//zacuvuva tags
if(isset($info['snippet']['tags'])) {
if ($info['snippet']['tags'] != null) {
foreach ($info['snippet']['tags'] as $tag) {
$youtube_video_tags = new YouTubeVideosTags();
$youtube_video_tags->youtube_video_id = $youtube_video->id;
$youtube_video_tags->tag = $tag;
$youtube_video_tags->save();
}
}
}
if ($youtube_video->is_video_captioned) {
$captions = YouTubeVideosCaptions::where('youtube_video_id', $youtube_video->id)->get();
foreach ($captions as $caption) {
$video_id = YouTubeVideos::where('id', $caption->youtube_video_id)->first();
$client->authorize();
$fp = fopen('../storage/app/captions/' . $caption->id . '.xml', 'w');
$xmlString = file_get_contents("http://video.google.com/timedtext?type=track&v=" . $video_id['yt_video_id'] . "&id=0&lang=" . $caption['language']);
fwrite($fp, $xmlString);
fclose($fp);
}
}
echo 'done';
}
}
}
}
// Command::line('Youtube videos updated');
//
//
//end new test
}
}

get table rate shipping data in Woocommerce REST API

I am trying to get all active shipping methods in Woocommerce REST API. How can I achieve this. I am new to woocommerce REST API, Any help is much appreciated.
I want response something like this -
{
"shipping_methods": {
"method_id": "method_title"
}
}
I , finally, come up with the solution. It may help others.
Below is complete code to get all table rate shipping data including shipping zones, shipping methods by zone and rates by zone -
header('Content-type: application/json');
$json_file=file_get_contents('php://input');
$jsonvalue= json_decode($json_file,true);
global $wpdb;
global $woocommerce;
$active_methods = array();
$shipping_methods = $woocommerce->shipping->load_shipping_methods();
//echo "<pre>";print_r($shipping_methods);
foreach ( $shipping_methods as $id => $shipping_method ) {
if ( isset( $shipping_method->enabled ) && 'yes' === $shipping_method->enabled ) {
$data_arr = array( 'title' => $shipping_method->title, 'tax_status' => $shipping_method->tax_status );
if($id=='table_rate'){
$raw_zones = $wpdb->get_results("SELECT zone_id, zone_name, zone_order FROM {$wpdb->prefix}woocommerce_shipping_zones order by zone_order ASC;");
//echo "<pre>";print_r($raw_zones);
$shipping = array();
$shippingarr = array();
foreach ($raw_zones as $raw_zone) {
$zones = new WC_Shipping_Zone($raw_zone->zone_id);
$zone_id = $zones->zone_id;
$zone_name = $zones->zone_name;
$zone_enabled = $zones->zone_enabled;
$zone_type = $zones->zone_type;
$zone_order = $zones->zone_order;
$shipping['zone_id'] = $zone_id;
$shipping['zone_name'] = $zone_name;
$shipping['zone_enabled'] = $zone_enabled;
$shipping['zone_type'] = $zone_type;
$shipping['zone_order'] = $zone_order;
$shipping_methods = $zones->shipping_methods;
foreach($shipping_methods as $shipping_method){
$methodid = $shipping_method["number"];
$raw_rates[$methodid]['rates'] = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}woocommerce_shipping_table_rates WHERE shipping_method_id={$methodid};",ARRAY_A);
}
$shipping['shipping_methods'] = $raw_rates;
$raw_country = $wpdb->get_results("SELECT location_code FROM {$wpdb->prefix}woocommerce_shipping_zone_locations WHERE zone_id={$zone_id};",ARRAY_N);
$shipping['countries'] = $raw_country;
$shippingarr[] = $shipping;
}
$data_arr['shipping_zones'] = $shippingarr;
}
$active_methods[ $id ] = $data_arr;
}
}
if(!empty($shippingarr)){
$result['success']='true';
$result['error']="0";
$result['msg']='Shipping methos found.';
$result['data']=$active_methods;
}else{
$result['success']='true';
$result['error']="0";
$result['msg']='Shipping methos found.';
$result['data']= array();
}
echo json_encode($result); `

CDbCriteria throwing column name is ambigous

I have the following method in a controller of my Yii app.
public function actionManage($typeid=0, $locationid=0, $page=1, $rows=12, $sidx='date_input', $sord='desc', $kategori='')
{
if (Yii::app()->request->isAjaxRequest) {
// Jika dilakukan operasi 'edit' pada row
if (isset($_REQUEST['oper']))
{
$oper = $_REQUEST['oper'];
$id = $_REQUEST['id'];
if ($oper == 'edit')
{
$value = $_REQUEST['value'];
$record = InputData::model()->findByPk($id);
$record->value = $value;
$record->update();
}
if($oper == 'delete'){
$model = InputData::model()->findByPk($id);
$model->delete();
}
}
// inisialisasi criteria query
$criteria = new CDbCriteria();
$criteria->order = "$sidx $sord";
// filter lokasi
if (is_numeric($locationid) && $locationid !== 0)
{
$criteria->with = array('data'=>array(
'condition'=>'data.locationid=:locationid',
'params'=>array(':locationid'=>$locationid)
));
} else {
if (is_numeric($typeid) && $typeid !== 0)
{
$criteria->with = array('data.location'=>array(
'with'=>array(
'type'=>array(
'condition'=>'type.typeid=:typeid',
'params'=>array(':typeid'=>$typeid)
)
)
));
} else {
$criteria->with = array('data.location'=>array(
'with'=>array(
'type'=>array(
'condition'=>'type.type_desc=:type_desc',
'params'=>array(':type_desc'=>$kategori)
)
)
));
}
}
// filter range tanggal
if (isset($_REQUEST['startdate'], $_REQUEST['enddate']))
{
$startdate = $_REQUEST['startdate'];
$enddate = $_REQUEST['enddate'];
$criteria->condition = 'date_input <= :enddate AND date_input >= :startdate';
$criteria->params = array(':startdate'=>$startdate, ':enddate'=>$enddate);
}
if(isset($_REQUEST['dataid'])){
$dataid = $_REQUEST['dataid'];
$criteria->addCondition("dataid = $dataid");
}
$dataProvider = new CActiveDataProvider('InputData', array(
'criteria'=>$criteria,
'pagination'=>array(
'currentPage'=>$page-1,
'pageSize'=>$rows
)
));
$count = $dataProvider->totalItemCount;
$total_pages = $count > 0 ? ceil($count/$rows) : 0;
if ($page > $total_pages) $page=$total_pages;
// generate response untuk jqgrid
$response = new stdClass();
$response->page = $page;
$response->total = $total_pages;
$response->records = $count;
foreach($dataProvider->getData() as $row)
{
$response->rows[] = array(
'id'=>$row->inputdataid,
'cell'=>array(
$row->inputdataid,
$row->date_input,
$row->time_input,
$row->data->location->location_name,
$row->data->data_name,
$row->data->variable->var_name,
round($row->value, 3),
$row->data->variable->unit->uom_name,
($row->inputOfficer !== NULL ? $row->inputOfficer->officer_name:''),
'<i class="fa fa-pencil-square-o"></i> Edit <i class="fa fa-trash-o"></i> Delete'
)
);
}
echo json_encode($response);
} else {
$url = $this->createUrl("dataAir/manage");
$delurl = $this->createUrl("dataAir/deleteRow");
$startdate = '2013-01-01';
$enddate = date_format(new DateTime(), 'Y-m-d');
$this->render('jqgrid', array(
'kategori'=>$kategori,
'url'=>$url,
'delurl'=>$delurl,
'startdate'=>$startdate,
'enddate'=>$enddate
));
}
}
this line causing the problem
if(isset($_REQUEST['dataid'])){
$dataid = $_REQUEST['dataid'];
$criteria->addCondition("dataid = $dataid");
}
when, I remove those lines the method work just fine. what could be the problem causing ambigous colum name? here is the error log
SELECT COUNT(DISTINCT "t"."inputdataid") FROM "app_inputdata" "t" LEFT OUTER JOIN "app_ref_periodicdata" "data" ON ("t"."dataid"="data"."dataid") WHERE ((date_input <= :enddate AND date_input >= :startdate) AND (dataid = 7)) AND (data.locationid=:locationid). Bound with :startdate='2013-01-01', :enddate='2015-02-02', :locationid='6'
You need to add the table alias t to your condition:
$criteria->addCondition("t.dataid = $dataid");
Also, since $dataid is being obtained from a $_REQUEST it is best to pass it as a parameter. This can be done in two ways:
$criteria->addCondition("t.dataid = :dataid", [":dataid" => $dataid]);
$criteria->compare("t.dataid", $dataid);
you have used table aliases,
'with'=>array(
'type'=>array(
'condition'=>'type.type_desc=:type_desc', <<- I mean here you have used alias : type
'params'=>array(':type_desc'=>$kategori)
)
you just have to remember that the main model that you are working with, will always need alias t to unambigufy! (not sure if that is an actual word :D )

How to grab contacts from gmail using google API's and contact grabber in PHP?

In my project i want to grab the contacts from gmail using google API's. I provide three keys such as client id, client secret and signature key. When i trying to get contacts the pop-up window is showing error message "Signature key must be formatted". What i have done wrong? Thanks in advance.
Here is my code
keyConfig.php
<?php
$apiRequestUrl = "https://stescodes.com/api/contactsapi.aspx"; // StesCodes contact grabber API request url
$originalsignaturekey = "lxFWDA5ng36sdvlFGukof75vyi";//replace with your signature key
$gmailConsumerKey = "1009516162377-n5s7lo5b4dvlt8e7s3rt12f8i02lpk1f.apps.googleusercontent.com";
$gmailConsumerSecret = "raCUba1smsZCzrVNjqFIqiqC";
$YahooConsumerKey = "your yahoo api key";
$YahooConsumerSecret = "your yahoo api key";
$LiveConsumerKey = "your live api key";
$LiveConsumerSecret = "your live api key";
$fbConsumerKey = "your facebook api key";
$fbConsumerSecret = "your facebook api key";
$callbackurl = "http://localhost/grab/oauth.php";// eg: return url after user authentication http://yourdomain/oauth.php
$currentdirpath = "http://dev.stescodes.com/";//your current web directory path eg:http://yourdomain/
?>
oauth.php
<?php
session_start();
?>
<?php include 'keyConfig.php'; ?>
<html>
<head><title></title>
<script>
function redirectrequest(a)
{
window.location = a;
}
function closepopup(a,b,c,d) {
window.opener.startGrabbingContactsOauth(a,b,c,d);
window.self.close();
}
</script>
</head>
<body>
<?php
$servicename = "gmail";
$token = "";
$ConsumerKey = "";
$ConsumerSecret="";
$tokensecret="";
$tokenverifier="";
$flag=0;
$parameters="";
if($_GET['currpage']!=null)
$_SESSION['currpage']=$_GET['currpage'];
if($_SESSION['currpage']=="gmail")
{
$servicename = "gmail";
$ConsumerKey = $gmailConsumerKey;
$ConsumerSecret = $gmailConsumerSecret;
if ($_GET['code'] != null)
{
$token = $_GET['code'];
$tokensecret = $_SESSION['tokensecret'];
$flag = 1;
}
}
else if($_SESSION['currpage']=="yahoo")
{
$servicename = "yahoo";
$ConsumerKey = $YahooConsumerKey;
$ConsumerSecret = $YahooConsumerSecret;
if (($_GET['oauth_token'] != null) && ($_GET['oauth_verifier'] != null))
{
$token = $_GET['oauth_token'];
$tokenverifier = $_GET['oauth_verifier'];
$tokensecret = $_SESSION['tokensecret'];
$flag = 1;
}
}
else if($_SESSION['currpage']=="facebook")
{
$servicename = "facebook";
$ConsumerKey = $fbConsumerKey;
$ConsumerSecret = $fbConsumerSecret;
if (($_GET['code'] != null))
{
$token = $_GET['code'];
$tokenverifier = "";
$tokensecret = "";
$flag = 1;
}
}
else if(($_SESSION['currpage']=="msn") || ($_SESSION['currpage']=="hotmail") || ($_SESSION['currpage']=="msnmessenger"))
{
$servicename = $_SESSION['currpage'];
$ConsumerKey = $LiveConsumerKey;
$ConsumerSecret = $LiveConsumerSecret;
//Live settings
if ($_GET["code"] != null)
{
$token = $_GET["code"];
$flag = 1;
}
}
if ($flag == 1)
{
$parameters = "type=accesstoken&ServiceName=" . urlencode($servicename) . "&ConsumerKey=" . urlencode($ConsumerKey) . "&ConsumerSecret=" . urlencode($ConsumerSecret);
$parameters = $parameters . "&ReturnUrl=" . urlencode($callbackurl) . "&Token=" . urlencode($token) . "&TokenSecret=" . urlencode($tokensecret) . "&TokenVerifier=" . urlencode($tokenverifier);
$result = file_get_contents($apiRequestUrl."?".$parameters);
$authdetails = json_decode($result,true);
$_SESSION['token'] = $authdetails[details][token];
$_SESSION['tokensecret'] = $authdetails[details][tokenSecret];
$_SESSION['uid'] = $authdetails[details][userID];
$_SESSION['tokenverifier'] = $_SESSION['tokenverifier'];
$_SESSION["consumerkey"] = $ConsumerKey;
$_SESSION["consumersecret"] = $ConsumerSecret;
echo "<SCRIPT LANGUAGE=\"javascript\"> closepopup('".$servicename."',". $result .",'".$ConsumerKey."','".$ConsumerSecret."');</SCRIPT>";
}
else
{
$parameters = "type=authenticationurl&ServiceName=" . urlencode($servicename) . "&ConsumerKey=" . urlencode($ConsumerKey) . "&ConsumerSecret=" . urlencode($ConsumerSecret);
$parameters = $parameters . "&ReturnUrl=" . urlencode($callbackurl) ;
$result = file_get_contents($apiRequestUrl."?".$parameters);
$authdetails = json_decode($result,true);
$_SESSION['token'] = $authdetails[details][token];
$_SESSION['tokensecret'] = $authdetails[details][tokenSecret];
$_SESSION['uid'] = $authdetails[details][userID];
$_SESSION['tokenverifier'] = $tokenverifier;
echo "<SCRIPT LANGUAGE=\"javascript\"> redirectrequest('".$authdetails[details][authUrl]."'); </SCRIPT>";
}
?>