google analytics api need exact date, hour and minute - google-analytics

Im experimenting with the google reports api (v4), im using the goalCompletionsAll metric, and is bringing the info that i need, im passing as parameters ga:medium, ga:date, ga:hour however when i pass the ga:minute parameter as request it throws me the following error: "Selected dimensions and metrics cannot be queried together." I understand that the metrics have their own set of dimensions, but i found this weird, since when i use the query explorer i add all this dimensions and it returns the correct info, but as soon as i put in the code, it displays the error...
Here i attach my code to see if someone can point me into the right direction regarding this.
<?php
require_once 'google-api-php-client/src/Google/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('xxxxx');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Create an authorized analytics service object.
$analytics = new Google_Service_AnalyticsReporting($client);
// Call the Analytics Reporting API V4.
$response = getReport($analytics);
// Print the response.
printResults($response);
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/api/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
function getReport(&$analytics) {
// Replace with your view ID. E.g., XXXX.
$VIEW_ID = "xxxxxxxx";
// Create the DateRange object.
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate("2016-01-01");
$dateRange->setEndDate("today");
// Create the Metrics object.
$sessions = new Google_Service_AnalyticsReporting_Metric();
$sessions->setExpression("ga:goalCompletionsAll");
$sessions->setAlias("objetivos");
//Create the Dimensions object.
$medium = new Google_Service_Analyticsreporting_Dimension();
$medium->setName("ga:medium");
$minute = new Google_Service_Analyticsreporting_Dimension();
$minute->setName("ga:minute");
$hour = new Google_Service_Analyticsreporting_Dimension();
$hour->setName("ga:hour");
$date = new Google_Service_Analyticsreporting_Dimension();
$date->setName("ga:date");
$avgpageloadtime = new Google_Service_Analyticsreporting_Metric();
$avgpageloadtime->setExpression("ga:avgpageloadtime");
$avgpageloadtime->setAlias("average load time");
$goals = new Google_Service_Analyticsreporting_Metric();
$goals->setExpression("ga:goalStartsAll");
// Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($VIEW_ID);
$request->setDateRanges($dateRange);
$request->setDimensions(array($medium, $date, $hour, $minute));
$request->setMetrics(array($sessions, $avgpageloadtime, $goals));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests( array( $request) );
return $analytics->reports->batchGet( $body );
}
function printResults(&$reports) {
for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
$report = $reports[ $reportIndex ];
$header = $report->getColumnHeader();
$dimensionHeaders = $header->getDimensions();
$metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
$rows = $report->getData()->getRows();
for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
$row = $rows[ $rowIndex ];
$dimensions = $row->getDimensions();
$metrics = $row->getMetrics();
for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n");
}
echo "<br>";
for ($j = 0; $j < count( $metricHeaders ) && $j < count( $metrics ); $j++) {
$entry = $metricHeaders[$j];
$values = $metrics[$j];
//print("Tipo de metrica: " . $entry->getType() . "\n" );
for ( $valueIndex = 0; $valueIndex < count( $values->getValues() ); $valueIndex++ ) {
$value = $values->getValues()[ $valueIndex ];
//echo $values->getValues()[$valueIndex]."<br>";
//print($entry->getName() . ": " . $value . "<br>");
}
}
}
}
}
?>
Thanks in advance.

The issue you are seeing is that in the query explorer you are querying for ga:goalCompletionsAll and the V4 API you are querying for ga:gaolStartsAll which happens to be incompatible with ga:avgPageLoadTime:
See the Dimensions and Metrics Explorer for details of which dimensions are incompatible with others.
Remove the ga:avgPageLoadTime and you should be able to get the information you need.
TLDR: your V4 API request has different metrics than the Query Explorer Request.

Related

How to check type of order notes in woocommerce

How to check the type of order notes in woocommerce?
I want to check the note is private_note or customer_note.
Here is my code:
//add_action('wp_insert_comment','hook_insert_func',100,2);
add_filter( 'comments_clauses','hook_insert_func',100,2);
function hook_insert_func($id, $comment){
if($comment->comment_type!='order_note')
return;
if($comment->comment_type == 'order_note'){
$mobile = PWooSMS()->buyerMobile($comment->comment_post_ID);
$data = array();
$data['type'] = 1;
$data['mobile'] = "$mobile";
$data['message'] = $comment->comment_content;
$response = PWooSMS()->SendSMS( $data );
}
}

