Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GA Ecommerce transaction tracking #14

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
46 changes: 43 additions & 3 deletions src/android/GAPlugin.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,32 @@
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONObject;

import com.google.analytics.tracking.android.GAServiceManager;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;
import com.google.analytics.tracking.android.Transaction;
import com.google.analytics.tracking.android.Transaction.*;

public class GAPlugin extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, CallbackContext callback) {
GoogleAnalytics ga = GoogleAnalytics.getInstance(cordova.getActivity());
Tracker tracker = ga.getDefaultTracker();
Tracker tracker = ga.getDefaultTracker();

if (action.equals("initGA")) {
try {
tracker = ga.getTracker(args.getString(0));
GAServiceManager.getInstance().setDispatchPeriod(args.getInt(1));
ga.setDefaultTracker(tracker);
callback.success("initGA - id = " + args.getString(0) + "; interval = " + args.getInt(1) + " seconds");

// set debug mode
if(args.getBoolean(2)){
ga.setDebug(true);
}

callback.success("initGA - id = " + args.getString(0) + "; interval = " + args.getInt(1) + " seconds; "+" isDebugEnabled = "+ga.isDebugEnabled());
return true;
} catch (final Exception e) {
callback.error(e.getMessage());
Expand Down Expand Up @@ -69,12 +78,43 @@ else if (action.equals("setDimension")) {
else if (action.equals("setMetric")) {
try {
tracker.setCustomMetric(args.getInt(0), args.getLong(1));
callback.success("setVariable passed - index = " + args.getInt(2) + "; key = " + args.getString(0) + "; value = " + args.getString(1));
callback.success("setMetric passed - index = " + args.getInt(2) + "; key = " + args.getString(0) + "; value = " + args.getString(1));
return true;
} catch (final Exception e) {
callback.error(e.getMessage());
}
}
else if (action.equals("trackTransaction")) {
try {
Transaction trans = new Transaction.Builder(
args.getString(0),
(long)(args.getDouble(1) * 1000000)
)
.setShippingCostInMicros(0)
.setCurrencyCode(args.getString(2))
.build();

JSONArray items = args.getJSONArray(3);

for(int i=0; i<items.length(); i++){
JSONObject item = items.getJSONObject(i);
trans.addItem(new Item.Builder(
item.getString("sku"),
item.getString("name"),
(long)(item.getDouble("price") * 1000000),
item.getLong("quantity"))
.setProductCategory(item.getString("category"))
.build());
}
tracker.sendTransaction(trans);

callback.success("trackTransaction - transactionId = " + args.getString(0) + "; orderTotal = " + args.getLong(1) + "; items = " + args.getJSONArray(2).toString());
return true;
} catch (final Exception e) {
callback.error(e.getMessage());
}
}

return false;
}
}
Expand Down
3 changes: 3 additions & 0 deletions src/ios/GAPlugin.h
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,8 @@
- (void) trackEvent:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
- (void) trackPage:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
- (void) setVariable:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
- (void) setDimension:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
- (void) setMetric:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;
- (void) trackTransaction:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options;

@end
83 changes: 83 additions & 0 deletions src/ios/GAPlugin.m
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,89 @@ - (void) setVariable:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)o
[self failWithMessage:@"setVariable failed - not initialized" toID:callbackId withError:nil];
}

- (void) setDimension:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options
{
NSString *callbackId = [arguments pop];
NSInteger index = [[arguments objectAtIndex:0] intValue];
NSString *value = [arguments objectAtIndex:1];

if (inited)
{
NSError *error = nil;
BOOL result = [[[GAI sharedInstance] defaultTracker] setCustom:index dimension:value];

if (result)
[self successWithMessage:[NSString stringWithFormat:@"setDimension: index = %d, value = %@;", index, value] toID:callbackId];
else
[self failWithMessage:@"setDimension failed" toID:callbackId withError:error];
}
else
[self failWithMessage:@"setDimension failed - not initialized" toID:callbackId withError:nil];
}

- (void) setMetric:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options
{
NSString *callbackId = [arguments pop];
NSInteger index = [[arguments objectAtIndex:0] intValue];
NSNumber *value = [arguments objectAtIndex:1];

if (inited)
{
NSError *error = nil;
BOOL result = [[[GAI sharedInstance] defaultTracker] setCustom:index metric:value];

if (result)
[self successWithMessage:[NSString stringWithFormat:@"setMetric: index = %d, value = %@;", index, value] toID:callbackId];
else
[self failWithMessage:@"setMetric failed" toID:callbackId withError:error];
}
else
[self failWithMessage:@"setVariable failed - not initialized" toID:callbackId withError:nil];
}


