authorizenet-react
Version:
React components for Authorize.Net payments
803 lines (761 loc) • 28.7 kB
JavaScript
import je, { createContext as Oe, useState as Ne, useEffect as ke, useContext as Pe, useRef as Ye } from "react";
var ae = { exports: {} }, D = {};
/**
* @license React
* react-jsx-runtime.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var xe;
function Ve() {
if (xe) return D;
xe = 1;
var o = Symbol.for("react.transitional.element"), u = Symbol.for("react.fragment");
function p(m, c, i) {
var s = null;
if (i !== void 0 && (s = "" + i), c.key !== void 0 && (s = "" + c.key), "key" in c) {
i = {};
for (var b in c)
b !== "key" && (i[b] = c[b]);
} else i = c;
return c = i.ref, {
$$typeof: o,
type: m,
key: s,
ref: c !== void 0 ? c : null,
props: i
};
}
return D.Fragment = u, D.jsx = p, D.jsxs = p, D;
}
var L = {};
/**
* @license React
* react-jsx-runtime.development.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
var we;
function $e() {
return we || (we = 1, process.env.NODE_ENV !== "production" && function() {
function o(e) {
if (e == null) return null;
if (typeof e == "function")
return e.$$typeof === Ae ? null : e.displayName || e.name || null;
if (typeof e == "string") return e;
switch (e) {
case A:
return "Fragment";
case H:
return "Portal";
case V:
return "Profiler";
case Y:
return "StrictMode";
case J:
return "Suspense";
case X:
return "SuspenseList";
}
if (typeof e == "object")
switch (typeof e.tag == "number" && console.error(
"Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
), e.$$typeof) {
case M:
return (e.displayName || "Context") + ".Provider";
case $:
return (e._context.displayName || "Context") + ".Consumer";
case z:
var t = e.render;
return e = e.displayName, e || (e = t.displayName || t.name || "", e = e !== "" ? "ForwardRef(" + e + ")" : "ForwardRef"), e;
case Z:
return t = e.displayName || null, t !== null ? t : o(e.type) || "Memo";
case Q:
t = e._payload, e = e._init;
try {
return o(e(t));
} catch {
}
}
return null;
}
function u(e) {
return "" + e;
}
function p(e) {
try {
u(e);
var t = !1;
} catch {
t = !0;
}
if (t) {
t = console;
var r = t.error, n = typeof Symbol == "function" && Symbol.toStringTag && e[Symbol.toStringTag] || e.constructor.name || "Object";
return r.call(
t,
"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
n
), u(e);
}
}
function m() {
}
function c() {
if (W === 0) {
ie = console.log, se = console.info, de = console.warn, fe = console.error, me = console.group, ve = console.groupCollapsed, pe = console.groupEnd;
var e = {
configurable: !0,
enumerable: !0,
value: m,
writable: !0
};
Object.defineProperties(console, {
info: e,
log: e,
warn: e,
error: e,
group: e,
groupCollapsed: e,
groupEnd: e
});
}
W++;
}
function i() {
if (W--, W === 0) {
var e = { configurable: !0, enumerable: !0, writable: !0 };
Object.defineProperties(console, {
log: C({}, e, { value: ie }),
info: C({}, e, { value: se }),
warn: C({}, e, { value: de }),
error: C({}, e, { value: fe }),
group: C({}, e, { value: me }),
groupCollapsed: C({}, e, { value: ve }),
groupEnd: C({}, e, { value: pe })
});
}
0 > W && console.error(
"disabledDepth fell below zero. This is a bug in React. Please file an issue."
);
}
function s(e) {
if (ee === void 0)
try {
throw Error();
} catch (r) {
var t = r.stack.trim().match(/\n( *(at )?)/);
ee = t && t[1] || "", ge = -1 < r.stack.indexOf(`
at`) ? " (<anonymous>)" : -1 < r.stack.indexOf("@") ? "@unknown:0:0" : "";
}
return `
` + ee + e + ge;
}
function b(e, t) {
if (!e || te) return "";
var r = re.get(e);
if (r !== void 0) return r;
te = !0, r = Error.prepareStackTrace, Error.prepareStackTrace = void 0;
var n = null;
n = w.H, w.H = null, c();
try {
var f = {
DetermineComponentFrameRoot: function() {
try {
if (t) {
var E = function() {
throw Error();
};
if (Object.defineProperty(E.prototype, "props", {
set: function() {
throw Error();
}
}), typeof Reflect == "object" && Reflect.construct) {
try {
Reflect.construct(E, []);
} catch (y) {
var G = y;
}
Reflect.construct(e, [], E);
} else {
try {
E.call();
} catch (y) {
G = y;
}
e.call(E.prototype);
}
} else {
try {
throw Error();
} catch (y) {
G = y;
}
(E = e()) && typeof E.catch == "function" && E.catch(function() {
});
}
} catch (y) {
if (y && G && typeof y.stack == "string")
return [y.stack, G.stack];
}
return [null, null];
}
};
f.DetermineComponentFrameRoot.displayName = "DetermineComponentFrameRoot";
var l = Object.getOwnPropertyDescriptor(
f.DetermineComponentFrameRoot,
"name"
);
l && l.configurable && Object.defineProperty(
f.DetermineComponentFrameRoot,
"name",
{ value: "DetermineComponentFrameRoot" }
);
var a = f.DetermineComponentFrameRoot(), h = a[0], _ = a[1];
if (h && _) {
var v = h.split(`
`), N = _.split(`
`);
for (a = l = 0; l < v.length && !v[l].includes(
"DetermineComponentFrameRoot"
); )
l++;
for (; a < N.length && !N[a].includes(
"DetermineComponentFrameRoot"
); )
a++;
if (l === v.length || a === N.length)
for (l = v.length - 1, a = N.length - 1; 1 <= l && 0 <= a && v[l] !== N[a]; )
a--;
for (; 1 <= l && 0 <= a; l--, a--)
if (v[l] !== N[a]) {
if (l !== 1 || a !== 1)
do
if (l--, a--, 0 > a || v[l] !== N[a]) {
var q = `
` + v[l].replace(
" at new ",
" at "
);
return e.displayName && q.includes("<anonymous>") && (q = q.replace("<anonymous>", e.displayName)), typeof e == "function" && re.set(e, q), q;
}
while (1 <= l && 0 <= a);
break;
}
}
} finally {
te = !1, w.H = n, i(), Error.prepareStackTrace = r;
}
return v = (v = e ? e.displayName || e.name : "") ? s(v) : "", typeof e == "function" && re.set(e, v), v;
}
function d(e) {
if (e == null) return "";
if (typeof e == "function") {
var t = e.prototype;
return b(
e,
!(!t || !t.isReactComponent)
);
}
if (typeof e == "string") return s(e);
switch (e) {
case J:
return s("Suspense");
case X:
return s("SuspenseList");
}
if (typeof e == "object")
switch (e.$$typeof) {
case z:
return e = b(e.render, !1), e;
case Z:
return d(e.type);
case Q:
t = e._payload, e = e._init;
try {
return d(e(t));
} catch {
}
}
return "";
}
function x() {
var e = w.A;
return e === null ? null : e.getOwner();
}
function g(e) {
if (ue.call(e, "key")) {
var t = Object.getOwnPropertyDescriptor(e, "key").get;
if (t && t.isReactWarning) return !1;
}
return e.key !== void 0;
}
function k(e, t) {
function r() {
be || (be = !0, console.error(
"%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",
t
));
}
r.isReactWarning = !0, Object.defineProperty(e, "key", {
get: r,
configurable: !0
});
}
function U() {
var e = o(this.type);
return he[e] || (he[e] = !0, console.error(
"Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
)), e = this.props.ref, e !== void 0 ? e : null;
}
function F(e, t, r, n, f, l) {
return r = l.ref, e = {
$$typeof: T,
type: e,
key: t,
props: l,
_owner: f
}, (r !== void 0 ? r : null) !== null ? Object.defineProperty(e, "ref", {
enumerable: !1,
get: U
}) : Object.defineProperty(e, "ref", { enumerable: !1, value: null }), e._store = {}, Object.defineProperty(e._store, "validated", {
configurable: !1,
enumerable: !1,
writable: !0,
value: 0
}), Object.defineProperty(e, "_debugInfo", {
configurable: !1,
enumerable: !1,
writable: !0,
value: null
}), Object.freeze && (Object.freeze(e.props), Object.freeze(e)), e;
}
function j(e, t, r, n, f, l) {
if (typeof e == "string" || typeof e == "function" || e === A || e === V || e === Y || e === J || e === X || e === Te || typeof e == "object" && e !== null && (e.$$typeof === Q || e.$$typeof === Z || e.$$typeof === M || e.$$typeof === $ || e.$$typeof === z || e.$$typeof === _e || e.getModuleId !== void 0)) {
var a = t.children;
if (a !== void 0)
if (n)
if (K(a)) {
for (n = 0; n < a.length; n++)
O(a[n], e);
Object.freeze && Object.freeze(a);
} else
console.error(
"React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."
);
else O(a, e);
} else
a = "", (e === void 0 || typeof e == "object" && e !== null && Object.keys(e).length === 0) && (a += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."), e === null ? n = "null" : K(e) ? n = "array" : e !== void 0 && e.$$typeof === T ? (n = "<" + (o(e.type) || "Unknown") + " />", a = " Did you accidentally export a JSX literal instead of a component?") : n = typeof e, console.error(
"React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",
n,
a
);
if (ue.call(t, "key")) {
a = o(e);
var h = Object.keys(t).filter(function(v) {
return v !== "key";
});
n = 0 < h.length ? "{key: someKey, " + h.join(": ..., ") + ": ...}" : "{key: someKey}", ye[a + n] || (h = 0 < h.length ? "{" + h.join(": ..., ") + ": ...}" : "{}", console.error(
`A props object containing a "key" prop is being spread into JSX:
let props = %s;
<%s {...props} />
React keys must be passed directly to JSX without using spread:
let props = %s;
<%s key={someKey} {...props} />`,
n,
a,
h,
a
), ye[a + n] = !0);
}
if (a = null, r !== void 0 && (p(r), a = "" + r), g(t) && (p(t.key), a = "" + t.key), "key" in t) {
r = {};
for (var _ in t)
_ !== "key" && (r[_] = t[_]);
} else r = t;
return a && k(
r,
typeof e == "function" ? e.displayName || e.name || "Unknown" : e
), F(e, a, l, f, x(), r);
}
function O(e, t) {
if (typeof e == "object" && e && e.$$typeof !== Re) {
if (K(e))
for (var r = 0; r < e.length; r++) {
var n = e[r];
S(n) && P(n, t);
}
else if (S(e))
e._store && (e._store.validated = 1);
else if (e === null || typeof e != "object" ? r = null : (r = le && e[le] || e["@@iterator"], r = typeof r == "function" ? r : null), typeof r == "function" && r !== e.entries && (r = r.call(e), r !== e))
for (; !(e = r.next()).done; )
S(e.value) && P(e.value, t);
}
}
function S(e) {
return typeof e == "object" && e !== null && e.$$typeof === T;
}
function P(e, t) {
if (e._store && !e._store.validated && e.key == null && (e._store.validated = 1, t = I(t), !Ee[t])) {
Ee[t] = !0;
var r = "";
e && e._owner != null && e._owner !== x() && (r = null, typeof e._owner.tag == "number" ? r = o(e._owner.type) : typeof e._owner.name == "string" && (r = e._owner.name), r = " It was passed a child from " + r + ".");
var n = w.getCurrentStack;
w.getCurrentStack = function() {
var f = d(e.type);
return n && (f += n() || ""), f;
}, console.error(
'Each child in a list should have a unique "key" prop.%s%s See https://react.dev/link/warning-keys for more information.',
t,
r
), w.getCurrentStack = n;
}
}
function I(e) {
var t = "", r = x();
return r && (r = o(r.type)) && (t = `
Check the render method of \`` + r + "`."), t || (e = o(e)) && (t = `
Check the top-level render call using <` + e + ">."), t;
}
var B = je, T = Symbol.for("react.transitional.element"), H = Symbol.for("react.portal"), A = Symbol.for("react.fragment"), Y = Symbol.for("react.strict_mode"), V = Symbol.for("react.profiler"), $ = Symbol.for("react.consumer"), M = Symbol.for("react.context"), z = Symbol.for("react.forward_ref"), J = Symbol.for("react.suspense"), X = Symbol.for("react.suspense_list"), Z = Symbol.for("react.memo"), Q = Symbol.for("react.lazy"), Te = Symbol.for("react.offscreen"), le = Symbol.iterator, Ae = Symbol.for("react.client.reference"), w = B.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, ue = Object.prototype.hasOwnProperty, C = Object.assign, _e = Symbol.for("react.client.reference"), K = Array.isArray, W = 0, ie, se, de, fe, me, ve, pe;
m.__reactDisabledLog = !0;
var ee, ge, te = !1, re = new (typeof WeakMap == "function" ? WeakMap : Map)(), Re = Symbol.for("react.client.reference"), be, he = {}, ye = {}, Ee = {};
L.Fragment = A, L.jsx = function(e, t, r, n, f) {
return j(e, t, r, !1, n, f);
}, L.jsxs = function(e, t, r, n, f) {
return j(e, t, r, !0, n, f);
};
}()), L;
}
process.env.NODE_ENV === "production" ? ae.exports = Ve() : ae.exports = $e();
var ne = ae.exports;
let R = null, oe = "", ce = "";
const Me = (o) => {
oe = o.apiLoginId, ce = o.clientKey;
}, ze = (o) => {
R = o;
}, We = async () => new Promise((o, u) => {
if (!window.Accept) {
u(new Error("Authorize.Net Accept.js not loaded"));
return;
}
if (!R) {
u(new Error("Card data not available"));
return;
}
if (!oe || !ce) {
u(new Error("API credentials not configured"));
return;
}
const p = {
authData: {
clientKey: ce,
apiLoginID: oe
},
cardData: {
cardNumber: R.cardNumber.replace(/\s/g, ""),
month: R.month,
year: R.year,
cardCode: R.cardCode
}
}, m = (c) => {
var i, s;
((i = c == null ? void 0 : c.messages) == null ? void 0 : i.resultCode) === "Error" ? u((s = c == null ? void 0 : c.messages) == null ? void 0 : s.message[0].text) : o(c.opaqueData);
};
Accept.dispatchData(p, m);
}), Ce = {
endpoint: {
sandbox: "https://jstest.authorize.net/v1/Accept.js",
production: "https://js.authorize.net/v1/Accept.js"
}
}, Se = Oe(null), Le = ({
apiLoginId: o,
clientKey: u,
children: p,
environment: m = "sandbox",
className: c = ""
}) => {
const [i, s] = Ne(!1);
ke(() => {
Me({ apiLoginId: o, clientKey: u });
const g = document.createElement("script");
return g.src = m === "sandbox" ? Ce.endpoint.sandbox : Ce.endpoint.production, g.async = !0, g.onload = () => {
if (window.Accept)
try {
s(!0);
} catch (k) {
console.error("Error initializing Accept.js:", k);
}
}, document.body.appendChild(g), () => {
document.body.removeChild(g), s(!1);
};
}, [o, u, m]);
const x = {
createToken: async () => We(),
isScriptLoaded: i,
setCardData: (g) => {
ze(g);
},
apiLoginId: o,
clientKey: u,
environment: m
};
return /* @__PURE__ */ ne.jsx(Se.Provider, { value: x, children: /* @__PURE__ */ ne.jsx("div", { className: c, children: p }) });
};
function qe() {
const o = Pe(Se);
if (!o)
throw new Error("useAuthorizeNet must be used within an AuthorizeNetProvider");
return o;
}
const Ue = ({
options: o = {},
onChange: u,
className: p = "",
onComplete: m
}) => {
const c = Ye(null), { setCardData: i } = qe(), [s, b] = Ne(!1);
return ke(() => {
var U, F, j, O, S, P, I, B, T, H, A;
const d = document.createElement("iframe");
d.style.width = "100%", d.style.height = "60px", d.style.border = "none", d.style.overflow = "hidden", d.className = `authorize-net-card-iframe ${p}`;
const x = `authorize-net-card-${Math.random().toString(36).substring(2)}`;
d.name = x;
const g = `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
margin: 0;
padding: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}
.card-container {
display: flex;
align-items: center;
gap: 8px;
padding: 12px;
background: white;
border: 1px solid #e0e0e0;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
transition: all 0.2s ease;
}
.card-container:hover {
border-color: #a0a0a0;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.15);
}
.card-container:focus-within {
border-color: #4f46e5;
box-shadow: 0 0 0 2px rgba(79, 70, 229, 0.2);
}
input {
border: none;
background: transparent;
outline: none;
font-size: ${((F = (U = o.style) == null ? void 0 : U.base) == null ? void 0 : F.fontSize) || "16px"};
color: ${((O = (j = o.style) == null ? void 0 : j.base) == null ? void 0 : O.color) || "#424770"};
padding: 4px 0;
width: 100%;
}
input::placeholder {
color: ${((I = (P = (S = o.style) == null ? void 0 : S.base) == null ? void 0 : P["::placeholder"]) == null ? void 0 : I.color) || "#aab7c4"};
}
.card-number {
flex: 1;
}
.expiry-wrapper {
display: flex;
align-items: center;
gap: 4px;
min-width: 100px;
}
.expiry-month,
.expiry-year {
width: 40px;
text-align: center;
}
.separator {
color: #a0a0a0;
margin: 0 4px;
}
.cvv {
width: 64px;
text-align: center;
}
</style>
</head>
<body>
<div class="card-container">
<input type="text" class="card-number" placeholder="Card Number" maxlength="19" autocomplete="cc-number">
<span class="separator">|</span>
<div class="expiry-wrapper">
<input type="text" class="expiry-month" placeholder="MM" maxlength="2" autocomplete="cc-exp-month">
<span class="separator">/</span>
<input type="text" class="expiry-year" placeholder="YY" maxlength="2" autocomplete="cc-exp-year">
</div>
<span class="separator">|</span>
<input type="password" class="cvv" placeholder="CVV" maxlength="4" autocomplete="cc-csc">
</div>
<script>
function formatCardNumber(input) {
return input.replace(/\\D/g, '').replace(/(\\d{4})/g, '$1 ').trim();
}
function formatExpiry(input) {
return input.replace(/\\D/g, '');
}
function formatCVV(input) {
return input.replace(/\\D/g, '').slice(0, 4);
}
function validateCardNumber(number) {
if (!/^\\d+$/.test(number) || number.length !== 16) {
return false;
}
let sum = 0;
let shouldDouble = false;
for (let i = number.length - 1; i >= 0; i--) {
let digit = parseInt(number.charAt(i));
if (shouldDouble) {
digit *= 2;
if (digit > 9) {
digit -= 9;
}
}
sum += digit;
shouldDouble = !shouldDouble;
}
return (sum % 10) === 0;
}
function validateExpiry(month, year) {
if (isNaN(month) || isNaN(year)) {
return false;
}
if (month < 1 || month > 12) {
return false;
}
const now = new Date();
const currentMonth = now.getMonth() + 1;
const currentYear = now.getFullYear();
const fullYear = 2000 + year;
if (fullYear < currentYear) {
return false;
}
if (fullYear === currentYear && month < currentMonth) {
return false;
}
return true;
}
function validateForm() {
const cardNumber = document.querySelector('.card-number');
const month = document.querySelector('.expiry-month');
const year = document.querySelector('.expiry-year');
const cvv = document.querySelector('.cvv');
const cardNumberValue = cardNumber.value.replace(/\\s/g, '');
const monthValue = parseInt(month.value);
const yearValue = parseInt(year.value);
const isCardNumberValid = validateCardNumber(cardNumberValue);
const isExpiryValid = validateExpiry(monthValue, yearValue);
const isCvvValid = cvv.value.length >= 3 && cvv.value.length <= 4;
const isComplete = isCardNumberValid && isExpiryValid && isCvvValid;
// Send data to parent
window.parent.postMessage({
type: 'cardUpdate',
data: {
cardNumber: cardNumberValue,
month: month.value,
year: year.value,
cardCode: cvv.value,
isComplete,
error: isComplete ? undefined : 'Please fill in all fields correctly'
}
}, ${o.targetOrigin});
// If complete, add the complete class to make fields readonly
if (isComplete) {
document.querySelector('.card-container').classList.add('complete');
}
}
// Add event listeners
const cardNumber = document.querySelector('.card-number');
const month = document.querySelector('.expiry-month');
const year = document.querySelector('.expiry-year');
const cvv = document.querySelector('.cvv');
cardNumber.addEventListener('input', (e) => {
e.target.value = formatCardNumber(e.target.value);
if (e.target.value.length === 19) {
month.focus();
}
validateForm();
});
month.addEventListener('input', (e) => {
e.target.value = formatExpiry(e.target.value);
if (e.target.value.length === 2) {
year.focus();
}
validateForm();
});
year.addEventListener('input', (e) => {
e.target.value = formatExpiry(e.target.value);
if (e.target.value.length === 2) {
cvv.focus();
}
validateForm();
});
cvv.addEventListener('input', (e) => {
e.target.value = formatCVV(e.target.value);
validateForm();
});
// Add keydown event listeners for backspace navigation
month.addEventListener('keydown', (e) => {
if ((e.key === 'Backspace' || e.key === 'Delete') && e.target.value === '') {
cardNumber.focus();
// Place cursor at the end of the input
const len = cardNumber.value.length;
cardNumber.setSelectionRange(len, len);
}
});
year.addEventListener('keydown', (e) => {
if ((e.key === 'Backspace' || e.key === 'Delete') && e.target.value === '') {
month.focus();
// Place cursor at the end of the input
const len = month.value.length;
month.setSelectionRange(len, len);
}
});
cvv.addEventListener('keydown', (e) => {
if ((e.key === 'Backspace' || e.key === 'Delete') && e.target.value === '') {
year.focus();
// Place cursor at the end of the input
const len = year.value.length;
year.setSelectionRange(len, len);
}
});
<\/script>
</body>
</html>
`, k = (Y) => {
var V;
if (((V = Y.data) == null ? void 0 : V.type) === "cardUpdate") {
const { isComplete: $, error: M, ...z } = Y.data.data;
i(z), u && u({ complete: $, error: M ? new Error(M) : void 0 }), $ && !s && (b(!0), m == null || m());
}
};
return window.addEventListener("message", k), (B = c.current) != null && B.parentNode && c.current.parentNode.replaceChild(d, c.current), c.current = d, (T = d.contentWindow) == null || T.document.open(), (H = d.contentWindow) == null || H.document.write(g), (A = d.contentWindow) == null || A.document.close(), () => {
window.removeEventListener("message", k);
};
}, [o, u, i, p, s, m]), /* @__PURE__ */ ne.jsx("div", { ref: c, className: "authorize-net-card-element" });
};
export {
Le as AuthorizeNetProvider,
Ue as Card,
We as createToken,
qe as useAuthorizeNet
};