Skip to content

Commit 817d45e

Browse files
Google Analytics: Fixed tracking script for usage with no cookies & Added function to restore original scripts.
1 parent d4ef508 commit 817d45e

File tree

7 files changed

+128
-60
lines changed

7 files changed

+128
-60
lines changed

src/Plugins/SmartStore.GoogleAnalytics/Controllers/WidgetsGoogleAnalyticsController.cs

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
using SmartStore.Core.Logging;
1010
using SmartStore.Core.Plugins;
1111
using SmartStore.GoogleAnalytics.Models;
12+
using SmartStore.GoogleAnalytics.Services;
1213
using SmartStore.Services.Catalog;
1314
using SmartStore.Services.Configuration;
1415
using SmartStore.Services.Customers;
@@ -58,7 +59,7 @@ public ActionResult Configure(GoogleAnalyticsSettings settings)
5859
return View(model);
5960
}
6061

61-
[HttpPost, AdminAuthorize, ChildActionOnly, ValidateInput(false)]
62+
[HttpPost, AdminAuthorize, ChildActionOnly, ValidateInput(false), FormValueRequired("save")]
6263
public ActionResult Configure(ConfigurationModel model, FormCollection form)
6364
{
6465
var storeDependingSettingHelper = new StoreDependingSettingHelper(ViewData);
@@ -83,6 +84,23 @@ public ActionResult Configure(ConfigurationModel model, FormCollection form)
8384
return RedirectToConfiguration("SmartStore.GoogleAnalytics");
8485
}
8586

