Google Analytics PHP API : goals not found - php

In my company we decided to use Google Analytics to get some intersting metrics about visitors, entrance channels etc ...
I created a goal which is "triggered" when a visitor submit the contact form, everything work perfectly well and I even created a segment to preview the difference between people who use the form and the others.
Using the PHP API, i have my own dashboard table giving me some details about each session, one by one, with :
every visited URL
date & time
if come from Adwords, then the keywords
Below a screenshot from my dashboard, with a visitor who went to my website thought the homepage (first row), then submit the contact form (second row).
My own datas table from GA PHP API
But.. i do not manage to link those datas with my goal !
I tried metrics like :
ga:goal1start
ga:goal1Completions
ga:goal1Value
ga:goal1ConversationRate
(https://developers.google.com/analytics/devguides/reporting/core/dimsmets)
Whatever the metric I test (last column in my screnshot), the metric = 0 but I see completed goals in my Google Analytics dashboard for some of those sessions.
Is there something wrong ?
Thanks for your help ;)
EDIT 01/10 - Below is my PHP code :
$optParams = array(
'dimensions' => 'ga:dimension3, ga:pagePath, ga:date, ga:adMatchedQuery, ga:hour',
'sort' => '-ga:date, -ga:hour',
//'filters' => 'ga:medium==organic',
'max-results' => '99999');
return $analytics->data_ga->get(
'ga:' . $profileId,
'30daysAgo',
'today',
'ga:pageviews, ga:goal2Completions ',
$optParams);
And this is one row from the result :
array(7) {
[0]=>
string(12) "John Cena" // ga:dimension3
[1]=>
string(32) "/financial-expertise.php" // ga:pagePath
[2]=>
string(8) "20170110" // ga:date
[3]=>
string(9) "(not set)" // ga:adMatchedQuery
[4]=>
string(2) "12" // ga:hour
[5]=>
string(1) "1" // ga:pageviews
[6]=>
string(1) "0" // ga:goal2Completions ??
}
As you would see, the key "6" is related to the "ga:goal2Completions" metrics and in the above array, I guess it should be at least "1" ?

