-
Notifications
You must be signed in to change notification settings - Fork 0
/
konnektive-cart.js.liquid
101 lines (73 loc) · 2.8 KB
/
konnektive-cart.js.liquid
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
{%- comment %}
@param cart (cart, mandatory)
@param checkout_url (string, mandatory) the checkout url
@param checkout_button_selector (string) the query selector for the checkout button
{% endcomment -%}
{% unless checkout_url %}
{% assign checkout_url = 'enter_your_checkout_url_here' %}
{% endunless %}
{% unless checkout_button_selector %}
{% assign checkout_button_selector = '[type="submit"][name="checkout"]' %}
{% endunless %}
<script>
document.addEventListener("DOMContentLoaded", function () {
var debug = true ? console.log.bind(console, '[DEBUG][RedirectCart]') : function () {};
debug('Script loaded');
window.RedirectCart = function (options) {
var self = {};
function productIdsWithQuantities() {
{%- assign added_first = false -%}
return {
{%- for item in cart.items -%}
{%- if item.variant.metafields.productId.productId -%}
{%- if added_first %},{% endif -%}
{%- if item.selling_plan_allocation -%}
"{{ item.variant.metafields.productId.productId}}{{"|"}}{{item.selling_plan_allocation.selling_plan.name}}": {{ item.quantity | json }}
{%- else -%}
"{{ item.variant.metafields.productId.productId }}": {{ item.quantity | json }}
{% endif -%}
{%- assign added_first = true -%}
{%- endif -%}
{%- endfor -%}
};
}
function init() {
self.options = Object.assign({
products: productIdsWithQuantities(),
checkoutButtonSelector: '{{ checkout_button_selector }}',
checkoutUrl: '{{ checkout_url }}',
}, options);
self.$checkoutButton = $(self.options.checkoutButtonSelector);
debug('Initialized with options', self.options);
inject();
}
function inject() {
debug('Inject');
self.$checkoutButton.on('click', checkout);
}
function checkout(event) {
var checkoutUrl = getCheckoutURL(self.options.products);
debug('Checkout ->', checkoutUrl);
event.preventDefault();
window.location.href = checkoutUrl;
}
function getCartCookie(name) {
var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
if (match){
return match[2];
}
}
function getCheckoutURL(products) {
cookie = getCartCookie('cart');
var urlLineItems = Object.keys(products).reduce(function (output, productId) {
var quantity = products[productId];
return output.concat([ productId + ':' + quantity ]);
}, []).join(';');
return self.options.checkoutUrl + '?products=' + urlLineItems + '&cartId='+cookie;
}
init();
return self;
};
var instance = new RedirectCart();
});
</script>