Why Google Analytics doesn't track all my events with _setcustomvar? - wordpress

I'm using the following code
_gaq.push(['_setCustomVar',1,'logged-in','administrator',1],['_trackPageview']);
to track logged-in user levels on my site (running WordPress).
Now my problem is that in the last month I had around 100 new registrations, but Google Analytics only shows me 65 registered users active on my site.
Is this an error in interpreting the results or am I doing something wrong?

PREAMBLE
With Google Analytics(GA), it's impossible to get ALL your hits registred. This is not a GA specific problem. Any analytics tool can be affected.
Imagine for instance, that the user gets its connection broken while registring on your WP site. Chances are that the javascript code won't be executed. The new user will be registred hopefully, but GA won't be notified.
WORKAROUND
This workaround would be to tied the notification of GA with your registration process right on the server side:
Step 1: Register a php function with the user_register hook.
add_action('user_register', 'myplugin_registration_save');
function myplugin_registration_save($user_id) {
// GA will be notified here ...
}
Step 2: Inside this registred function notify GA of the new user registration.
Here comes php-ga. It's a GA client written in PHP. You can implement nearly every parameter and tracking feature of the original GA Javascript client. Call it to track your GA custom vars.
Here is a sample code from the php-ga site:
use UnitedPrototype\GoogleAnalytics;
// Initilize GA Tracker
$tracker = new GoogleAnalytics\Tracker('UA-12345678-9', 'example.com');
// Assemble Visitor information
// (could also get unserialized from database)
$visitor = new GoogleAnalytics\Visitor();
$visitor->setIpAddress($_SERVER['REMOTE_ADDR']);
$visitor->setUserAgent($_SERVER['HTTP_USER_AGENT']);
$visitor->setScreenResolution('1024x768');
// Assemble Session information
// (could also get unserialized from PHP session)
$session = new GoogleAnalytics\Session();
// Assemble Page information
$page = new GoogleAnalytics\Page('/page.html');
$page->setTitle('My Page');
// Track page view
$tracker->trackPageview($page, $session, $visitor);
THERE IS MORE
Even if you implement the workaround, it may not be able to notify GA sucessfully. If GA server experiment some heavy load for instance, your notification may be lost.
I would advice you to use both system notification : GA Javascript client AND GA PHP client.
Assign them two distinct events 'JS-new-user-registred' and 'PHP-new-user-registred'. With two registred events you improve the quality of your analytic data. You improve the new registrations notification rate too.
Always keep in mind that this approach may not be 100% accurate. For example, on the client side the ga.js file may be blocked (firewall etc). At the same time, your PHP client may not be able to notify succesfully GA. It results that the new registration is not tracked.

Related

How to handle the success URL on Stripe considering GET requests should be safe?

When we make a stripe checkout session we include a success url:
session = await this.stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: lineItems,
payment_intent_data: {
transfer_data: {
amount: 9999999,
destination: someaccountId,
},
},
success_url: `http://localhost:4000/api/checkout/success?true&session_id={CHECKOUT_SESSION_ID}&alias_id=${aliasId}`,
cancel_url: `http://localhost:4000/api/checkout/canceled?session_id={CHECKOUT_SESSION_ID}`,
});
The success URL is where stripe sends the user after a successful payment. It's a GET request since stripe is redirecting the user. Many apps using stripe will need to take actions after a successful checkout- sending an email receipt, notifications, sending paid content, updating the order in the database etc. But it's suggested not to do these actions in GET requests because GET requests are supposed to be idempotent and safe.
For example an unsubscribe link in an email should not unsubscribe a user but instead the "proper approach for unsubscribe links is to lead to a page where the user can click a button to unsubscribe (where the button click triggers a POST request)."src This is because "Many, many, many tools, utilities, web crawlers and other thingamajiggies assume that GET will never be a destructive action (rightly so, since it's specified this way). If you now break your application by breaking that specification, you'll get to keep both parts of your application." src
So I was wondering what is the proper way to handle the stripe success url? If we follow the suggested advice above, then the success url would link to a page where the user clicks a button that updates the order, emails a receipt, etc. But then we are relying on customer to finish the order that has already been paid for. If they don't press that button then important actions aren't completed. What is the proper way to do this? Or does the suggestion to not change the database on a GET request not apply for some reason to these type of actions?
Make the part of that page that handles the Checkout Session code idempotent - i.e. have it check first to see if its steps have already been processed (and in that case skip), or else make it so whatever processing it does could be repeated multiple times without having any additional effect after the first time it runs.
For "tools, utilities, web crawlers and other thingamajiggies" to hit your URL with a valid Checkout Session ID would be pretty close to impossible, so whatever code you use to handle a 'bad session ID' would handle that just fine.
You should also have a webhook for this - which would get a POST request. https://stripe.com/docs/payments/checkout/fulfill-orders#handle-the---event
If you are using a stripe template then you need to follow this step
Stripe Pricing Table -> edit -> Click on Don't show confirmation page -> add your web url (https://test.com/success?session_id={CHECKOUT_SESSION_ID}.
Stripe will update the checkout session-id for you