for the php code
can you try this one and tell me if its work or not ==>
$optParams = array(
'dimensions' => 'ga:dimension3, ga:pagePath, ga:date, ga:adMatchedQuery, ga:hour',
'sort' => '-ga:date, -ga:hour',
//'filters' => 'ga:medium==organic',
$metrics = 'ga:pageviews, ga:goal2Completions';
$from = date('Y-m-d', strtotime("last day of -1 month"));
$to = date('Y-m-d', strtotime("today"));
try {
$campaigns = $service->data_ga->get( 'ga:' . $profileId,
$from,
$to ,
$metrics,
$optParams);
} catch (\Google_Exception $e) {
$message = sprintf("<h3>Oups !</h3>
<p>Request to analytics failed.
Google error message was :</p>
<p><q>%s</q></p>", htmlspecialchars( $e->getMessage() ));
you need to { print_r } $compaigns and see the results

OK after hours of research .. no solution. So I have edited my goal to be equal to an event and then change my report to extract event. That works. Thx for your help!

Related

PHP and Pods: Combine array values only into new array

Long time user, first time poster. The forums here have got me out of a lot of trouble but I'm really stuck on this one.
I'm using Pods for a Custom Post Type that has a Custom Field where a user can enter a numeric value. eg. or 4 or 2 etc
I want to display the total sum of this Custom Field across all user made posts on the front end. To achieve this I'm using a Pods Template to make a short code for the front end, but to do the calculation I'm using PHP.
So my current PHP is:
function jobs_total ($id) {
$pods = pods ('pledged_job', $id);
$jobs = ($pods->field ('jobs_pledged'));
$a = ($jobs);
$b = explode(' ', $a);
var_dump($b);
}
And the result I get so far is:
array(1) { [0]=> string(1) "5" }
array(1) { [0]=> string(1) "4" }
array(1) { [0]=> string(1) "2" }
array(1) { [0]=> string(1) "7" }
How do I take the numeric values from "_", which are correctly appearing from post entries, and combine them in a new array so I can perform an 'array_sum' and return the total of those numbers?!
I'm a PHP novice so I'm not sure if this is obvious or if it's a clash between Pods terms and standard PHP.
Thanks in advance!!
Final code wrapped in shortcode to allow for displaying on the frontend through Elementor
function jobs_shortcode () {
$jobs = get_posts(array(
'post_type' => 'pledged_job',
'post_status' => 'publish',
'numberposts' => -1, ));
$total = 0;
foreach ($jobs as $field) {
$total += (int) get_post_meta($field->ID, 'jobs_pledged', true);
}
echo $total;
}
add_shortcode( 'jobs', 'jobs_shortcode' );

Stripe API: Filter Paid and Unpaid Invoices

I'm new to using the Stripe API and I'm running into trouble trying to get a list of unpaid and paid invoices from a particular customer.
To preface using an example: I have a customer, they have 1 unpaid invoice and 0 paid invoices. There have been 19 failed payment attempts and none that were successful. I want to show a list of paid invoices (which there should be 0) and unpaid (which there should be 1).
When I retrieve invoices using the following code:
$response = \Stripe\Invoice::all(array("customer" => $cust, "paid" => false));
It returns object(Stripe\Collection)#7 (7) { ["_requestParams":protected]=> array(2) { ["customer"]=> string(18) "CUST_ID" ["paid"]=> bool(false) } ...
It's showing one record which is what I want but I don't believe it's retrieving the unpaid invoice.
Now if I try to retrieve invoices using the following:
$response = \Stripe\Invoice::all(array("customer" => $cust, "paid" => true));
I get an entire page of objects the first line of which being: object(Stripe\Collection)#7 (7) { ["_requestParams":protected]=> array(2) { ["customer"]=> string(18) "CUST_ID" ["paid"]=> bool(true) }...
With the ["paid"] => bool(true) line appearing 10 times.
I've been looking at the Stripe API documentation but it doesn't really seem to show examples of what I'm looking for.
Any help would be greatly appreciated :)
I've filtered invoice using below arguments
$response = \Stripe\Invoice::all(array("customer" => $cust, "billing" => charge_automatically));
Ex.
billing => charge_automatically
billing:
The billing mode of the invoice to retrieve. Either charge_automatically or send_invoice.
For more details, https://stripe.com/docs/api#list_invoices
Thank you.

Why is it when I take 3 array values it shows error but when I only show 1 value it works?

When I use var_dump($paid) it will show all the values
this is the code. If I use all 3 description, amount, and payment_type it will show an error that the amount is undefined. But if I use only 1 like for example I use only the description and erase the rest the code will work
$paid = array();
foreach ( $user as $u ) :
$paidDetail = \App\PaymentTransaction::where('user_id','=', $u->user_id)->get();
if ($paidDetail->count()) :
$paid[]['description'] = $paidDetail[0]->description;
$paid[]['amount'] = $paidDetail[0]->amount;
$paid[]['payment_type'] = $paidDetail[0]->payment_type;
endif;
endforeach;
return $paid;
this is for the view/blade to show the details in the frontend
{{ $paid['description'] }}
{{ $paid['amount'] }}
{{ $paid['payment_type'] }}
showing each 1 of them works but showing all of them at the same time will show an error saying that the 2nd value is undefined
Below is the var_dump($paid)
array(1) { ["description"]=> string(33) "Plan Subscription Payment for PRO" }
array(1) { ["amount"]=> float(350) }
array(1) { ["payment_type"]=> string(27) "Stripe Payment Subscription" }
array(1) { ["description"]=> string(38) "Test Plan Subscription Payment for PRO" }
array(1) { ["amount"]=> float(351) }
array(1) { ["payment_type"]=> string(27) "Stripe Payment Subscription" }
It's just because,
Your foreach loop overwriting 0 Index Parameters and every time last record stores in Array.
And Executing query in every iteration of foreach loop may reduce your code performance.
You Should use laravel eloquent model and relationship for this issue.
https://laravel.com/docs/5.5/eloquent-relationships
Try this:
$paid = array();
$i=0;
foreach ( $user as $u ) :
$paidDetail = \App\PaymentTransaction::where('user_id','=', $u->user_id)->get();
if ($paidDetail->count()) :
$paid[$i]['description'] = $paidDetail[0]->description;
$paid[$i]['amount'] = $paidDetail[0]->amount;
$paid[$i]['payment_type'] = $paidDetail[0]->payment_type;
$i++;
endif;
endforeach;
return $paid;
The main issue with you code is that you forgot to use a index on you array. Adding $i as an index makes sure that each user payment have his own index.
Note
Lopping thru an collection and doing a SQL QUERY for each user is not wrong but also not a good practice. Try to get both in one SQL Statment.

CakePHP: Custom pagination with an array

I am trying to paginate an array in CakePHP. The array is extracted from a JSON file, thus not using any database queries or whatsoever. I'm trying to stick to the functions of CakePHP to make sure I don't write useless code. I have been looking around and can not find any answer on my question.
The array is as of the following:
array(161) {
[0]=> array(8) {
["id"]=> int(589)
["status"]=> string(7) "running"
["threads"]=> int(12)
["create_time"]=> float(1487712882.42)
["memory_usage_precent"]=> float(11.0328674316)
["cpu_usage_precent"]=> int(62)
["cwd"]=> string(1) "/"
["process_name"]=> string(16) "plugin-container"
}
}
This is one row of the 161 rows in the array. How can I paginate this by using CakePHP's methods?
Here is an example for making pagination from Array
Step 1 - PHP Data Array :
$data = [
[
"id"=> 0,
"status"=> "running"
],[
"id"=> 1,
"status"=> "running"
],
#More Arrays ...
];
Step 2 - Prepare Data [Calculations]
$TotalDatas = count($data); #Total number of Data in Array
$StartFrom = 0; #Start from Array index
$DisplayLimit = 2; #Limit the result per page
$CurrentPage = isset($_GET['page'])? $_GET['page'] : 0; #Get the page number value from URL
$StartFrom = $CurrentPage*$DisplayLimit; #Update the Array index by calculating Page number and Limit
Step 3 - Display Data using loop :
for($i=$StartFrom; $i<$StartFrom+$DisplayLimit; $i++){ #Increase the Array index by Limit
if($i>=$TotalDatas){
continue; #Break Or put some message, Because no more Data in Array
}
var_dump($data[$i]);
}
Browse URL like as - localhost?page={PAGE_MUNBER_HERE}
Example :
localhost?page=3
Note : Above codes is the simple example of basic pagination.

How to perform a search query using Services_Twitter?

I am trying to perform a Twitter search using the PEAR package Services_Twitter.
Unfortunately this only returns an array of status ids, for example (var_dump):
object(stdClass)#88 (2) {
["statuses"]=>
array(11) {
[0]=>
int(49497593539)
[1]=>
int(49497593851)
[2]=>
int(49497598001)
[3]=>
int(49497599055)
[4]=>
int(49497599597)
[5]=>
int(49497600733)
[6]=>
int(49497602607)
[7]=>
int(49497607031)
[8]=>
int(49497607453)
[9]=>
int(49497609577)
[10]=>
int(49497610605)
}
["created_in"]=>
float(0.008847)
}
The script I'm using is similar to this test script I wrote:
<?php
//$oAuth = new HTTP_OAuth_Consumer( /** Supply oAuth details here **/ );
$Twitter = new Services_Twitter();
//$Twitter->setOAuth($oAuth);
try {
$Response = $Twitter->search(array(
"q" => "#FF -RT OR #FollowFriday -RT",
"rpp" => 10,
"since_id" => 23982086000,
"result_type" => "recent"
));
var_dump($Response);
} catch (Exception $e) {
fwrite(STDERR, $e->getMessage());
}
?>
Since I want to scan the tweets for certain words and want to know when it was posted and by whom, I would need to request all these statuses one by one.
But according to the example response in the Twitter API documentation they already return all the necessary information about the tweets (which is kinda obvious).
So, the question is: How can I access this information using Services_Twitter?
Kind Regards,
Arno
So as I said ->search() is wrapped through Services_Twitter::__call().
But here's the mis-understanding!
Two searches:
http://api.twitter.com/1/search.json?q=#noradio
http://search.twitter.com/search.json?q=#noradio
This is confusing as search.twitter.com returns the results as you'd expect them and the other API method just the status IDs.
For some reason only when you search for trends search.twitter.com is used. Otherwise it's the API methods. If you want to help, please open a ticket on PEAR and I can try to implement this for you.
A quickfix for you is this script:
<?php
$uri = 'http://search.twitter.com/search.json?';
$uri .= http_build_query(
array(
"q" => "#FF -RT OR #FollowFriday -RT",
"rpp" => 10,
"since_id" => 23982086000,
"result_type" => "recent"
));
$response = file_get_contents($uri);
if ($response === false) {
fwrite(STDERR, "Could not fetch search result.");
exit(1);
}
$data = json_decode($response);
var_dump($data);
Are you using a custom Services_Twitter, I just did a search through the class via Pear Documentation and was unable to find the search function. However, it seems like most of the returns for that class is a simple_xml object. Given that I would look through the documentation there and see how you can pull that data out. It would also help looking at how Twitter returns the response in XML format.

Categories