forked from men232/plus-for-trello
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stripe-wrap.js
324 lines (281 loc) · 14.4 KB
/
stripe-wrap.js
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
/// <reference path="intellisense.js" />
var g_loaderStripe = {
load: function () {
var price = 9.99;
var stripe = Stripe('pk_live_4kZi0Lw0rPUHuLsDb00UVPt8');
var elements = stripe.elements();
var style = {
base: {
color: '#32325d',
lineHeight: '24px',
fontSize: '16px',
'::placeholder': {
color: '#CEDDED'
}
},
invalid: {
color: '#fa755a',
iconColor: '#fa755a'
}
};
var elemNum = document.getElementById('agile_quantity_stripe');
var form = document.getElementById('agile-stripe-payment-form');
var userTrello = document.getElementById('agile_userTrello_stripe').textContent;
var liStripe = document.getElementById('agile_stripe_li').textContent;
var bChanging = (liStripe != "");
var quantityOrig = parseInt(elemNum.value || "0",10) || 0;
function hiliteElem(elem, msTime, count, strClass) {
var classBlink = (strClass ? strClass : "agile_box_input_hilite");
msTime = msTime || 1500;
elem.classList.add(classBlink);
setTimeout(function () {
elem.classList.remove(classBlink);
if (count && count > 1) {
setTimeout(function () {
hiliteElem(elem, msTime,count - 1, strClass);
}, msTime);
}
}, msTime);
}
//review: code relies on whether button text contains "preview"
function changeButtonText(bNeedsPreview) {
var num = Math.floor(parseFloat(elemNum.value) || 0);
var title = "Buy";
var bShowPreviewData = false;
var bAddBuyClass = true;
if (num && num > 0) {
if (bChanging) {
title = "Modify license";
if (quantityOrig > 0) {
var diff = num - quantityOrig;
if (bNeedsPreview) {
title = "Preview charges";
bAddBuyClass = false;
}
else {
if (diff > 0) {
title = "Modify: Add " + diff + " licenses";
bShowPreviewData = true;
}
else if (diff < 0) {
title = "Modify: Remove " + Math.abs(diff) + " licenses";
bShowPreviewData = true;
}
}
}
}
else
title = title + ": $" + (num * price).toFixed(2) + " yearly";
} else if (num === 0) {
title = "Remove subscription";
}
var buttonAction = document.getElementById('agile_stripe_paydialog_buy');
buttonAction.textContent = title;
document.getElementById('agile_stripe_modifyinfo_reply').style.display = (bShowPreviewData ? "block" : "none");
if (bChanging)
document.getElementById('agile_stripe_modifyinfo').style.display = (!bShowPreviewData ? "block" : "none");
if (bAddBuyClass)
buttonAction.classList.add("agile_dialog_stripeBuy");
else
buttonAction.classList.remove("agile_dialog_stripeBuy");
}
changeButtonText();
elemNum.addEventListener("input", function (event) {
changeButtonText(bChanging);
});
var card = elements.create('card', { style: style, hidePostalCode: true });
card.mount('#agile-stripe-card-element');
// Handle real-time validation errors from the card Element.
card.addEventListener('change', function (event) {
var displayError = document.getElementById('agile-stripe-card-errors');
if (event.error) {
displayError.textContent = event.error.message || "error";
} else {
displayError.textContent = '';
}
});
var email = null;
var quantity = null;
var name = null;
var proration_last = 0;
function showOverlay(bShow) {
var elem = document.getElementById('agile_stripe_overlay');
elem.style.display = (bShow ? "block" : "none");
}
function enableElements(bEnable, bNeedPreview) {
function enableByTag(tag) {
var inputs = form.getElementsByTagName(tag);
for (var i = 0; i < inputs.length; i++)
inputs[i].disabled = !bEnable;
}
enableByTag("input");
enableByTag("button");
showOverlay(!bEnable);
if (bEnable)
changeButtonText(bNeedPreview); //helps refresh state of show/hide elements in case of comming from an error
}
form.addEventListener('submit', function (event) {
event.preventDefault();
email = (document.getElementById('agile_email_stripe').value || "").trim();
quantity = parseInt(document.getElementById('agile_quantity_stripe').value || 0, 10) || 0;
name = (document.getElementById('agile_cardholdername_stripe').value || "").trim();
if (!email) {
alert("Please type the license owner's email.");
return false;
}
var iAtEmail = email.indexOf("@");
if (iAtEmail <= 0) {
alert("Please type a valid email address.");
return false;
}
if (email.lastIndexOf(".") < iAtEmail) {
alert("Please type a valid email address with a '.'");
return false;
}
if (!name) {
alert("Please type the license owner's name.");
return false;
}
if (quantity == 0 && !confirm("Are you sure you want to remove the subscription?"))
return false;
document.getElementById('agile-stripe-card-errors').textContent = "";
document.getElementById('agile_stripe_modifyinfo_reply').style.display = "none";
enableElements(false);
var textButton = document.getElementById('agile_stripe_paydialog_buy').textContent || "";
if (textButton.toLowerCase().indexOf("preview")>=0) {
serverTokenHandlerPreviewChange(userTrello, liStripe, quantity);
} else {
stripe.createToken(card).then(function (result) {
if (result.error) {
// Inform the user if there was an error
var errorElement = document.getElementById('agile-stripe-card-errors');
errorElement.textContent = result.error.message;
enableElements(true);
} else {
serverTokenHandlerCreateModify(result.token);
}
});
}
return false;
});
function serverTokenHandlerPreviewChange(userTrello, liStripe, quantity) {
var xhr = new XMLHttpRequest();
// Bind the FormData object and the form element
var fd = new FormData(form);
var i = 0;
var strParams = "?li=" + encodeURIComponent(liStripe) + "&quantity=" + quantity.toString()+ "&userTrello=" + encodeURIComponent(userTrello);
function handleError(val) {
var iColon = val.indexOf(":");
var displayError = document.getElementById('agile-stripe-card-errors');
if (iColon > 0)
val = val.substr(iColon + 1, val.length) + " (" + val.substr(0, iColon) + ")";
displayError.textContent = val || "error";
enableElements(true, true);
}
xhr.addEventListener("load", function (event) {
var val = event.target.responseText;
if (val.indexOf("error") == 0) {
handleError(val);
return;
} else if (val.indexOf("sub-change-preview") == 0) {
//server returns sub-change-preview:cost:proration_date:bTrial
var params = val.split(":");
if (params.length == 5) {
var cost = ((parseInt(params[1], 10) || 0) / 100);
var strCost = Math.abs(cost).toFixed(2);
proration_last = parseInt(params[2], 10) || 0; //in seconds
var bTrial = (params[3] == "1");
var msPeriodEnd = parseInt(params[4], 10) || 0;
var elemInfo = document.getElementById('agile_stripe_modifyinfo_reply');
var strInfo = "Almost done! Click the Modify button to finish. ";
var strDateEnd = new Date(msPeriodEnd).toLocaleDateString();
if (bTrial)
strInfo += "Then once the trial period ends you will be charged <b>$" + strCost + "</b> instead of the previous pending charge.";
else {
if (cost > 0)
strInfo += "Then you will be charged an adjustment of <b>$" + strCost + "</b> for the current yearly period.<br>Afterwards, on your next yearly period ("+strDateEnd+") the subscription will be <b>$" + (quantity * price).toFixed(2)+"</b>.";
else
strInfo += "Then your next yearly subscription invoice ("+strDateEnd+") will be <b>$" + (quantity * price).toFixed(2) +
"</b>.<br>Additionally, that next invoice will receive a credit of <b>$" + strCost + "</b> for unused license time this period.";
}
elemInfo.innerHTML = strInfo;
enableElements(true);
} else {
handleError("Invalid server response");
return;
}
} else {
handleError("Invalid server response");
return;
}
});
xhr.addEventListener("error", function (event) {
var displayError = document.getElementById('agile-stripe-card-errors');
displayError.textContent = event.target.responseText || "error";
enableElements(true, true);
});
xhr.open("GET", "https://us-central1-plusfortrelloapp.cloudfunctions.net/calcpreview" + strParams);
xhr.send();
}
function serverTokenHandlerCreateModify(token) {
var xhr = new XMLHttpRequest();
// Bind the FormData object and the form element
var fd = new FormData(form);
var i = 0;
var strParams = "?cardholder-name=" + encodeURIComponent(name) + "&email=" + encodeURIComponent(email) + "&quantity=" + quantity.toString();
strParams += ("&stripeToken=" + encodeURIComponent(token.id));
strParams += ("&userTrello=" + encodeURIComponent(userTrello));
strParams += ("&liStripe=" + encodeURIComponent(liStripe));
strParams += ("&prorate=" + proration_last.toString());
xhr.addEventListener("load", function (event) {
var val = event.target.responseText;
var iColon = val.indexOf(":");
if (val.indexOf("error") == 0) {
var displayError = document.getElementById('agile-stripe-card-errors');
if (iColon > 0)
val = val.substr(iColon + 1, val.length) + " (" + val.substr(0, iColon) + ")";
displayError.textContent = val || "error";
enableElements(true, true);
return;
}
var params = val.split(":");
var strLicense = params[1];
var msStart = parseInt(params[2], 10) || 0;
document.getElementById("agile_stripe_modifyinfo").style.display = "none";
if (quantity > 0) {
document.getElementById("agile_stripe_licence").value = ("https://trello.com/plus-license/" + userTrello + "/" + strLicense);
document.getElementById("agile_stripe_startdate").textContent = ((new Date(msStart)).toLocaleDateString());
document.getElementById("agile_stripe_licence_info").style.display = "block";
}
var elemSensitive = document.getElementById("agile_stripe_postpayhide");
elemSensitive.parentNode.removeChild(elemSensitive);
document.getElementById("agile_stripe_ok").style.display = "block";
showOverlay(false);
if (quantity == 0) {
alert("License removed.");
strLicense = ""; //should already be from stripe params, but just in case their API definition changes.
}
window.postMessage({
type: 'agile_stripe_data',
license: {
msCreated: msStart,
li: strLicense,
userTrello: userTrello,
emailOwner: email,
quantity: quantity,
nameCardOwner: name
}
},
'*' /* targetOrigin: any */);
});
xhr.addEventListener("error", function (event) {
var displayError = document.getElementById('agile-stripe-card-errors');
displayError.textContent = event.target.responseText || "error";
enableElements(true, true);
});
xhr.open("GET", "https://us-central1-plusfortrelloapp.cloudfunctions.net/setlic" + strParams);
xhr.send();
}
return this;
}
}.load();