PluginProbe ʕ •ᴥ•ʔ
Payment Gateway for Authorize.net for WooCommerce / 1.0.15
Payment Gateway for Authorize.net for WooCommerce v1.0.15
1.0.19 1.0.18 1.0.17 1.0.16 1.0.15 1.0.14 1.0.13 trunk 1.0.0 1.0.1 1.0.10 1.0.11 1.0.12 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.0.7 1.0.8 1.0.9
payment-gateway-for-authorize-net-for-woocommerce / assets / js / googlepay-express.js
payment-gateway-for-authorize-net-for-woocommerce / assets / js Last commit date
blocks 2 weeks ago acceptjs-echeck-handler.js 2 weeks ago acceptjs-handler.js 2 weeks ago blocks-authorizenet.js 2 weeks ago easyauthnet-authorizenet-admin.js 2 weeks ago easyauthnet-review-ajax.js 2 weeks ago googlepay-express.js 2 weeks ago googlepay-handler.js 2 weeks ago
googlepay-express.js
381 lines
1 (function ($) {
2 "use strict";
3
4 var cfg = window.easyauthnet_gpay_express;
5 if (!cfg) return;
6
7 function log() {
8 if (!cfg.debug) return;
9 var args = Array.prototype.slice.call(arguments);
10 args.unshift("[EasyAuthNet][GPayExpress]");
11 // eslint-disable-next-line no-console
12 console.log.apply(console, args);
13 }
14
15 // Store token as base64 (matches checkout handler behavior).
16 function b64utf8(str) {
17 return btoa(unescape(encodeURIComponent(String(str || ""))));
18 }
19
20 function getBillingName(paymentData) {
21 try {
22 var info = paymentData && paymentData.paymentMethodData && paymentData.paymentMethodData.info;
23 var ba = info && info.billingAddress;
24 return ba && ba.name ? String(ba.name) : "";
25 } catch (e) {
26 return "";
27 }
28 }
29
30 function getShippingName(paymentData) {
31 try {
32 var sa = paymentData && paymentData.shippingAddress;
33 return sa && sa.name ? String(sa.name) : "";
34 } catch (e) {
35 return "";
36 }
37 }
38
39 function paymentsClient() {
40 return new google.payments.api.PaymentsClient({
41 environment: cfg.environment,
42 paymentDataCallbacks: {
43 onPaymentDataChanged: onPaymentDataChanged,
44 },
45 });
46 }
47
48 function allowedPaymentMethods() {
49 return [
50 {
51 type: "CARD",
52 parameters: {
53 allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"],
54 allowedCardNetworks: ["AMEX", "DISCOVER", "JCB", "MASTERCARD", "VISA"],
55 },
56 tokenizationSpecification: {
57 type: "PAYMENT_GATEWAY",
58 parameters: {
59 gateway: "authorizenet",
60 gatewayMerchantId: cfg.gatewayMerchantId,
61 },
62 },
63 },
64 ];
65 }
66
67 function baseRequest() {
68 var req = {
69 apiVersion: 2,
70 apiVersionMinor: 0,
71 allowedPaymentMethods: allowedPaymentMethods(),
72 merchantInfo: { merchantName: cfg.merchantName || "" },
73 };
74
75 // Google Pay requires merchantId in PRODUCTION environment.
76 if (cfg.googleMerchantId) {
77 req.merchantInfo.merchantId = String(cfg.googleMerchantId);
78 }
79
80 return req;
81 }
82
83 function getBtnCfg() {
84 return cfg && cfg.button ? cfg.button : {};
85 }
86
87 function mapButtonColor(color) {
88 color = String(color || "").toLowerCase();
89 return color === "black" || color === "white" ? color : "black";
90 }
91
92 function mapButtonSizeMode(width) {
93 width = String(width || "").toLowerCase();
94 return width === "auto" ? "static" : "fill";
95 }
96
97 function mapButtonType(label) {
98 label = String(label || "").toLowerCase();
99
100 // Your dropdown includes "plain". Google Pay doesn't have a "plain" type in v2,
101 // so fallback to "pay" (safe default).
102 if (label === "plain") return "pay";
103
104 // Allowed: buy, checkout, donate, book, order, pay, subscribe
105 switch (label) {
106 case "buy":
107 case "checkout":
108 case "donate":
109 case "book":
110 case "order":
111 case "pay":
112 case "subscribe":
113 return label;
114 default:
115 return "pay";
116 }
117 }
118
119 function applyButtonStyle(btn) {
120 var b = getBtnCfg();
121
122 var h = parseInt(b.height, 10);
123 if (h > 0) {
124 btn.style.height = h + "px";
125 btn.style.minHeight = h + "px";
126 }
127
128 var shape = String(b.shape || "rect").toLowerCase();
129 if (shape === "pill") {
130 btn.style.borderRadius = "9999px";
131 btn.style.overflow = "hidden";
132 } else {
133 btn.style.borderRadius = "4px";
134 btn.style.overflow = "hidden";
135 }
136 }
137
138 function syncGpayWidthWithCheckout() {
139 var b = getBtnCfg();
140 if (String(b.width || "").toLowerCase() === "auto") return;
141
142 var checkoutEl = document.querySelector(".wc-proceed-to-checkout");
143 var gpayWrap = document.querySelector(".easyauthnet-gpay-express-wrap");
144 if (!checkoutEl || !gpayWrap) return;
145
146 var width = checkoutEl.getBoundingClientRect().width;
147 if (width && width > 0) {
148 gpayWrap.style.maxWidth = width + "px";
149 gpayWrap.style.marginLeft = "auto";
150 gpayWrap.style.marginRight = "auto";
151 }
152 }
153
154 function buildRequest(total, shippingOptions, defaultShippingId) {
155 var req = baseRequest();
156 req.transactionInfo = {
157 totalPriceStatus: "FINAL",
158 totalPrice: String(total || "0.00"),
159 currencyCode: cfg.currency || "USD",
160 countryCode: cfg.countryCode || "US",
161 };
162
163 // Ask Google Pay to return the buyer's email so we can populate
164 // billing_email on the order (used for receipts, shipping updates, etc.).
165 req.emailRequired = true;
166
167 if (cfg.needs_shipping) {
168 req.shippingAddressRequired = true;
169
170 var hasOptions = Array.isArray(shippingOptions) && shippingOptions.length > 0;
171
172 if (hasOptions) {
173 req.shippingOptionRequired = true;
174 req.callbackIntents = ["SHIPPING_ADDRESS", "SHIPPING_OPTION"];
175 req.shippingOptionParameters = {
176 defaultSelectedOptionId: String(defaultShippingId || ""),
177 shippingOptions: shippingOptions.map(function (o) {
178 return {
179 id: o.id,
180 label: o.label,
181 description: o.description || "",
182 };
183 }),
184 };
185 } else {
186 // No rates yet (no address selected, or no shipping zones configured).
187 // Don't send shippingOptionParameters with an empty array — that triggers
188 // OR_BIBED_06 in Google Pay. We re-quote in onPaymentDataChanged once
189 // the shopper picks an address.
190 req.callbackIntents = ["SHIPPING_ADDRESS"];
191 }
192 }
193
194 return req;
195 }
196
197 function post(action, dataObj) {
198 var data = $.extend({ action: action, nonce: cfg.nonce }, dataObj || {});
199 return $.ajax({
200 url: cfg.ajax_url,
201 method: "POST",
202 data: data,
203 dataType: "json",
204 }).then(function (resp) {
205 if (!resp || !resp.success) {
206 var msg = resp && resp.data && resp.data.message ? resp.data.message : "Request failed";
207 throw new Error(msg);
208 }
209 return resp.data;
210 });
211 }
212
213 function quote(shippingAddress, shippingOptionId) {
214 return post("easyauthnet_gpay_express_quote", {
215 shippingAddress: shippingAddress ? JSON.stringify(shippingAddress) : "",
216 shipping_option_id: shippingOptionId || "",
217 });
218 }
219
220 function onPaymentDataChanged(intermediatePaymentData) {
221 if (!cfg.needs_shipping) return {};
222
223 var addr = intermediatePaymentData.shippingAddress || null;
224 var optId =
225 intermediatePaymentData.shippingOptionData && intermediatePaymentData.shippingOptionData.id
226 ? intermediatePaymentData.shippingOptionData.id
227 : "";
228
229 return quote(addr, optId)
230 .then(function (q) {
231 var options = Array.isArray(q.shipping_options) ? q.shipping_options : [];
232
233 if (!options.length) {
234 return {
235 error: {
236 reason: "SHIPPING_ADDRESS_UNSERVICEABLE",
237 message:
238 cfg.i18n && cfg.i18n.no_shipping
239 ? cfg.i18n.no_shipping
240 : "No shipping methods are available for this address.",
241 intent: "SHIPPING_ADDRESS",
242 },
243 };
244 }
245
246 return {
247 newTransactionInfo: {
248 totalPriceStatus: "FINAL",
249 totalPrice: String(q.total),
250 currencyCode: String(q.currency || cfg.currency || "USD"),
251 countryCode: cfg.countryCode || "US",
252 },
253 newShippingOptionParameters: {
254 defaultSelectedOptionId: String(q.default_shipping_option_id || ""),
255 shippingOptions: options.map(function (o) {
256 return {
257 id: o.id,
258 label: o.label,
259 description: o.description || "",
260 };
261 }),
262 },
263 };
264 })
265 .catch(function (e) {
266 return {
267 error: {
268 reason: "SHIPPING_ADDRESS_UNSERVICEABLE",
269 message: e && e.message ? e.message : "Unable to calculate shipping",
270 intent: "SHIPPING_ADDRESS",
271 },
272 };
273 });
274 }
275
276 function startExpress() {
277 var client = paymentsClient();
278
279 return quote(null, "")
280 .then(function (q) {
281 var req = buildRequest(q.total, q.shipping_options || [], q.default_shipping_option_id || "");
282 return client.loadPaymentData(req);
283 })
284 .then(function (paymentData) {
285 var token =
286 paymentData &&
287 paymentData.paymentMethodData &&
288 paymentData.paymentMethodData.tokenizationData
289 ? paymentData.paymentMethodData.tokenizationData.token
290 : "";
291
292 if (!token) throw new Error("Google Pay token missing");
293
294 var shipName = getShippingName(paymentData);
295 var billName = getBillingName(paymentData);
296
297 var payload = {
298 token: b64utf8(token),
299 email: paymentData.email || "",
300 // Send raw "First Last" strings; PHP parses them.
301 shippingName: shipName || billName || "",
302 billingName: billName || "",
303 };
304
305 if (cfg.needs_shipping) {
306 payload.shippingAddress = paymentData.shippingAddress ? JSON.stringify(paymentData.shippingAddress) : "";
307 payload.shipping_option_id =
308 paymentData.shippingOptionData && paymentData.shippingOptionData.id ? paymentData.shippingOptionData.id : "";
309 }
310
311 return post("easyauthnet_gpay_express_pay", payload);
312 })
313 .then(function (r) {
314 window.location.href = r.redirect;
315 })
316 .catch(function (err) {
317 log("Express error", err);
318 alert(
319 err && err.message
320 ? err.message
321 : cfg.i18n && cfg.i18n.failed
322 ? cfg.i18n.failed
323 : "Google Pay Express failed"
324 );
325 });
326 }
327
328 function mountButton() {
329 var $wraps = $(".easyauthnet-gpay-express-wrap");
330 if (!$wraps.length) return;
331
332 var client = paymentsClient();
333
334 return client
335 .isReadyToPay({
336 apiVersion: 2,
337 apiVersionMinor: 0,
338 allowedPaymentMethods: [
339 {
340 type: "CARD",
341 parameters: {
342 allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"],
343 allowedCardNetworks: ["AMEX", "DISCOVER", "JCB", "MASTERCARD", "VISA"],
344 },
345 },
346 ],
347 })
348 .then(function (r) {
349 if (!r || !r.result) return;
350
351 var b = getBtnCfg();
352
353 $wraps.each(function () {
354 var $w = $(this);
355
356 var btn = client.createButton({
357 buttonType: mapButtonType(b.label),
358 buttonColor: mapButtonColor(b.color),
359 buttonSizeMode: mapButtonSizeMode(b.width),
360 onClick: startExpress,
361 });
362
363 $w.empty().append(btn);
364
365 try {
366 applyButtonStyle(btn);
367 } catch (e) {}
368 });
369
370 setTimeout(syncGpayWidthWithCheckout, 0);
371 })
372 .catch(function (e) {
373 log("isReadyToPay failed", e);
374 });
375 }
376
377 $(function () {
378 mountButton();
379 });
380 })(jQuery);
381