87+
[AdminAuthorize, HttpPost]
88+
[ActionName("Configure"), FormValueRequired("restore-scripts")]
89+
public ActionResult RestoreScripts()
90+
{
91+
var storeDependingSettingHelper = new StoreDependingSettingHelper(ViewData);
92+
var storeScope = this.GetActiveStoreScopeConfiguration(Services.StoreService, Services.WorkContext);
93+
var settings = Services.Settings.LoadSetting<GoogleAnalyticsSettings>(storeScope);
94+
95+
settings.TrackingScript = GoogleAnalyticsScriptHelper.GetTrackingScript();
96+
settings.EcommerceScript = GoogleAnalyticsScriptHelper.GetEcommerceScript();
97+
settings.EcommerceDetailScript = GoogleAnalyticsScriptHelper.GetEcommerceDetailScript();
98+
99+
_settingService.SaveSetting(settings, storeScope);
100+
101+
return RedirectToConfiguration("SmartStore.GoogleAnalytics", true);
102+
}
103+
86104
[ChildActionOnly]
87105
public ActionResult PublicInfo(string widgetZone)
88106
{
@@ -147,13 +165,15 @@ private string GetStorageScript()
147165
{
148166
// If no consent to analytical cookies was given, set storage to none.
149167
var script = @"
150-
ga('set', 'storage', 'none');
151-
ga('set', 'clientId', '{0}');
168+
, {
169+
'storage': 'none',
170+
'clientId': '" + _workContext.CurrentCustomer.CustomerGuid + @"',
171+
storeGac: false
172+
}
152173
";
153174

154175
script = script + "\n";
155-
script = script.FormatWith(_workContext.CurrentCustomer.CustomerGuid);
156-
176+
157177
return script;
158178
}
159179

src/Plugins/SmartStore.GoogleAnalytics/GoogleAnalyticPlugin.cs

Lines changed: 15 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,62 +1,18 @@
11
using System.Collections.Generic;
22
using System.Web.Routing;
33
using SmartStore.Core.Plugins;
4+
using SmartStore.GoogleAnalytics.Services;
45
using SmartStore.Services.Cms;
56
using SmartStore.Services.Configuration;
67
using SmartStore.Services.Localization;
78

89
namespace SmartStore.GoogleAnalytics
910
{
10-
/// <summary>
11-
/// Google Analytics Plugin
12-
/// </summary>
13-
public class GoogleAnalyticPlugin : BasePlugin, IWidget, IConfigurable, ICookiePublisher
14-
{
15-
#region Scripts
16-
17-
private const string TRACKING_SCRIPT = @"<!-- Google code for Analytics tracking -->
18-
<script>
19-
{OPTOUTCOOKIE}
20-
21-
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
22-
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
23-
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
24-
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
25-
26-
ga('create', '{GOOGLEID}', 'auto');
27-
ga('set', 'anonymizeIp', true);
28-
ga('send', 'pageview');
29-
30-
{STORAGETYPE}
31-
32-
{ECOMMERCE}
33-
</script>";
34-
35-
private const string ECOMMERCE_SCRIPT = @"ga('require', 'ecommerce');
36-
ga('ecommerce:addTransaction', {
37-
'id': '{ORDERID}',
38-
'affiliation': '{SITE}',
39-
'revenue': '{TOTAL}',
40-
'shipping': '{SHIP}',
41-
'tax': '{TAX}',
42-
'currency': '{CURRENCY}'
43-
});
44-
45-
{DETAILS}
46-
47-
ga('ecommerce:send');";
48-
49-
private const string ECOMMERCE_DETAIL_SCRIPT = @"ga('ecommerce:addItem', {
50-
'id': '{ORDERID}',
51-
'name': '{PRODUCTNAME}',
52-
'sku': '{PRODUCTSKU}',
53-
'category': '{CATEGORYNAME}',
54-
'price': '{UNITPRICE}',
55-
'quantity': '{QUANTITY}'
56-
});";
57-
58-
#endregion
59-
11+
/// <summary>
12+
/// Google Analytics Plugin
13+
/// </summary>
14+
public class GoogleAnalyticPlugin : BasePlugin, IWidget, IConfigurable, ICookiePublisher
15+
{
6016
private readonly ISettingService _settingService;
6117
private readonly GoogleAnalyticsSettings _googleAnalyticsSettings;
6218
private readonly ILocalizationService _localizationService;
@@ -145,8 +101,15 @@ public override void Install()
145101
EcommerceDetailScript = ECOMMERCE_DETAIL_SCRIPT
146102
};
147103

148-
_settingService.SaveSetting(settings);
149-
_localizationService.ImportPluginResourcesFromXml(this.PluginDescriptor);
104+
public override void Install()
105+
{
106+
var settings = new GoogleAnalyticsSettings
107+
{
108+
GoogleId = "UA-0000000-0",
109+
TrackingScript = GoogleAnalyticsScriptHelper.GetTrackingScript(),
110+
EcommerceScript = GoogleAnalyticsScriptHelper.GetEcommerceScript(),
111+
EcommerceDetailScript = GoogleAnalyticsScriptHelper.GetEcommerceDetailScript()
112+
};
150113

151114
base.Install();
152115
}

src/Plugins/SmartStore.GoogleAnalytics/Localization/resources.de-de.xml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,4 +51,10 @@
5151
<LocaleResource Name="CookieInfo">
5252
<Value>Google Analytics hilft uns das Nutzerverhalten unserer Webseite zu analysieren und aufgrund dessen zu verbessern, um Ihnen die bestmögliche Nutzererfahrung zu bieten.</Value>
5353
</LocaleResource>
54+
<LocaleResource Name="RestoreScripts">
55+
<Value>Scripte wiederherstellen</Value>
56+
</LocaleResource>
57+
<LocaleResource Name="RestoreScripts.Hint">
58+
<Value>Stellt die Original-Scripte wieder her. Nach einem Shop-Update sollte diese Funktion genutzt werden, um sicher zu gehen, dass die aktuellsten Scripte verwendet werden.</Value>
59+
</LocaleResource>
5460
</Language>

src/Plugins/SmartStore.GoogleAnalytics/Localization/resources.en-us.xml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,4 +51,10 @@
5151
<LocaleResource Name="CookieInfo">
5252
<Value>Google Analytics helps us analyze and improve the user behavior of our website to provide you with the best possible user experience.</Value>
5353
</LocaleResource>
54+
<LocaleResource Name="RestoreScripts">
55+
<Value>Restore scripts</Value>
56+
</LocaleResource>
57+
<LocaleResource Name="RestoreScripts.Hint">
58+
<Value>Restores the original scripts. After a store update this function should be used to make sure that the latest scripts are used.</Value>
59+
</LocaleResource>
5460
</Language>
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
namespace SmartStore.GoogleAnalytics.Services
2+
{
3+
/// <summary>
4+
/// Provides ready to use scripts for plugin settings.
5+
/// </summary>
6+
/// <remarks>
7+
/// Code formatting (everything is squeezed to the edge) was done intentionally like this.
8+
/// Else whitespace would be copied into the setting properties and effect the configuration page in a negative way.
9+
/// </remarks>
10+
public partial class GoogleAnalyticsScriptHelper
11+
{
12+
internal static string GetTrackingScript()
13+
{
14+
return @"<!-- Google code for Analytics tracking -->
15+
<script>
16+
{OPTOUTCOOKIE}
17+
18+
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
19+
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
20+
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
21+
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
22+
23+
ga('create', '{GOOGLEID}', 'auto'{STORAGETYPE});
24+
ga('set', 'anonymizeIp', true);
25+
ga('send', 'pageview');
26+
27+
{ECOMMERCE}
28+
</script>";
29+
}
30+
31+
internal static string GetEcommerceScript()
32+
{
33+
return @"ga('require', 'ecommerce');
34+
ga('ecommerce:addTransaction', {
35+
'id': '{ORDERID}',
36+
'affiliation': '{SITE}',
37+
'revenue': '{TOTAL}',
38+
'shipping': '{SHIP}',
39+
'tax': '{TAX}',
40+
'currency': '{CURRENCY}'
41+
});
42+
43+
{DETAILS}
44+
45+
ga('ecommerce:send');";
46+
}
47+
48+
internal static string GetEcommerceDetailScript()
49+
{
50+
return @"ga('ecommerce:addItem', {
51+
'id': '{ORDERID}',
52+
'name': '{PRODUCTNAME}',
53+
'sku': '{PRODUCTSKU}',
54+
'category': '{CATEGORYNAME}',
55+
'price': '{UNITPRICE}',
56+
'quantity': '{QUANTITY}'
57+
});";
58+
}
59+
}
60+
}