- (void) trackTransaction:(NSMutableArray *)arguments withDict:(NSMutableDictionary *)options
{
NSString *callbackId = [arguments pop];
NSString *transId = [arguments objectAtIndex:0];
int64_t orderTotal = (int64_t)([[arguments objectAtIndex:1] doubleValue] * 1000000);
NSString *currencyCode = [arguments objectAtIndex:2]; // Not yet available in iOS GA SDK
NSArray *items = [arguments objectAtIndex:3];

if(inited){
NSError *error = nil;
GAITransaction *transaction =
[GAITransaction transactionWithId:transId // (NSString) Transaction ID, should be unique.
withAffiliation:@"In-App Store"]; // (NSString) Affiliation
transaction.shippingMicros = (int64_t)(0); // (int64_t) Total shipping (in micros)
transaction.revenueMicros = (orderTotal); // (int64_t) Total revenue (in micros)

for (NSDictionary *item in items ){
NSString* sku = [item objectForKey:@"sku"];
NSString* name = [item objectForKey:@"name"];
NSString* category = [item objectForKey:@"category"];
int64_t price = (int64_t)([[item objectForKey:@"price"] doubleValue] * 1000000);
NSInteger quantity = [[item objectForKey:@"quantity"] integerValue];

[transaction addItemWithCode:sku // (NSString) Product SKU
name:name // (NSString) Product name
category:category // (NSString) Product category
priceMicros:price // (int64_t) Product price (in micros)
quantity:quantity]; // (NSInteger) Product quantity
}

BOOL result = [[GAI sharedInstance].defaultTracker sendTransaction:transaction]; // Send the transaction
if(result)
[self successWithMessage:[NSString stringWithFormat:@"trackTransaction: transactionId = %@ OK", transId] toID:callbackId];
else
[self failWithMessage:@"trackTransaction failed" toID:callbackId withError:error];
} else {
[self failWithMessage:@"trackTransaction failed - not initialized" toID:callbackId withError:nil];
}

[self failWithMessage:@"trackTransaction not implemented yet" toID:callbackId withError:nil];
}

-(void)successWithMessage:(NSString *)message toID:(NSString *)callbackID
{
CDVPluginResult *commandResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:message];
Expand Down
49 changes: 47 additions & 2 deletions www/GAPlugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
//
// id = the GA account ID of the form 'UA-00000000-0'
// period = the minimum interval for transmitting tracking events if any exist in the queue
GAPlugin.prototype.init = function(success, fail, id, period) {
return cordovaRef.exec(success, fail, 'GAPlugin', 'initGA', [id, period]);
// debug = Should GA set to debug mode? true/false
GAPlugin.prototype.init = function(success, fail, id, period, debug) {
debug = debug || false;
return cordovaRef.exec(success, fail, 'GAPlugin', 'initGA', [id, period, debug]);
};

// log an event
Expand Down Expand Up @@ -40,9 +42,52 @@
return cordovaRef.exec(success, fail, 'GAPlugin', 'setVariable', [index, value]);
};

// Set a custom dimension. The variable set is included with
// the next event only. If there is an existing custom dimension at the specified
// index, it will be overwritten by this one.
//
// value = the value of the dimension you are logging
// index = the numerical index of the dimension to which this variable will be assigned (1 - 20)
// Standard accounts support up to 20 custom dimensions.
GAPlugin.prototype.setDimension = function (success, fail, index, value) {
return cordovaRef.exec(success, fail, 'GAPlugin', 'setDimension', [index, value]);
};

// Set a custom metric. The variable set is included with
// the next event only. If there is an existing custom metric at the specified
// index, it will be overwritten by this one.
//
// value = the value of the metric you are logging
// index = the numerical index of the metric to which this variable will be assigned (1 - 20)
// Standard accounts support up to 20 custom metrics.
GAPlugin.prototype.setMetric = function (success, fail, index, value) {
return cordovaRef.exec(success, fail, 'GAPlugin', 'setMetric', [index, value]);
};


GAPlugin.prototype.exit = function(success, fail) {
return cordovaRef.exec(success, fail, 'GAPlugin', 'exitGA', []);
};

/**
* GA Ecommerce Transaction tracking
*
* @param {type} success
* @param {type} fail
* @param {type} transId Unique transaction id
* @param {type} orderTotal Order total
* @param {type} items JSON array
* @param {type} currency Currency string
* <pre>
* [{sku: <string>, name: <string>, price: <number>, quantity: <number>, category:<string>}]
* </pre>
* @returns {@exp;cordovaRef@call;exec}
*
* @author Gihan S <[email protected]>
*/
GAPlugin.prototype.trackTransaction = function(success, fail, transId, orderTotal, items, currency) {
return cordovaRef.exec(success, fail, 'GAPlugin', 'trackTransaction', [transId, orderTotal, currency, items]);
};

if (cordovaRef)
{
Expand Down