How to pass parameters from Wordpress Contact Form 7 to an external server?

I have a login form created in Wordpress using Contact form 7. I'm tryig to pass parameters from this form to an external server. But it is not happening.
I am a designer, and not much of a programmer. I understand code(sometimes) but can not write it from the scratch.
I have designed a website for a client. This client has a "Flying Returns" like logistic membership system in which members get lots of perks in shipping etc. This system is on their own server. They want the users to log in to that system from this website.
So I have created a login form using Contact Form 7. I have set skip_mail: on; I have tried a few plugins login, but either they dont log into different servers or are expensive, or does not yield correct URL and hence does not log into the system. Therefore I have finally decided to make it happen using code.
Their programmer has given me following JS code that will take the parameters from this form and pass on to their system. IF the parameters are correct, then the user is logged into the system and taken to the member's dashboard page on their server (not my website/server), else it returns an error message, {"error":"Login Data Incorrect.."}
I have tried to put this code with in the contact form. Here is the code (i've hidden the actual IP address, sorry):
<script>
document.addEventListener( 'wpcf7submit', function( event ) {
alert( "Fire!" );
document.location.href="http://49.XXX.XXX.202:XXXX/glslink/servlet/GPLogin?password="+$('#password').val()+"&emailid="+$('#emailid').val();
}, false );
</script>
If I remove the document.location line, it shows the alert. But the above, in its entirety does nothing. If I use the URL, replace variables with actual values and paste it browser, it logs me into the system without a hitch.
I have tried quite a few different codes which I could find as possible solution on internet, this site including, but to no avail.
Please help me out. I want the email and password to be passed to this external server, if they are correct then the user should log in and see their dashboard there. Else if it gives the above mentioned error message, then I should be able to reset the form and give an error message to the user.

Google Analytics API - inconsistent error "insufficientPermissions' (403)

Backgroud:
I have a PHP code that runs queries to Google Analytics API on behalf of my users.
I am using OAuth2 for authentication and storing the access-tokens of the users in my DB.
My code makes sure not to exceed the quota per user (10 QPS), and I'm using the "quotaUser" parameter in my queries.
The issue:
About 50% of my queries to GA are responded with error 403 ("insufficientPermissions", "User does not have sufficient permissions for this profile.").
The strange this is, that the other ~50% are getting the results from GA successfully.
Some important points:
The only thing common to all the successful queries and common to the unsuccessful queries is the batch that they are in: my code is sending a "batches" of queries (one after one with very short delay between them) to GA's API and every batch is ether passing or failing with 403.
Adding \ removing permissions to the scope did not solved the issue.
It is worth mentioning that this is not a View-ID \ Account-ID issue etc. as the same query can pass or fail for the same user and view.
I saw a related unanswered issue here and couldn't find any other truly-related issues.
A snippet from my code:
//Create a Google Client
$client = new Google_Client();
$client->setAuthConfigFile($this->secretJson);
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Oauth2::PLUS_LOGIN, Google_Service_Analytics::ANALYTICS);
// Set the access token on the client.
$client->setAccessToken($accessToken);
// Create an authorized analytics service object.
$this->analytics = new Google_Service_Analytics($client);
...
//Run the query
$results = $this->analytics->data_ga->get($id, $startDate, $endDate, $metrics, $opts);
Ido, can you still reproduce this issue? It sounds very much like there is a problem with your access token. I would start troubleshooting by making sure you are setting the same access token for all batch runs and validating that the token is not expired (isAccessTokenExpired()).