Wordpress do_shortcode not working when new user is created

I am currently using Groups plugin and I want a new user is assigned automatically to a group when it is created. $groupName prints out loggedin user's group(contributor) and when a contributor creates a new user (subscriber), subscriber should have the same group as contributor. Debugger showed $groupName correctly, but the do_shortcode part does not work. Do you have any idea?
add_action( 'user_register', array($this, 'create_user'), 10, 1 );
function create_user($user_id) {
global $wpdb;
//Get current user's group id from database
$getValue = $wpdb->get_results("SELECT user_id , wp_groups_group.group_id, wp_groups_user_group.group_id, name FROM wp_groups_group, wp_groups_user_group WHERE wp_groups_group.group_id = wp_groups_user_group.group_id");
$currentUser = wp_get_current_user();
$currentUserID = $currentUser->ID;
$groupID = "";
$groupName = "";
foreach ($getValue as $key => $value) {
if ($currentUserID == $value->user_id && $value->group_id > 1) {
$groupID = $value->group_id;
$groupName = $value->name;
}else{
}
}
do_shortcode('[groups_join group="'.$groupName.'"]');
}

InvalidArgumentException - The current node list is empty.

I am using goutte sracper to scrape the data , i m getting error like InvalidArgumentException - The current node list is empty. Below is the code which i m using
$string = $crawler->filter('div#links.results')->html();
if ( empty( $string ) )
return false;
$dom = new \DOMDocument;
$state = libxml_use_internal_errors(true);
$dom->loadHTML($string);
libxml_use_internal_errors($state);
$xp = new \DOMXPath($dom);
$divNodeList = $xp->query('//div[contains(#class, "results_links_deep")]
[contains(#class, "web-result")]
/div[contains(#class, "links_main")]
[contains(#class, "links_deep")]
[contains(#class, "result__body")]');
$results = [];
if(count($divNodeList) > 0){
foreach ($divNodeList as $divNode) {
$results[] = [
trim($xp->evaluate('string(./h2/a[#class="result__a"])', $divNode)),
trim($xp->evaluate('string(.//a[#class="result__snippet"])', $divNode)),
trim($xp->evaluate('string(.//a[#class="result__url"])', $divNode))
];
}
}
I tried using the solution as below
if ($crawler->filter('div#links.results')->count() > 0 ) {
$string = $crawler->filter('div#links.results')->html()
}
then it started giving another error like DOMDocument::loadHTML(): Empty string supplied as input
Any suggestions please ?
Your filterdid not return any results. That is why it crashed. That's how I solved this issue, by adding a try catch.
try {
$string = $crawler->filter('div#links.results')->html()
} catch (\InvalidArgumentException $e) {
// Handle the current node list is empty..
}

Get total price after ajax update in woocommerce

I am trying to take the price in the filter woocommerce_update_order_review_fragments, but failing to understand where it resides
add_filter('woocommerce_update_order_review_fragments', 'price_bottom_checkout');
function price_bottom_checkout($arr) {
$price = ? // how to get it over here?
$price_txt = '<span class="total-pay">'.$price.'</span>';
$arr['.total-pay'] = $price;
return $arr;
}
Managed to find out how. Needed to see the session cart which is updated on every cart refresh via ajax.
add_filter('woocommerce_update_order_review_fragments', 'price_bottom_checkout');
function price_bottom_checkout($arr) {
global $woocommerce;
$the_total = '';
foreach ($woocommerce->cart->cart_contents as $cart_item) {
$the_total = $cart_item['line_total'];
break;
}
$price_txt = '<span class="total-pay">'.wc_price($the_total).'</span>';
$arr['.total-pay'] = $price_txt;
return $arr;
}

Authorize.Net API: Define a default credit card for charging

I have saved multiple Payment Profiles for a single customer in authorize.net. Each Payment Profile contains a credit card information.
I have two questions
1) Which credit card will be charge, When I am charging a transaction of customer who have multiple Payment Profile.
2) Is there any way to define a default credit card to charge.
Thanks
Currently there is no way to create a default payment profile for payments. One must always be passed with each createCustomerProfileTransactionRequest call.
in updateCustomerPaymentProfileRequest page , I see this content:
defaultPaymentProfile : When set to true, this field designates the payment profile as the default payment profile.
When a default payment profile has been designated, you can use getCustomerPaymentProfileRequest with customerProfileId as the only parameter.
it will work 100% to set default payment profile
$paymentprofile = new AnetAPI\CustomerPaymentProfileExType();
$paymentprofile->setCustomerPaymentProfileId($payment_detail['payment_profile_id']);
$paymentprofile->setBillTo($billto);
$paymentprofile->setPayment($paymentCreditCard);
$paymentprofile->setDefaultPaymentProfile($payment_detail['default_payment']);
All the other answers don't allow for UPDATING an existing payment profile but only CREATING a new payment profile. I know this is PHP but hopefully it will help someone, since I couldn't find anything related to this.
function paymentProfileUpdateDefault($profile_id, $payment_profile_id) {
$success = false;
$message = '';
$error_message = '';
// Create a merchantAuthenticationType object with authentication details
$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
$merchantAuthentication->setName($GLOBALS["authorizeNet"]["login_id"]);
$merchantAuthentication->setTransactionKey($GLOBALS["authorizeNet"]["transaction_key"]);
// Set the transaction's refId
$refId = 'ref' . time();
$request = new AnetAPI\GetCustomerPaymentProfileRequest();
$request->setMerchantAuthentication($merchantAuthentication);
$request->setRefId($refId);
$request->setCustomerProfileId($profile_id);
$request->setCustomerPaymentProfileId($payment_profile_id);
$controller = new AnetController\GetCustomerPaymentProfileController($request);
// Get the response
$response = $controller->executeWithApiResponse($GLOBALS["authorizeNet"]["api_endpoint"]);
if (($response != null) && ($response->getMessages()->getResultCode() == "Ok") ){
$billto = $response->getPaymentProfile()->getbillTo();
$old_billto_obj = json_encode($billto, JSON_FORCE_OBJECT);
$old_billto_arr = json_decode($old_billto_obj, true);
$billto->setFirstName($old_billto_arr['firstName']);
$billto->setLastName($old_billto_arr['lastName']);
$old_paymentprofile = $response->getPaymentProfile();
$old_paymentprofile_obj = json_encode($old_paymentprofile, JSON_FORCE_OBJECT);
$old_paymentprofile_arr = json_decode($old_paymentprofile_obj, true);
$creditCard = new AnetAPI\CreditCardType();
$creditCard->setCardNumber( $old_paymentprofile_arr['payment']['creditCard']['cardNumber'] );
$creditCard->setExpirationDate( $old_paymentprofile_arr['payment']['creditCard']['expirationDate'] );
$paymentCreditCard = new AnetAPI\PaymentType();
$paymentCreditCard->setCreditCard($creditCard);
$paymentprofile = new AnetAPI\CustomerPaymentProfileExType();
$paymentprofile->setCustomerPaymentProfileId($payment_profile_id);
$paymentprofile->setDefaultPaymentProfile(true); // Setting to default here
$paymentprofile->setBillTo($billto);
$paymentprofile->setPayment($paymentCreditCard);
// Submit a UpdatePaymentProfileRequest
$request = new AnetAPI\UpdateCustomerPaymentProfileRequest();
$request->setMerchantAuthentication($merchantAuthentication);
$request->setCustomerProfileId($profile_id);
$request->setPaymentProfile($paymentprofile);
$controller = new AnetController\UpdateCustomerPaymentProfileController($request);
$response = $controller->executeWithApiResponse($GLOBALS["authorizeNet"]["api_endpoint"]);
if (($response != null) && ($response->getMessages()->getResultCode() == "Ok") ){
$Message = $response->getMessages()->getMessage();
$success = true;
} else if ($response != null){
$errorMessages_obj = $response->getMessages()->getMessage();
$errorMessages_obj = json_encode($errorMessages_obj, JSON_FORCE_OBJECT);
$errorMessages_arr = json_decode($errorMessages_obj, true);
$error_message = $errorMessages_arr[0]['text'];
$message = 'There was an error';
}
} else {
$errorMessages_obj = $response->getMessages()->getMessage();
$errorMessages_obj = json_encode($errorMessages_obj, JSON_FORCE_OBJECT);
$errorMessages_arr = json_decode($errorMessages_obj, true);
$error_message = $errorMessages_arr[0]['text'];
$message = 'There was an error';
}
return array('success'=>$success, 'message'=>$message, 'error'=>$error_message, 'data'=>$old_paymentprofile_arr);
}

Resources