PluginProbe ʕ •ᴥ•ʔ
Payment Gateway for Authorize.net for WooCommerce / 1.0.13
Payment Gateway for Authorize.net for WooCommerce v1.0.13
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 1 month ago acceptjs-echeck-handler.js 1 month ago acceptjs-handler.js 1 month ago blocks-authorizenet.js 1 month ago easyauthnet-authorizenet-admin.js 1 month ago easyauthnet-review-ajax.js 1 month ago googlepay-express.js 1 month ago googlepay-handler.js 1 month ago
googlepay-express.js
377 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 if (cfg.needs_shipping) {
164 req.shippingAddressRequired = true;
165
166 var hasOptions = Array.isArray(shippingOptions) && shippingOptions.length > 0;
167
168 if (hasOptions) {
169 req.shippingOptionRequired = true;
170 req.callbackIntents = ["SHIPPING_ADDRESS", "SHIPPING_OPTION"];
171 req.shippingOptionParameters = {
172 defaultSelectedOptionId: String(defaultShippingId || ""),
173 shippingOptions: shippingOptions.map(function (o) {
174 return {
175 id: o.id,
176 label: o.label,
177 description: o.description || "",
178 };
179 }),
180 };
181 } else {
182 // No rates yet (no address selected, or no shipping zones configured).
183 // Don't send shippingOptionParameters with an empty array — that triggers
184 // OR_BIBED_06 in Google Pay. We re-quote in onPaymentDataChanged once
185 // the shopper picks an address.
186 req.callbackIntents = ["SHIPPING_ADDRESS"];
187 }
188 }
189
190 return req;
191 }
192
193 function post(action, dataObj) {
194 var data = $.extend({ action: action, nonce: cfg.nonce }, dataObj || {});
195 return $.ajax({
196 url: cfg.ajax_url,
197 method: "POST",
198 data: data,
199 dataType: "json",
200 }).then(function (resp) {
201 if (!resp || !resp.success) {
202 var msg = resp && resp.data && resp.data.message ? resp.data.message : "Request failed";
203 throw new Error(msg);
204 }
205 return resp.data;
206 });
207 }
208
209 function quote(shippingAddress, shippingOptionId) {
210 return post("easyauthnet_gpay_express_quote", {
211 shippingAddress: shippingAddress ? JSON.stringify(shippingAddress) : "",
212 shipping_option_id: shippingOptionId || "",
213 });
214 }
215
216 function onPaymentDataChanged(intermediatePaymentData) {
217 if (!cfg.needs_shipping) return {};
218
219 var addr = intermediatePaymentData.shippingAddress || null;
220 var optId =
221 intermediatePaymentData.shippingOptionData && intermediatePaymentData.shippingOptionData.id
222 ? intermediatePaymentData.shippingOptionData.id
223 : "";
224
225 return quote(addr, optId)
226 .then(function (q) {
227 var options = Array.isArray(q.shipping_options) ? q.shipping_options : [];
228
229 if (!options.length) {
230 return {
231 error: {
232 reason: "SHIPPING_ADDRESS_UNSERVICEABLE",
233 message:
234 cfg.i18n && cfg.i18n.no_shipping
235 ? cfg.i18n.no_shipping
236 : "No shipping methods are available for this address.",
237 intent: "SHIPPING_ADDRESS",
238 },
239 };
240 }
241
242 return {
243 newTransactionInfo: {
244 totalPriceStatus: "FINAL",
245 totalPrice: String(q.total),
246 currencyCode: String(q.currency || cfg.currency || "USD"),
247 countryCode: cfg.countryCode || "US",
248 },
249 newShippingOptionParameters: {
250 defaultSelectedOptionId: String(q.default_shipping_option_id || ""),
251 shippingOptions: options.map(function (o) {
252 return {
253 id: o.id,
254 label: o.label,
255 description: o.description || "",
256 };
257 }),
258 },
259 };
260 })
261 .catch(function (e) {
262 return {
263 error: {
264 reason: "SHIPPING_ADDRESS_UNSERVICEABLE",
265 message: e && e.message ? e.message : "Unable to calculate shipping",
266 intent: "SHIPPING_ADDRESS",
267 },
268 };
269 });
270 }
271
272 function startExpress() {
273 var client = paymentsClient();
274
275 return quote(null, "")
276 .then(function (q) {
277 var req = buildRequest(q.total, q.shipping_options || [], q.default_shipping_option_id || "");
278 return client.loadPaymentData(req);
279 })
280 .then(function (paymentData) {
281 var token =
282 paymentData &&
283 paymentData.paymentMethodData &&
284 paymentData.paymentMethodData.tokenizationData
285 ? paymentData.paymentMethodData.tokenizationData.token
286 : "";
287
288 if (!token) throw new Error("Google Pay token missing");
289
290 var shipName = getShippingName(paymentData);
291 var billName = getBillingName(paymentData);
292
293 var payload = {
294 token: b64utf8(token),
295 email: paymentData.email || "",
296 // Send raw "First Last" strings; PHP parses them.
297 shippingName: shipName || billName || "",
298 billingName: billName || "",
299 };
300
301 if (cfg.needs_shipping) {
302 payload.shippingAddress = paymentData.shippingAddress ? JSON.stringify(paymentData.shippingAddress) : "";
303 payload.shipping_option_id =
304 paymentData.shippingOptionData && paymentData.shippingOptionData.id ? paymentData.shippingOptionData.id : "";
305 }
306
307 return post("easyauthnet_gpay_express_pay", payload);
308 })
309 .then(function (r) {
310 window.location.href = r.redirect;
311 })
312 .catch(function (err) {
313 log("Express error", err);
314 alert(
315 err && err.message
316 ? err.message
317 : cfg.i18n && cfg.i18n.failed
318 ? cfg.i18n.failed
319 : "Google Pay Express failed"
320 );
321 });
322 }
323
324 function mountButton() {
325 var $wraps = $(".easyauthnet-gpay-express-wrap");
326 if (!$wraps.length) return;
327
328 var client = paymentsClient();
329
330 return client
331 .isReadyToPay({
332 apiVersion: 2,
333 apiVersionMinor: 0,
334 allowedPaymentMethods: [
335 {
336 type: "CARD",
337 parameters: {
338 allowedAuthMethods: ["PAN_ONLY", "CRYPTOGRAM_3DS"],
339 allowedCardNetworks: ["AMEX", "DISCOVER", "JCB", "MASTERCARD", "VISA"],
340 },
341 },
342 ],
343 })
344 .then(function (r) {
345 if (!r || !r.result) return;
346
347 var b = getBtnCfg();
348
349 $wraps.each(function () {
350 var $w = $(this);
351
352 var btn = client.createButton({
353 buttonType: mapButtonType(b.label),
354 buttonColor: mapButtonColor(b.color),
355 buttonSizeMode: mapButtonSizeMode(b.width),
356 onClick: startExpress,
357 });
358
359 $w.empty().append(btn);
360
361 try {
362 applyButtonStyle(btn);
363 } catch (e) {}
364 });
365
366 setTimeout(syncGpayWidthWithCheckout, 0);
367 })
368 .catch(function (e) {
369 log("isReadyToPay failed", e);
370 });
371 }
372
373 $(function () {
374 mountButton();
375 });
376 })(jQuery);
377