How to measure the number of people disabling push notifications from my progressive web app?

I'm using the new web push API with service workers in my progressive web app but am worried about users disabling the push notification permission after originally enabling it.
What is the best way to detect users disabling the notification permission (i.e. add instrumentation/analytics) so I can track this?
I believe what you're looking is covered in the Permissions API, which includes a change event. That event is fired both for the initial user decision and again if the user later changes their mind.
At its most basic, you could do:
if ('permissions' in navigator) {
navigator.permissions.query({name:'notifications'}).then(function(notificationPerm) {
// notificationPerm.state is one of 'granted', 'denied', or 'prompt'.
// At this point you can compare notificationPerm.state to a previously
// cached value, and also listen for changes while the page is open via
// the onchange handler.
notificationPerm.onchange = function() {
// Permissions have changed while the page is open.
// Do something based on the current notificationPerm.state value.
};
});
}
There are a few good resources out there demonstrating how this could be used:
https://developers.google.com/web/updates/2015/04/permissions-api-for-the-web
https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API
https://github.com/GoogleChrome/samples/tree/gh-pages/permissions
The Permissions API is supported in Chrome as of version 43, and Firefox as of the upcoming version 45 release.

Error 'Login Required' while calling Google Analytics API from Google Spreadsheet

I use google scripts to fill Google Spreadsheet by Google Analytics data.
Problem: I get error: Login Required when I call =getCountOfNewUsers(B1,B2) from my Spreadsheet file. NOTE: when I run runTest() from google script project everything working OK.
FYI: I have followed this tutorial.
function runTest() {
try {
var results = getCountOfNewUsers(new Date(), new Date());
Logger.log(results.totalsForAllResults["ga:newVisits"]);
} catch(error) {
Logger.log(error.message);
}
}
function getCountOfNewUsers(date_from, date_till) {
date_from = Utilities.formatDate(date_from, 'GMT', 'yyyy-MM-dd');
date_till = Utilities.formatDate(date_till, 'GMT', 'yyyy-MM-dd');
var tableId = 'ga:*****';
// Make a request to the API.
var results = Analytics.Data.Ga.get(tableId, date_from, date_till, 'ga:newVisits', {});
if (results.getRows()) {
return results;
} else {
throw new Error('No views (profiles) found');
}
}
This is not solution to your question but it directs you to easy better solution to your problem if your interested!, you can easily setup this solution in an hour!
Details:
Better Than A writing our own script with Diligent Study and make Google scripts to fill Google Spreadsheet by Google Analytics data I use this Google Analytics Report Automation (Magic Script)
This Magic Script allow you to simplifies this process and makes it
easy to get the data you want so that you can focus on analysis and
reporting.
Custom API Dashboards - No Code Required it will save your burden for
Writing Your Own Script.
About the Error Try following things
Go to script editor, click on Resources > click on Use Google APIs.
Click on "Google APIs Console".
select APIs & auth > click on Registered apps.
Do Register your script project as web application.
select Certificate > Generate New Key .
This is an expected behavior. Custom Functions cannot ask users to give access to personal data. So they are not suitable for all types of services, specifically those which need authorization for personal data.
Check this url to know which services you can use - https://developers.google.com/apps-script/guides/sheets/functions#using_apps_script_services
Unlike most other types of Apps Scripts, custom functions never ask users to authorize access to personal data. Consequently, they can only call services that do not have access to personal data

Resources