src/Plugins/SmartStore.GoogleAnalytics/SmartStore.GoogleAnalytics.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@
141141
<Compile Include="Properties\AssemblyInfo.cs" />
142142
<Compile Include="RouteProvider.cs" />
143143
<Compile Include="GoogleAnalyticsSettings.cs" />
144+
<Compile Include="Services\GoogleAnalyticsScriptHelper.cs" />
144145
</ItemGroup>
145146
<ItemGroup>
146147
<ProjectReference Include="..\..\Libraries\SmartStore.Core\SmartStore.Core.csproj">

src/Plugins/SmartStore.GoogleAnalytics/Views/WidgetsGoogleAnalytics/Configure.cshtml

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
<td class="adminTitle">
4242
@Html.SmartLabelFor(model => model.TrackingScript)
4343
</td>
44-
<td class="adminData">
44+
<td class="adminData wide">
4545
@Html.SettingEditorFor(model => model.TrackingScript,
4646
Html.TextAreaFor(model => model.TrackingScript, new { style = "height: 300px;" }))
4747
@Html.ValidationMessageFor(model => model.TrackingScript)
@@ -51,7 +51,7 @@
5151
<td class="adminTitle">
5252
@Html.SmartLabelFor(model => model.EcommerceScript)
5353
</td>
54-
<td class="adminData">
54+
<td class="adminData wide">
5555
@Html.SettingEditorFor(model => model.EcommerceScript,
5656
Html.TextAreaFor(model => model.EcommerceScript, new { style = "height: 300px;" }))
5757
@Html.ValidationMessageFor(model => model.EcommerceScript)
@@ -61,11 +61,23 @@
6161
<td class="adminTitle">
6262
@Html.SmartLabelFor(model => model.EcommerceDetailScript)
6363
</td>
64-
<td class="adminData">
64+
<td class="adminData wide">
6565
@Html.SettingEditorFor(model => model.EcommerceDetailScript,
6666
Html.TextAreaFor(model => model.EcommerceDetailScript, new { style = "height: 200px;" }))
6767
@Html.ValidationMessageFor(model => model.EcommerceDetailScript)
6868
</td>
6969
</tr>
70+
<tr>
71+
<td class="adminTitle">
72+
</td>
73+
<td class="adminData">
74+
<button type="submit" name="restore-scripts" class="btn btn-danger" value="restore-scripts"
75+
title="@T("Plugins.Widgets.GoogleAnalytics.RestoreScripts.Hint")"
76+
onclick="return confirm(@T("Admin.Common.AreYouSure").JsText);">
77+
<i class="far fa-bolt"></i>
78+
<span>@T("Plugins.Widgets.GoogleAnalytics.RestoreScripts")</span>
79+
</button>
80+
</td>
81+
</tr>
7082
</table>
7183
}

0 commit comments

Comments
 (0)