@koomipay/react 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ "use strict";var jsxRuntime=require("react/jsx-runtime"),react=require("react"),axios=require("axios"),AdyenCheckout=require("@adyen/adyen-web"),__assign=function(){return(__assign=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var s in t=arguments[n])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e}).apply(this,arguments)};function __awaiter(e,a,o,c){return new(o=o||Promise)(function(n,t){function r(e){try{i(c.next(e))}catch(e){t(e)}}function s(e){try{i(c.throw(e))}catch(e){t(e)}}function i(e){var t;e.done?n(e.value):((t=e.value)instanceof o?t:new o(function(e){e(t)})).then(r,s)}i((c=c.apply(e,a||[])).next())})}function __generator(r,s){var i,a,o,c={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},l={next:e(0),throw:e(1),return:e(2)};return"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function e(n){return function(e){var t=[n,e];if(i)throw new TypeError("Generator is already executing.");for(;c=l&&t[l=0]?0:c;)try{if(i=1,a&&(o=2&t[0]?a.return:t[0]?a.throw||((o=a.return)&&o.call(a),0):a.next)&&!(o=o.call(a,t[1])).done)return o;switch(a=0,(t=o?[2&t[0],o.value]:t)[0]){case 0:case 1:o=t;break;case 4:return c.label++,{value:t[1],done:!1};case 5:c.label++,a=t[1],t=[0];continue;case 7:t=c.ops.pop(),c.trys.pop();continue;default:if(!(o=0<(o=c.trys).length&&o[o.length-1])&&(6===t[0]||2===t[0])){c=0;continue}if(3===t[0]&&(!o||t[1]>o[0]&&t[1]<o[3]))c.label=t[1];else if(6===t[0]&&c.label<o[1])c.label=o[1],o=t;else{if(!(o&&c.label<o[2])){o[2]&&c.ops.pop(),c.trys.pop();continue}c.label=o[2],c.ops.push(t)}}t=s.call(r,c)}catch(e){t=[6,e],a=0}finally{i=o=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}}function classNames(e){return Object.entries(e).map(function(e,t){return e[1]?e[0]:null}).filter(function(e){return e}).join(" ")}function classNameObject(e){return e?e.split(" ").reduce(function(e,t){return __assign(__assign({},e),((e={})[t]=!0,e))},{}):{}}function Label(e){var t=e.className,n=e.error,r=e.htmlFor,s=e.info,i=e.mandatory,e=e.children;return jsxRuntime.jsxs("div",__assign({className:"flex items-center justify-between"},{children:[jsxRuntime.jsxs("label",__assign({htmlFor:r,className:classNames(__assign(__assign({},classNameObject(t)),{"block text-base font-medium mb-1.5":!0,"text-gray-900 dark:text-white":!n,"text-red-600 dark:text-red-500":!!n}))},{children:[e,i&&jsxRuntime.jsx("span",__assign({className:"ml-1 text-red-500"},{children:"*"}))]})),s&&jsxRuntime.jsx("span",__assign({className:"text-sm leading-5 text-gray-500 dark:text-gray-500 ".concat(n&&"text-red-600")},{children:s}))]}))}function resolveLogoUrl(e,t){return"".concat(t.assetHost,"/").concat(e)}function CheckoutCardLogo(e){var t=e.active,n=e.logoUrl,e=e.client.getConfig();return jsxRuntime.jsx("div",__assign({className:classNames({"h-10":!0,"grayscale opacity-30":!t})},{children:jsxRuntime.jsx("img",{className:"object-contain w-full h-full",src:resolveLogoUrl(n,e)})}))}function CheckoutInputField(e){var t=e.field,n=e.focus,r=e.valids,e=e.errors,e=!!e&&e[t],r=!!r&&r[t],s=null!=e,e=!!s&&e.errorMessage;return jsxRuntime.jsxs("div",__assign({className:"relative mb-4"},{children:[jsxRuntime.jsx("div",{className:classNames({"h-12 border px-3 py-1.5 rounded-md overflow-hidden":!0,"border-gray-200":!n&&!s,"bg-green-50 border-green-700":!!r,"bg-red-50 border-red-500":!n&&!!s&&!r,"bg-blue-50 border-blue-500 ring-2 ring-blue-200":!!n}),"data-cse":t}),!!r&&jsxRuntime.jsx("div",__assign({className:"absolute top-0 bottom-0 flex items-center text-green-700 right-3"},{children:jsxRuntime.jsxs("svg",__assign({className:"w-6 h-6",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"},{children:[jsxRuntime.jsx("path",{d:"M0 0h24v24H0z",fill:"none"}),jsxRuntime.jsx("path",{d:"M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z"})]}))})),!!e&&jsxRuntime.jsx("p",__assign({className:"mt-1.5 text-red-500 text-sm leading-tight"},{children:e}))]}))}function GrabPayComponent(e){var t=e.active,n=e.paymentMethod,r=e.onValid,s=e.onChange;return react.useEffect(function(){t&&("function"==typeof s&&s({type:n.type}),"function"==typeof r)&&r(!0)},[t]),t?jsxRuntime.jsx("div",{children:"After checkout, You will be redirected to payment page to complete this payment."}):null}function CardComponent(e){var t=e.client,n=e.active,r=e.type,s=e.brands,i=e.onValid,a=e.onChange,o=react.useRef(null),e=react.useState(!0),c=e[0],l=e[1],e=react.useState({}),u=e[0],d=e[1],e=react.useState(null),p=e[0],m=e[1],e=react.useState([]),h=e[0],x=e[1],e=react.useState({}),y=e[0],f=e[1],e=react.useState({}),g=e[0],v=e[1];react.useEffect(function(){n&&(i(!1),l(!0),d({}),m(null),x([]),f({}),v({}),function(){__awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,AdyenCheckout(j)];case 1:return t=e.sent(),o.current&&t.create("securedfields",{type:r,brands:s,styles:{error:{color:"red"},validated:{color:"green"},placeholder:{color:"#d8d8d8"}},onLoad:function(){l(!0)},onConfigSuccess:function(){l(!1)},onFocus:function(e){var e=e||{},t=e.focus,e=e.fieldType;m(t?e:null)},onBinLookup:function(e){e=(e||{}).detectedBrands;x(e||[])}}).mount(o.current),[3,3];case 2:return t=e.sent(),"development"===process.env.NODE_ENV&&console.log("[ERROR] Handle create checkout error: ",t),[3,3];case 3:return[2]}})})}())},[n,r]),react.useEffect(function(){var e;u&&"function"==typeof i&&(e=!!(u.encryptedCardNumber&&u.encryptedExpiryMonth&&u.encryptedExpiryYear&&u.encryptedSecurityCode),i(e),a({type:u.type,brand:u.brand,encryptedCardNumber:u.encryptedCardNumber,encryptedExpiryMonth:u.encryptedExpiryMonth,encryptedExpiryYear:u.encryptedExpiryYear,encryptedSecurityCode:u.encryptedSecurityCode,cardholder:u.cardholder}))},[u]);var e=t.getConfig(),j={locale:"en_US",environment:e.clientEnv,clientKey:e.clientKey,analytics:{enabled:!1},onChange:function(e){var t=(e=e||{}).data,n=e.valid,e=e.errors;d(!!t&&t.paymentMethod||{}),v(Object.assign(__assign(__assign({},n||{}),{encryptedExpiryDate:n.encryptedExpiryMonth&&n.encryptedExpiryYear}))),f(e||{})}};return n?jsxRuntime.jsxs("div",__assign({className:classNames({"relative transition-all":!0,"h-96 max-h-96":!!c,"h-auto max-h-120":!c})},{children:[jsxRuntime.jsxs("div",__assign({className:"flex my-3 space-x-3"},{children:[jsxRuntime.jsx(CheckoutCardLogo,{active:h.includes("visa"),logoUrl:"logo/visa.svg",client:t}),jsxRuntime.jsx(CheckoutCardLogo,{active:h.includes("mc"),logoUrl:"logo/mastercard.svg",client:t}),jsxRuntime.jsx(CheckoutCardLogo,{active:h.includes("amex"),logoUrl:"logo/american-express.svg",client:t})]})),jsxRuntime.jsxs("div",__assign({ref:o,className:classNames({"opacity-0":!!c})},{children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx(Label,__assign({htmlFor:"cardNumber"},{children:"Card number"})),jsxRuntime.jsx(CheckoutInputField,{field:"encryptedCardNumber",focus:"encryptedCardNumber"===p,valids:g,errors:y})]}),jsxRuntime.jsxs("div",__assign({className:"grid grid-cols-2 gap-6"},{children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx(Label,__assign({htmlFor:"expiryDate"},{children:"Expiry date"})),jsxRuntime.jsx(CheckoutInputField,{field:"encryptedExpiryDate",focus:"encryptedExpiryDate"===p,valids:g,errors:y})]}),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx(Label,__assign({htmlFor:"securityCode"},{children:"Security Code (CVV/CVC)"})),jsxRuntime.jsx(CheckoutInputField,{field:"encryptedSecurityCode",focus:"encryptedSecurityCode"===p,valids:g,errors:y})]})]}))]})),jsxRuntime.jsxs("div",__assign({className:classNames({"absolute inset-0 flex flex-col gap-3 items-center justify-center":!0,"opacity-0 pointer-events-none":!c})},{children:[jsxRuntime.jsx("div",__assign({className:"w-16 h-16"},{children:jsxRuntime.jsxs("svg",__assign({className:"w-full h-full animate-spin",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},{children:[jsxRuntime.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),jsxRuntime.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}))})),jsxRuntime.jsx("p",{children:"Loading"})]}))]})):null}function CheckoutPaymentMethod(e){var t=e.active,n=e.children,e=e.onClick;return jsxRuntime.jsx("div",__assign({className:classNames({"border px-3 py-2 mb-2 rounded-md cursor-pointer":!0,"bg-primary-500 text-white border-primary-500":!!t,"text-gray-300 border-gray-300":!t}),onClick:e},{children:n}))}function CheckoutContainer(e){var r=e.client,s=e.amount,t=e.onValid,e=e.onChange,n=r.getApiKey(),i=react.useState(!0),a=i[0],o=i[1],i=react.useState([]),c=i[0],l=i[1],i=react.useState(null),u=i[0],d=i[1];return react.useEffect(function(){n?function(n){__awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return[4,axios.post("".concat(r.getConfig().baseApiUri,"/koomipay/payment-methods"),{amount:{currency:s.currency,price:s.price}},{headers:{"X-API-KEY":n}})];case 1:return(t=e.sent())&&t.data&&t.data.success&&(l(t.data.paymentMethods),d(!!t.data.paymentMethods&&t.data.paymentMethods[0]),o(!1)),[2]}})})}(n):o(!1)},[n]),a?jsxRuntime.jsxs("div",__assign({className:classNames({"mx-auto w-64 h-64 inset-0 flex flex-col gap-3 items-center justify-center":!0,"opacity-0 pointer-events-none":!a})},{children:[jsxRuntime.jsx("div",__assign({className:"w-16 h-16"},{children:jsxRuntime.jsxs("svg",__assign({className:"w-full h-full animate-spin",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},{children:[jsxRuntime.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),jsxRuntime.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}))})),jsxRuntime.jsx("p",{children:"Loading"})]})):jsxRuntime.jsxs("div",{children:[(c||[]).map(function(t){return jsxRuntime.jsx(CheckoutPaymentMethod,__assign({active:(u||{}).type===t.type,onClick:function(){var e;e=t,(u||{}).type!==(e||{}).type&&d(e)}},{children:t.name}),t.type)}),jsxRuntime.jsxs("div",__assign({className:classNames({"border-t border-gray-200 mt-6 py-3":!0})},{children:[jsxRuntime.jsx(CardComponent,{client:r,active:!!u&&"scheme"===u.type,type:"card",brands:["mc","visa","amex"],onValid:t,onChange:e}),jsxRuntime.jsx(GrabPayComponent,{active:!!u&&u.type.includes("grabpay"),paymentMethod:u,onValid:t,onChange:e})]}))]})}Label.defaultProps={error:!1};var environments=["dev","test","live"],configuration={dev:{baseApiUri:"http://localhost:32022",assetHost:"http://localhost:3000",clientEnv:"TEST",clientKey:"test_6FPMOVL2VVGJ7PASYRZDHX2AHAM6D5SG"},test:{baseApiUri:"https://api-pay-demo.koomi.app",assetHost:"https://pay-demo.koomi.app",clientEnv:"TEST",clientKey:"test_6FPMOVL2VVGJ7PASYRZDHX2AHAM6D5SG"},live:{baseApiUri:"https://api-pay-demo.koomi.app",assetHost:"https://pay-demo.koomi.app",clientEnv:"TEST",clientKey:"test_6FPMOVL2VVGJ7PASYRZDHX2AHAM6D5SG"}};function getConfig(e){if(!e)throw new Error('getConfig(env) expected env as string, but got "'.concat(e,'"'));if(environments.includes(e))return configuration[e];throw new Error("env must be one of ".concat(environments.join(", ")))}function createClient(e){var t=e.apiKey,e=e.env;return new KoomiPayClient({apiKey:t,env:e})}var KoomiPayClient=function(){function e(e){this.apiKey=e.apiKey,this.env=e.env,this.config=getConfig(e.env)}return e.prototype.setConfig=function(e){"apiKey"in e&&(this.apiKey=e.apiKey),"env"in e&&(this.env=e.env,this.config=getConfig(e.env))},e.prototype.getConfig=function(){return this.config},e.prototype.getApiKey=function(){return this.apiKey},e.prototype.getEnv=function(){return this.env},e.prototype.checkout=function(n,r){return void 0===r&&(r={}),__awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:r&&this.setConfig(r),e.label=1;case 1:return e.trys.push([1,3,,4]),[4,axios.post("".concat(this.config.baseApiUri,"/koomipay/checkout"),n,{headers:{"X-API-KEY":this.apiKey}})];case 2:return[2,e.sent()];case 3:throw t=e.sent(),console.log("[DEBUG] Checkout error",t),new Error("Error when checkout, please check your payload");case 4:return[2]}})})},e.prototype.instantCheckout=function(n,r){return void 0===r&&(r={}),__awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:r&&this.setConfig(r),e.label=1;case 1:return e.trys.push([1,3,,4]),[4,axios.post("".concat(this.config.baseApiUri,"/koomipay/instant-checkout"),n,{headers:{"X-API-KEY":this.apiKey}})];case 2:return[2,e.sent()];case 3:throw t=e.sent(),console.log("[DEBUG] Instant Checkout error",t),new Error("Error when checkout, please check your payload");case 4:return[2]}})})},e}();exports.CheckoutContainer=CheckoutContainer,exports.createClient=createClient,module.exports=Object.assign(exports.default||{},exports);
@@ -1,5 +1,5 @@
1
1
  import React from "react";
2
- import { KoomiPayClient, CheckoutAmount } from "../../lib/client";
2
+ import { KoomiPayClient, CheckoutAmount } from "../lib/client";
3
3
  export type CardPaymentMethodPayload = {
4
4
  type: string;
5
5
  brand?: string;
File without changes
File without changes
@@ -0,0 +1,2 @@
1
+ export { CheckoutContainer } from "./components/CheckoutContainer";
2
+ export { createClient } from "./lib/client";
File without changes
File without changes
@@ -0,0 +1 @@
1
+ import{jsxs,jsx}from"react/jsx-runtime";import{useState,useEffect,useRef}from"react";import axios from"axios";import AdyenCheckout from"@adyen/adyen-web";var __assign=function(){return(__assign=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var s in t=arguments[n])Object.prototype.hasOwnProperty.call(t,s)&&(e[s]=t[s]);return e}).apply(this,arguments)};function __awaiter(e,o,i,c){return new(i=i||Promise)(function(n,t){function r(e){try{a(c.next(e))}catch(e){t(e)}}function s(e){try{a(c.throw(e))}catch(e){t(e)}}function a(e){var t;e.done?n(e.value):((t=e.value)instanceof i?t:new i(function(e){e(t)})).then(r,s)}a((c=c.apply(e,o||[])).next())})}function __generator(r,s){var a,o,i,c={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},l={next:e(0),throw:e(1),return:e(2)};return"function"==typeof Symbol&&(l[Symbol.iterator]=function(){return this}),l;function e(n){return function(e){var t=[n,e];if(a)throw new TypeError("Generator is already executing.");for(;c=l&&t[l=0]?0:c;)try{if(a=1,o&&(i=2&t[0]?o.return:t[0]?o.throw||((i=o.return)&&i.call(o),0):o.next)&&!(i=i.call(o,t[1])).done)return i;switch(o=0,(t=i?[2&t[0],i.value]:t)[0]){case 0:case 1:i=t;break;case 4:return c.label++,{value:t[1],done:!1};case 5:c.label++,o=t[1],t=[0];continue;case 7:t=c.ops.pop(),c.trys.pop();continue;default:if(!(i=0<(i=c.trys).length&&i[i.length-1])&&(6===t[0]||2===t[0])){c=0;continue}if(3===t[0]&&(!i||t[1]>i[0]&&t[1]<i[3]))c.label=t[1];else if(6===t[0]&&c.label<i[1])c.label=i[1],i=t;else{if(!(i&&c.label<i[2])){i[2]&&c.ops.pop(),c.trys.pop();continue}c.label=i[2],c.ops.push(t)}}t=s.call(r,c)}catch(e){t=[6,e],o=0}finally{a=i=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}}}function classNames(e){return Object.entries(e).map(function(e,t){return e[1]?e[0]:null}).filter(function(e){return e}).join(" ")}function classNameObject(e){return e?e.split(" ").reduce(function(e,t){return __assign(__assign({},e),((e={})[t]=!0,e))},{}):{}}function Label(e){var t=e.className,n=e.error,r=e.htmlFor,s=e.info,a=e.mandatory,e=e.children;return jsxs("div",__assign({className:"flex items-center justify-between"},{children:[jsxs("label",__assign({htmlFor:r,className:classNames(__assign(__assign({},classNameObject(t)),{"block text-base font-medium mb-1.5":!0,"text-gray-900 dark:text-white":!n,"text-red-600 dark:text-red-500":!!n}))},{children:[e,a&&jsx("span",__assign({className:"ml-1 text-red-500"},{children:"*"}))]})),s&&jsx("span",__assign({className:"text-sm leading-5 text-gray-500 dark:text-gray-500 ".concat(n&&"text-red-600")},{children:s}))]}))}function resolveLogoUrl(e,t){return"".concat(t.assetHost,"/").concat(e)}function CheckoutCardLogo(e){var t=e.active,n=e.logoUrl,e=e.client.getConfig();return jsx("div",__assign({className:classNames({"h-10":!0,"grayscale opacity-30":!t})},{children:jsx("img",{className:"object-contain w-full h-full",src:resolveLogoUrl(n,e)})}))}function CheckoutInputField(e){var t=e.field,n=e.focus,r=e.valids,e=e.errors,e=!!e&&e[t],r=!!r&&r[t],s=null!=e,e=!!s&&e.errorMessage;return jsxs("div",__assign({className:"relative mb-4"},{children:[jsx("div",{className:classNames({"h-12 border px-3 py-1.5 rounded-md overflow-hidden":!0,"border-gray-200":!n&&!s,"bg-green-50 border-green-700":!!r,"bg-red-50 border-red-500":!n&&!!s&&!r,"bg-blue-50 border-blue-500 ring-2 ring-blue-200":!!n}),"data-cse":t}),!!r&&jsx("div",__assign({className:"absolute top-0 bottom-0 flex items-center text-green-700 right-3"},{children:jsxs("svg",__assign({className:"w-6 h-6",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor"},{children:[jsx("path",{d:"M0 0h24v24H0z",fill:"none"}),jsx("path",{d:"M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z"})]}))})),!!e&&jsx("p",__assign({className:"mt-1.5 text-red-500 text-sm leading-tight"},{children:e}))]}))}function GrabPayComponent(e){var t=e.active,n=e.paymentMethod,r=e.onValid,s=e.onChange;return useEffect(function(){t&&("function"==typeof s&&s({type:n.type}),"function"==typeof r)&&r(!0)},[t]),t?jsx("div",{children:"After checkout, You will be redirected to payment page to complete this payment."}):null}function CardComponent(e){var t=e.client,n=e.active,r=e.type,s=e.brands,a=e.onValid,o=e.onChange,i=useRef(null),e=useState(!0),c=e[0],l=e[1],e=useState({}),u=e[0],d=e[1],e=useState(null),p=e[0],h=e[1],e=useState([]),y=e[0],f=e[1],e=useState({}),m=e[0],g=e[1],e=useState({}),v=e[0],x=e[1];useEffect(function(){n&&(a(!1),l(!0),d({}),h(null),f([]),g({}),x({}),function(){__awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),[4,AdyenCheckout(_)];case 1:return t=e.sent(),i.current&&t.create("securedfields",{type:r,brands:s,styles:{error:{color:"red"},validated:{color:"green"},placeholder:{color:"#d8d8d8"}},onLoad:function(){l(!0)},onConfigSuccess:function(){l(!1)},onFocus:function(e){var e=e||{},t=e.focus,e=e.fieldType;h(t?e:null)},onBinLookup:function(e){e=(e||{}).detectedBrands;f(e||[])}}).mount(i.current),[3,3];case 2:return t=e.sent(),"development"===process.env.NODE_ENV&&console.log("[ERROR] Handle create checkout error: ",t),[3,3];case 3:return[2]}})})}())},[n,r]),useEffect(function(){var e;u&&"function"==typeof a&&(e=!!(u.encryptedCardNumber&&u.encryptedExpiryMonth&&u.encryptedExpiryYear&&u.encryptedSecurityCode),a(e),o({type:u.type,brand:u.brand,encryptedCardNumber:u.encryptedCardNumber,encryptedExpiryMonth:u.encryptedExpiryMonth,encryptedExpiryYear:u.encryptedExpiryYear,encryptedSecurityCode:u.encryptedSecurityCode,cardholder:u.cardholder}))},[u]);var e=t.getConfig(),_={locale:"en_US",environment:e.clientEnv,clientKey:e.clientKey,analytics:{enabled:!1},onChange:function(e){var t=(e=e||{}).data,n=e.valid,e=e.errors;d(!!t&&t.paymentMethod||{}),x(Object.assign(__assign(__assign({},n||{}),{encryptedExpiryDate:n.encryptedExpiryMonth&&n.encryptedExpiryYear}))),g(e||{})}};return n?jsxs("div",__assign({className:classNames({"relative transition-all":!0,"h-96 max-h-96":!!c,"h-auto max-h-120":!c})},{children:[jsxs("div",__assign({className:"flex my-3 space-x-3"},{children:[jsx(CheckoutCardLogo,{active:y.includes("visa"),logoUrl:"logo/visa.svg",client:t}),jsx(CheckoutCardLogo,{active:y.includes("mc"),logoUrl:"logo/mastercard.svg",client:t}),jsx(CheckoutCardLogo,{active:y.includes("amex"),logoUrl:"logo/american-express.svg",client:t})]})),jsxs("div",__assign({ref:i,className:classNames({"opacity-0":!!c})},{children:[jsxs("div",{children:[jsx(Label,__assign({htmlFor:"cardNumber"},{children:"Card number"})),jsx(CheckoutInputField,{field:"encryptedCardNumber",focus:"encryptedCardNumber"===p,valids:v,errors:m})]}),jsxs("div",__assign({className:"grid grid-cols-2 gap-6"},{children:[jsxs("div",{children:[jsx(Label,__assign({htmlFor:"expiryDate"},{children:"Expiry date"})),jsx(CheckoutInputField,{field:"encryptedExpiryDate",focus:"encryptedExpiryDate"===p,valids:v,errors:m})]}),jsxs("div",{children:[jsx(Label,__assign({htmlFor:"securityCode"},{children:"Security Code (CVV/CVC)"})),jsx(CheckoutInputField,{field:"encryptedSecurityCode",focus:"encryptedSecurityCode"===p,valids:v,errors:m})]})]}))]})),jsxs("div",__assign({className:classNames({"absolute inset-0 flex flex-col gap-3 items-center justify-center":!0,"opacity-0 pointer-events-none":!c})},{children:[jsx("div",__assign({className:"w-16 h-16"},{children:jsxs("svg",__assign({className:"w-full h-full animate-spin",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},{children:[jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}))})),jsx("p",{children:"Loading"})]}))]})):null}function CheckoutPaymentMethod(e){var t=e.active,n=e.children,e=e.onClick;return jsx("div",__assign({className:classNames({"border px-3 py-2 mb-2 rounded-md cursor-pointer":!0,"bg-primary-500 text-white border-primary-500":!!t,"text-gray-300 border-gray-300":!t}),onClick:e},{children:n}))}function CheckoutContainer(e){var r=e.client,s=e.amount,t=e.onValid,e=e.onChange,n=r.getApiKey(),a=useState(!0),o=a[0],i=a[1],a=useState([]),c=a[0],l=a[1],a=useState(null),u=a[0],d=a[1];return useEffect(function(){n?function(n){__awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:return[4,axios.post("".concat(r.getConfig().baseApiUri,"/koomipay/payment-methods"),{amount:{currency:s.currency,price:s.price}},{headers:{"X-API-KEY":n}})];case 1:return(t=e.sent())&&t.data&&t.data.success&&(l(t.data.paymentMethods),d(!!t.data.paymentMethods&&t.data.paymentMethods[0]),i(!1)),[2]}})})}(n):i(!1)},[n]),jsxs("div",o?__assign({className:classNames({"mx-auto w-64 h-64 inset-0 flex flex-col gap-3 items-center justify-center":!0,"opacity-0 pointer-events-none":!o})},{children:[jsx("div",__assign({className:"w-16 h-16"},{children:jsxs("svg",__assign({className:"w-full h-full animate-spin",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24"},{children:[jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}))})),jsx("p",{children:"Loading"})]}):{children:[(c||[]).map(function(t){return jsx(CheckoutPaymentMethod,__assign({active:(u||{}).type===t.type,onClick:function(){var e;e=t,(u||{}).type!==(e||{}).type&&d(e)}},{children:t.name}),t.type)}),jsxs("div",__assign({className:classNames({"border-t border-gray-200 mt-6 py-3":!0})},{children:[jsx(CardComponent,{client:r,active:!!u&&"scheme"===u.type,type:"card",brands:["mc","visa","amex"],onValid:t,onChange:e}),jsx(GrabPayComponent,{active:!!u&&u.type.includes("grabpay"),paymentMethod:u,onValid:t,onChange:e})]}))]})}Label.defaultProps={error:!1};var environments=["dev","test","live"],configuration={dev:{baseApiUri:"http://localhost:32022",assetHost:"http://localhost:3000",clientEnv:"TEST",clientKey:"test_6FPMOVL2VVGJ7PASYRZDHX2AHAM6D5SG"},test:{baseApiUri:"https://api-pay-demo.koomi.app",assetHost:"https://pay-demo.koomi.app",clientEnv:"TEST",clientKey:"test_6FPMOVL2VVGJ7PASYRZDHX2AHAM6D5SG"},live:{baseApiUri:"https://api-pay-demo.koomi.app",assetHost:"https://pay-demo.koomi.app",clientEnv:"TEST",clientKey:"test_6FPMOVL2VVGJ7PASYRZDHX2AHAM6D5SG"}};function getConfig(e){if(!e)throw new Error('getConfig(env) expected env as string, but got "'.concat(e,'"'));if(environments.includes(e))return configuration[e];throw new Error("env must be one of ".concat(environments.join(", ")))}function createClient(e){var t=e.apiKey,e=e.env;return new KoomiPayClient({apiKey:t,env:e})}var KoomiPayClient=function(){function e(e){this.apiKey=e.apiKey,this.env=e.env,this.config=getConfig(e.env)}return e.prototype.setConfig=function(e){"apiKey"in e&&(this.apiKey=e.apiKey),"env"in e&&(this.env=e.env,this.config=getConfig(e.env))},e.prototype.getConfig=function(){return this.config},e.prototype.getApiKey=function(){return this.apiKey},e.prototype.getEnv=function(){return this.env},e.prototype.checkout=function(n,r){return void 0===r&&(r={}),__awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:r&&this.setConfig(r),e.label=1;case 1:return e.trys.push([1,3,,4]),[4,axios.post("".concat(this.config.baseApiUri,"/koomipay/checkout"),n,{headers:{"X-API-KEY":this.apiKey}})];case 2:return[2,e.sent()];case 3:throw t=e.sent(),console.log("[DEBUG] Checkout error",t),new Error("Error when checkout, please check your payload");case 4:return[2]}})})},e.prototype.instantCheckout=function(n,r){return void 0===r&&(r={}),__awaiter(this,void 0,void 0,function(){var t;return __generator(this,function(e){switch(e.label){case 0:r&&this.setConfig(r),e.label=1;case 1:return e.trys.push([1,3,,4]),[4,axios.post("".concat(this.config.baseApiUri,"/koomipay/instant-checkout"),n,{headers:{"X-API-KEY":this.apiKey}})];case 2:return[2,e.sent()];case 3:throw t=e.sent(),console.log("[DEBUG] Instant Checkout error",t),new Error("Error when checkout, please check your payload");case 4:return[2]}})})},e}();export{CheckoutContainer,createClient};
@@ -0,0 +1 @@
1
+ {"type":"module"}
@@ -0,0 +1,51 @@
1
+ import React from "react";
2
+ import { KoomiPayClient, CheckoutAmount } from "../lib/client";
3
+ export type CardPaymentMethodPayload = {
4
+ type: string;
5
+ brand?: string;
6
+ encryptedCardNumber?: string;
7
+ encryptedExpiryMonth?: string;
8
+ encryptedExpiryYear?: string;
9
+ encryptedSecurityCode?: string;
10
+ cardholder?: string;
11
+ };
12
+ export type OnPaymentMethodChangeCallback = (args: CardPaymentMethodPayload) => void;
13
+ export type CheckoutInputFieldProps = {
14
+ field: string;
15
+ focus: boolean;
16
+ valids: any;
17
+ errors: any;
18
+ };
19
+ export type GrabPayComponentProps = {
20
+ client?: KoomiPayClient;
21
+ active: boolean;
22
+ onValid: (isValid: boolean) => void;
23
+ onChange: OnPaymentMethodChangeCallback;
24
+ paymentMethod: any;
25
+ };
26
+ export type CardComponentProps = {
27
+ client: KoomiPayClient;
28
+ active: boolean;
29
+ type: string;
30
+ brands: string[];
31
+ onValid: (isValid: boolean) => void;
32
+ onChange: OnPaymentMethodChangeCallback;
33
+ };
34
+ export type CheckoutPaymentMethodProps = {
35
+ key: string;
36
+ active: boolean;
37
+ onClick: () => void;
38
+ children?: React.ReactNode | undefined;
39
+ };
40
+ export type KoomiPaymentMethod = {
41
+ type: string;
42
+ name: string;
43
+ [key: string]: any;
44
+ };
45
+ export type CheckoutContainerProps = {
46
+ client: KoomiPayClient;
47
+ amount: CheckoutAmount;
48
+ onValid: (args: any) => void;
49
+ onChange: (args: any) => void;
50
+ };
51
+ export declare function CheckoutContainer({ client, amount, onValid, onChange }: CheckoutContainerProps): JSX.Element;
@@ -0,0 +1,8 @@
1
+ /// <reference types="react" />
2
+ declare function Label({ className, error, htmlFor, info, mandatory, children }: any): JSX.Element;
3
+ declare namespace Label {
4
+ var defaultProps: {
5
+ error: boolean;
6
+ };
7
+ }
8
+ export default Label;
@@ -0,0 +1,10 @@
1
+ export type ClientConfiguration = {
2
+ baseApiUri: string;
3
+ assetHost: string;
4
+ clientEnv: string;
5
+ clientKey: string;
6
+ };
7
+ export type ClientConfigurationEnvironment = {
8
+ [key: string]: ClientConfiguration;
9
+ };
10
+ export declare function getConfig(env: string): ClientConfiguration;
@@ -0,0 +1,2 @@
1
+ export { CheckoutContainer } from "./components/CheckoutContainer";
2
+ export { createClient } from "./lib/client";
@@ -0,0 +1,30 @@
1
+ export type CheckoutPayload = {
2
+ orderID: String;
3
+ returnUrl: String;
4
+ items: CheckoutItem[];
5
+ amount: NonNullable<CheckoutAmount>;
6
+ paymentMethod: object;
7
+ };
8
+ export type CheckoutAmount = {
9
+ currency: NonNullable<string>;
10
+ price: NonNullable<number>;
11
+ };
12
+ export type CheckoutItem = {
13
+ productID: NonNullable<string | number>;
14
+ productName: NonNullable<string>;
15
+ quantity: NonNullable<number>;
16
+ price: NonNullable<number>;
17
+ };
18
+ export declare function createClient({ apiKey, env }: any): KoomiPayClient;
19
+ export declare class KoomiPayClient {
20
+ apiKey: string;
21
+ env: string;
22
+ config: any;
23
+ constructor(opts: any);
24
+ setConfig(opts: any): void;
25
+ getConfig(): any;
26
+ getApiKey(): string;
27
+ getEnv(): string;
28
+ checkout(payload: CheckoutPayload, opts?: any): Promise<import("axios").AxiosResponse<any, any>>;
29
+ instantCheckout(payload: CheckoutPayload, opts?: any): Promise<import("axios").AxiosResponse<any, any>>;
30
+ }
@@ -0,0 +1,2 @@
1
+ export declare function classNames(classNameHash: object): string;
2
+ export declare function classNameObject(classNameString: string): {};
package/package.json CHANGED
@@ -9,20 +9,13 @@
9
9
  "payments",
10
10
  "components"
11
11
  ],
12
- "version": "1.0.1",
12
+ "version": "1.0.2",
13
13
  "description": "Koomipay react components",
14
- "main": "dist/index.js",
15
- "types": "dist/types",
16
- "typings": "dist/types",
14
+ "main": "dist/cjs/index.js",
15
+ "module": "dist/es/index.js",
16
+ "types": "dist/cjs/types",
17
+ "typings": "dist/es/types",
17
18
  "license": "MIT",
18
- "exports": {
19
- ".": {
20
- "import": "./dist/index.js",
21
- "require": "./dist/index.js"
22
- },
23
- "./dist/koomipay.css": "./dist/koomipay.css",
24
- "./package.json": "./package.json"
25
- },
26
19
  "files": [
27
20
  "dist",
28
21
  "README",
@@ -33,14 +26,18 @@
33
26
  "clean": "rm -rf ./dist/*",
34
27
  "dev": "npm run clean && concurrently \"npm run dev:build-ts\" \"npm run dev:build-css\"",
35
28
  "dev:build-css": "tailwind -i ./src/global.css -o ./dist/koomipay.css --postcss ./postcss.config.js",
36
- "dev:build-ts": "tsc && tsc-alias",
29
+ "dev:build-ts": "rollup -c",
37
30
  "prod:build-css": "tailwind -i ./src/global.css -o ./dist/koomipay.css --postcss ./postcss.config.js --minify",
38
- "prod:build-ts": "tsc && tsc-alias",
31
+ "prod:build-ts": "ENV=production rollup -c && npm run minify",
32
+ "minify": "concurrently \"npm run minify:cjs\" \"npm run minify:es\"",
33
+ "minify:cjs": "uglifyjs --compress --mangle -o dist/cjs/index.js -- dist/cjs/index.js",
34
+ "minify:es": "uglifyjs --compress --mangle -o dist/es/index.js -- dist/es/index.js",
39
35
  "prepublishOnly": "npm run build",
40
36
  "test": "echo \"Error: no test specified\" && exit 1"
41
37
  },
42
38
  "author": "Novitee Team",
43
39
  "devDependencies": {
40
+ "@rollup/plugin-typescript": "^10.0.1",
44
41
  "@tailwindcss/aspect-ratio": "^0.4.2",
45
42
  "@tailwindcss/container-queries": "^0.1.0",
46
43
  "@tailwindcss/forms": "^0.5.3",
@@ -55,10 +52,11 @@
55
52
  "debug": "^4.3.4",
56
53
  "postcss": "^8.4.19",
57
54
  "postcss-import": "^15.0.0",
55
+ "rollup": "^3.5.1",
58
56
  "tailwindcss": "^3.2.4",
59
- "tsc-alias": "^1.8.1",
60
57
  "tsconfig-paths": "^4.1.1",
61
- "typescript": "^4.9.3"
58
+ "typescript": "^4.9.3",
59
+ "uglify-js": "^3.17.4"
62
60
  },
63
61
  "dependencies": {
64
62
  "@adyen/adyen-web": "^5.29.0",
@@ -1,249 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CheckoutContainer = void 0;
4
- var tslib_1 = require("tslib");
5
- var jsx_runtime_1 = require("react/jsx-runtime");
6
- var react_1 = require("react");
7
- var axios_1 = tslib_1.__importDefault(require("axios"));
8
- var adyen_web_1 = tslib_1.__importDefault(require("@adyen/adyen-web"));
9
- var format_1 = require("../utils/format");
10
- var Label_1 = tslib_1.__importDefault(require("./Label"));
11
- function resolveLogoUrl(url, config) {
12
- return "".concat(config.assetHost, "/").concat(url);
13
- }
14
- function CheckoutCardLogo(_a) {
15
- var active = _a.active, logoUrl = _a.logoUrl, client = _a.client;
16
- var config = client.getConfig();
17
- return ((0, jsx_runtime_1.jsx)("div", tslib_1.__assign({ className: (0, format_1.classNames)({
18
- "h-10": true,
19
- "grayscale opacity-30": !active,
20
- }) }, { children: (0, jsx_runtime_1.jsx)("img", { className: "object-contain w-full h-full", src: resolveLogoUrl(logoUrl, config) }) })));
21
- }
22
- function CheckoutInputField(_a) {
23
- var field = _a.field, focus = _a.focus, valids = _a.valids, errors = _a.errors;
24
- var fieldError = !!errors && errors[field];
25
- var valid = !!valids && valids[field];
26
- var filled = fieldError != null;
27
- var errorMessage = !!filled && fieldError.errorMessage;
28
- return ((0, jsx_runtime_1.jsxs)("div", tslib_1.__assign({ className: "relative mb-4" }, { children: [(0, jsx_runtime_1.jsx)("div", { className: (0, format_1.classNames)({
29
- "h-12 border px-3 py-1.5 rounded-md overflow-hidden": true,
30
- "border-gray-200": !focus && !filled,
31
- "bg-green-50 border-green-700": !!valid,
32
- "bg-red-50 border-red-500": !focus && !!filled && !valid,
33
- "bg-blue-50 border-blue-500 ring-2 ring-blue-200": !!focus,
34
- }), "data-cse": field }), !!valid && ((0, jsx_runtime_1.jsx)("div", tslib_1.__assign({ className: "absolute top-0 bottom-0 flex items-center text-green-700 right-3" }, { children: (0, jsx_runtime_1.jsxs)("svg", tslib_1.__assign({ className: "w-6 h-6", xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", fill: "currentColor" }, { children: [(0, jsx_runtime_1.jsx)("path", { d: "M0 0h24v24H0z", fill: "none" }), (0, jsx_runtime_1.jsx)("path", { d: "M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z" })] })) }))), !!errorMessage && (0, jsx_runtime_1.jsx)("p", tslib_1.__assign({ className: "mt-1.5 text-red-500 text-sm leading-tight" }, { children: errorMessage }))] })));
35
- }
36
- function GrabPayComponent(_a) {
37
- var active = _a.active, paymentMethod = _a.paymentMethod, onValid = _a.onValid, onChange = _a.onChange;
38
- (0, react_1.useEffect)(function () {
39
- if (!!active) {
40
- if (typeof onChange === "function") {
41
- onChange({
42
- type: paymentMethod.type,
43
- });
44
- }
45
- if (typeof onValid === "function") {
46
- onValid(true);
47
- }
48
- }
49
- }, [active]);
50
- if (!active) {
51
- return null;
52
- }
53
- return (0, jsx_runtime_1.jsx)("div", { children: "After checkout, You will be redirected to payment page to complete this payment." });
54
- }
55
- function CardComponent(_a) {
56
- var client = _a.client, active = _a.active, type = _a.type, brands = _a.brands, onValid = _a.onValid, onChange = _a.onChange;
57
- var cardContainerRef = (0, react_1.useRef)(null);
58
- var _b = (0, react_1.useState)(true), loading = _b[0], setLoading = _b[1];
59
- var _c = (0, react_1.useState)({}), paymentData = _c[0], setPaymentData = _c[1];
60
- var _d = (0, react_1.useState)(null), inputFocus = _d[0], setInputFocus = _d[1];
61
- var _e = (0, react_1.useState)([]), activeCards = _e[0], setActiveCards = _e[1];
62
- var _f = (0, react_1.useState)({}), errors = _f[0], setErrors = _f[1];
63
- var _g = (0, react_1.useState)({}), validFields = _g[0], setValidFields = _g[1];
64
- (0, react_1.useEffect)(function () {
65
- if (!!active) {
66
- onValid(false);
67
- setLoading(true);
68
- setPaymentData({});
69
- setInputFocus(null);
70
- setActiveCards([]);
71
- setErrors({});
72
- setValidFields({});
73
- handleCreateCheckout({ type: type });
74
- }
75
- }, [active, type]);
76
- (0, react_1.useEffect)(function () {
77
- if (!!paymentData && typeof onValid === "function") {
78
- var isValid = !!paymentData.encryptedCardNumber &&
79
- !!paymentData.encryptedExpiryMonth &&
80
- !!paymentData.encryptedExpiryYear &&
81
- !!paymentData.encryptedSecurityCode;
82
- onValid(isValid);
83
- onChange({
84
- type: paymentData.type,
85
- brand: paymentData.brand,
86
- encryptedCardNumber: paymentData.encryptedCardNumber,
87
- encryptedExpiryMonth: paymentData.encryptedExpiryMonth,
88
- encryptedExpiryYear: paymentData.encryptedExpiryYear,
89
- encryptedSecurityCode: paymentData.encryptedSecurityCode,
90
- cardholder: paymentData.cardholder,
91
- });
92
- // onChange(paymentData)
93
- }
94
- }, [paymentData]);
95
- function handleOnChange(state) {
96
- var _a = state || {}, data = _a.data, valid = _a.valid, errors = _a.errors;
97
- setPaymentData((!!data && data.paymentMethod) || {});
98
- setValidFields(Object.assign(tslib_1.__assign(tslib_1.__assign({}, (valid || {})), { encryptedExpiryDate: valid.encryptedExpiryMonth && valid.encryptedExpiryYear })));
99
- setErrors(errors || {});
100
- }
101
- var clientConfig = client.getConfig();
102
- var configuration = {
103
- locale: "en_US",
104
- environment: clientConfig.clientEnv,
105
- clientKey: clientConfig.clientKey,
106
- analytics: {
107
- enabled: false,
108
- },
109
- onChange: handleOnChange,
110
- };
111
- function handleCreateCheckout(opts) {
112
- return tslib_1.__awaiter(this, void 0, void 0, function () {
113
- var checkout, e_1;
114
- return tslib_1.__generator(this, function (_a) {
115
- switch (_a.label) {
116
- case 0:
117
- _a.trys.push([0, 2, , 3]);
118
- return [4 /*yield*/, (0, adyen_web_1.default)(configuration)];
119
- case 1:
120
- checkout = _a.sent();
121
- if (!!cardContainerRef.current) {
122
- checkout
123
- .create("securedfields", {
124
- type: type,
125
- brands: brands,
126
- styles: {
127
- error: {
128
- color: "red",
129
- },
130
- validated: {
131
- color: "green",
132
- },
133
- placeholder: {
134
- color: "#d8d8d8",
135
- },
136
- },
137
- onLoad: function () {
138
- setLoading(true);
139
- },
140
- onConfigSuccess: function () {
141
- setLoading(false);
142
- },
143
- onFocus: function (data) {
144
- var _a = data || {}, focus = _a.focus, fieldType = _a.fieldType;
145
- if (!!focus) {
146
- setInputFocus(fieldType);
147
- }
148
- else {
149
- setInputFocus(null);
150
- }
151
- },
152
- onBinLookup: function (data) {
153
- var detectedBrands = (data || {}).detectedBrands;
154
- setActiveCards(detectedBrands || []);
155
- },
156
- })
157
- .mount(cardContainerRef.current);
158
- }
159
- return [3 /*break*/, 3];
160
- case 2:
161
- e_1 = _a.sent();
162
- if (process.env.NODE_ENV === "development") {
163
- console.log("[ERROR] Handle create checkout error: ", e_1);
164
- }
165
- return [3 /*break*/, 3];
166
- case 3: return [2 /*return*/];
167
- }
168
- });
169
- });
170
- }
171
- if (!active) {
172
- return null;
173
- }
174
- return ((0, jsx_runtime_1.jsxs)("div", tslib_1.__assign({ className: (0, format_1.classNames)({
175
- "relative transition-all": true,
176
- "h-96 max-h-96": !!loading,
177
- "h-auto max-h-120": !loading,
178
- }) }, { children: [(0, jsx_runtime_1.jsxs)("div", tslib_1.__assign({ className: "flex my-3 space-x-3" }, { children: [(0, jsx_runtime_1.jsx)(CheckoutCardLogo, { active: activeCards.includes("visa"), logoUrl: "logo/visa.svg", client: client }), (0, jsx_runtime_1.jsx)(CheckoutCardLogo, { active: activeCards.includes("mc"), logoUrl: "logo/mastercard.svg", client: client }), (0, jsx_runtime_1.jsx)(CheckoutCardLogo, { active: activeCards.includes("amex"), logoUrl: "logo/american-express.svg", client: client })] })), (0, jsx_runtime_1.jsxs)("div", tslib_1.__assign({ ref: cardContainerRef, className: (0, format_1.classNames)({
179
- "opacity-0": !!loading,
180
- }) }, { children: [(0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)(Label_1.default, tslib_1.__assign({ htmlFor: "cardNumber" }, { children: "Card number" })), (0, jsx_runtime_1.jsx)(CheckoutInputField, { field: "encryptedCardNumber", focus: inputFocus === "encryptedCardNumber", valids: validFields, errors: errors })] }), (0, jsx_runtime_1.jsxs)("div", tslib_1.__assign({ className: "grid grid-cols-2 gap-6" }, { children: [(0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)(Label_1.default, tslib_1.__assign({ htmlFor: "expiryDate" }, { children: "Expiry date" })), (0, jsx_runtime_1.jsx)(CheckoutInputField, { field: "encryptedExpiryDate", focus: inputFocus === "encryptedExpiryDate", valids: validFields, errors: errors })] }), (0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)(Label_1.default, tslib_1.__assign({ htmlFor: "securityCode" }, { children: "Security Code (CVV/CVC)" })), (0, jsx_runtime_1.jsx)(CheckoutInputField, { field: "encryptedSecurityCode", focus: inputFocus === "encryptedSecurityCode", valids: validFields, errors: errors })] })] }))] })), (0, jsx_runtime_1.jsxs)("div", tslib_1.__assign({ className: (0, format_1.classNames)({
181
- "absolute inset-0 flex flex-col gap-3 items-center justify-center": true,
182
- "opacity-0 pointer-events-none": !loading,
183
- }) }, { children: [(0, jsx_runtime_1.jsx)("div", tslib_1.__assign({ className: "w-16 h-16" }, { children: (0, jsx_runtime_1.jsxs)("svg", tslib_1.__assign({ className: "w-full h-full animate-spin", xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24" }, { children: [(0, jsx_runtime_1.jsx)("circle", { className: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "4" }), (0, jsx_runtime_1.jsx)("path", { className: "opacity-75", fill: "currentColor", d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" })] })) })), (0, jsx_runtime_1.jsx)("p", { children: "Loading" })] }))] })));
184
- }
185
- function CheckoutPaymentMethod(_a) {
186
- var active = _a.active, children = _a.children, onClick = _a.onClick;
187
- return ((0, jsx_runtime_1.jsx)("div", tslib_1.__assign({ className: (0, format_1.classNames)({
188
- "border px-3 py-2 mb-2 rounded-md cursor-pointer": true,
189
- "bg-primary-500 text-white border-primary-500": !!active,
190
- "text-gray-300 border-gray-300": !active,
191
- }), onClick: onClick }, { children: children })));
192
- }
193
- function CheckoutContainer(_a) {
194
- var client = _a.client, amount = _a.amount, onValid = _a.onValid, onChange = _a.onChange;
195
- var apiKey = client.getApiKey();
196
- var _b = (0, react_1.useState)(true), loadingPaymentMethod = _b[0], setLoadingPaymentMethod = _b[1];
197
- var _c = (0, react_1.useState)([]), paymentMethods = _c[0], setPaymentMethods = _c[1];
198
- var _d = (0, react_1.useState)(null), currentPaymentMethod = _d[0], setPaymentMethod = _d[1];
199
- (0, react_1.useEffect)(function () {
200
- if (!!apiKey) {
201
- handleGeneratePaymentMethods(apiKey);
202
- }
203
- else {
204
- setLoadingPaymentMethod(false);
205
- }
206
- }, [apiKey]);
207
- function handleGeneratePaymentMethods(apiKey) {
208
- return tslib_1.__awaiter(this, void 0, void 0, function () {
209
- var response;
210
- return tslib_1.__generator(this, function (_a) {
211
- switch (_a.label) {
212
- case 0: return [4 /*yield*/, axios_1.default.post("".concat(client.getConfig().baseApiUri, "/koomipay/payment-methods"), {
213
- amount: {
214
- currency: amount.currency,
215
- price: amount.price,
216
- },
217
- }, {
218
- headers: {
219
- "X-API-KEY": apiKey,
220
- },
221
- })];
222
- case 1:
223
- response = _a.sent();
224
- if (!!response && response.data && response.data.success) {
225
- setPaymentMethods(response.data.paymentMethods);
226
- setPaymentMethod(!!response.data.paymentMethods && response.data.paymentMethods[0]);
227
- setLoadingPaymentMethod(false);
228
- }
229
- return [2 /*return*/];
230
- }
231
- });
232
- });
233
- }
234
- function handleChangePaymentMethod(updatedPaymentMethod) {
235
- if ((currentPaymentMethod || {}).type !== (updatedPaymentMethod || {}).type) {
236
- setPaymentMethod(updatedPaymentMethod);
237
- }
238
- }
239
- if (!!loadingPaymentMethod) {
240
- return ((0, jsx_runtime_1.jsxs)("div", tslib_1.__assign({ className: (0, format_1.classNames)({
241
- "mx-auto w-64 h-64 inset-0 flex flex-col gap-3 items-center justify-center": true,
242
- "opacity-0 pointer-events-none": !loadingPaymentMethod,
243
- }) }, { children: [(0, jsx_runtime_1.jsx)("div", tslib_1.__assign({ className: "w-16 h-16" }, { children: (0, jsx_runtime_1.jsxs)("svg", tslib_1.__assign({ className: "w-full h-full animate-spin", xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24" }, { children: [(0, jsx_runtime_1.jsx)("circle", { className: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", strokeWidth: "4" }), (0, jsx_runtime_1.jsx)("path", { className: "opacity-75", fill: "currentColor", d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" })] })) })), (0, jsx_runtime_1.jsx)("p", { children: "Loading" })] })));
244
- }
245
- return ((0, jsx_runtime_1.jsxs)("div", { children: [(paymentMethods || []).map(function (paymentMethod) { return ((0, jsx_runtime_1.jsx)(CheckoutPaymentMethod, tslib_1.__assign({ active: (currentPaymentMethod || {}).type === paymentMethod.type, onClick: function () { return handleChangePaymentMethod(paymentMethod); } }, { children: paymentMethod.name }), paymentMethod.type)); }), (0, jsx_runtime_1.jsxs)("div", tslib_1.__assign({ className: (0, format_1.classNames)({
246
- "border-t border-gray-200 mt-6 py-3": true,
247
- }) }, { children: [(0, jsx_runtime_1.jsx)(CardComponent, { client: client, active: !!currentPaymentMethod && currentPaymentMethod.type === "scheme", type: "card", brands: ["mc", "visa", "amex"], onValid: onValid, onChange: onChange }), (0, jsx_runtime_1.jsx)(GrabPayComponent, { active: !!currentPaymentMethod && currentPaymentMethod.type.includes("grabpay"), paymentMethod: currentPaymentMethod, onValid: onValid, onChange: onChange })] }))] }));
248
- }
249
- exports.CheckoutContainer = CheckoutContainer;
@@ -1,13 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- var tslib_1 = require("tslib");
4
- var jsx_runtime_1 = require("react/jsx-runtime");
5
- var format_1 = require("../utils/format");
6
- function Label(_a) {
7
- var className = _a.className, error = _a.error, htmlFor = _a.htmlFor, info = _a.info, mandatory = _a.mandatory, children = _a.children;
8
- return ((0, jsx_runtime_1.jsxs)("div", tslib_1.__assign({ className: "flex items-center justify-between" }, { children: [(0, jsx_runtime_1.jsxs)("label", tslib_1.__assign({ htmlFor: htmlFor, className: (0, format_1.classNames)(tslib_1.__assign(tslib_1.__assign({}, (0, format_1.classNameObject)(className)), { "block text-base font-medium mb-1.5": true, "text-gray-900 dark:text-white": !error, "text-red-600 dark:text-red-500": !!error })) }, { children: [children, mandatory && (0, jsx_runtime_1.jsx)("span", tslib_1.__assign({ className: "ml-1 text-red-500" }, { children: "*" }))] })), info && (0, jsx_runtime_1.jsx)("span", tslib_1.__assign({ className: "text-sm leading-5 text-gray-500 dark:text-gray-500 ".concat(error && "text-red-600") }, { children: info }))] })));
9
- }
10
- exports.default = Label;
11
- Label.defaultProps = {
12
- error: false,
13
- };
@@ -1,34 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getConfig = void 0;
4
- var environments = ["dev", "test", "live"];
5
- var configuration = {
6
- "dev": {
7
- "baseApiUri": "http://localhost:32022",
8
- "assetHost": "http://localhost:3000",
9
- "clientEnv": "TEST",
10
- "clientKey": "test_6FPMOVL2VVGJ7PASYRZDHX2AHAM6D5SG",
11
- },
12
- "test": {
13
- "baseApiUri": "https://api-pay-demo.koomi.app",
14
- "assetHost": "https://pay-demo.koomi.app",
15
- "clientEnv": "TEST",
16
- "clientKey": "test_6FPMOVL2VVGJ7PASYRZDHX2AHAM6D5SG",
17
- },
18
- "live": {
19
- "baseApiUri": "https://api-pay-demo.koomi.app",
20
- "assetHost": "https://pay-demo.koomi.app",
21
- "clientEnv": "TEST",
22
- "clientKey": "test_6FPMOVL2VVGJ7PASYRZDHX2AHAM6D5SG",
23
- }
24
- };
25
- function getConfig(env) {
26
- if (!env) {
27
- throw new Error("getConfig(env) expected env as string, but got \"".concat(env, "\""));
28
- }
29
- if (!environments.includes(env)) {
30
- throw new Error("env must be one of ".concat(environments.join(", ")));
31
- }
32
- return configuration[env];
33
- }
34
- exports.getConfig = getConfig;
package/dist/index.js DELETED
@@ -1,7 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createClient = exports.CheckoutContainer = void 0;
4
- var CheckoutContainer_1 = require("./components/CheckoutContainer");
5
- Object.defineProperty(exports, "CheckoutContainer", { enumerable: true, get: function () { return CheckoutContainer_1.CheckoutContainer; } });
6
- var client_1 = require("./lib/client");
7
- Object.defineProperty(exports, "createClient", { enumerable: true, get: function () { return client_1.createClient; } });
@@ -1,98 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.KoomiPayClient = exports.createClient = void 0;
4
- var tslib_1 = require("tslib");
5
- var config_1 = require("../config");
6
- var axios_1 = tslib_1.__importDefault(require("axios"));
7
- function createClient(_a) {
8
- var apiKey = _a.apiKey, env = _a.env;
9
- return new KoomiPayClient({ apiKey: apiKey, env: env });
10
- }
11
- exports.createClient = createClient;
12
- var KoomiPayClient = /** @class */ (function () {
13
- function KoomiPayClient(opts) {
14
- this.apiKey = opts.apiKey;
15
- this.env = opts.env;
16
- this.config = (0, config_1.getConfig)(opts.env);
17
- }
18
- KoomiPayClient.prototype.setConfig = function (opts) {
19
- if ("apiKey" in opts) {
20
- this.apiKey = opts.apiKey;
21
- }
22
- if ("env" in opts) {
23
- this.env = opts.env;
24
- this.config = (0, config_1.getConfig)(opts.env);
25
- }
26
- };
27
- KoomiPayClient.prototype.getConfig = function () {
28
- return this.config;
29
- };
30
- KoomiPayClient.prototype.getApiKey = function () {
31
- return this.apiKey;
32
- };
33
- KoomiPayClient.prototype.getEnv = function () {
34
- return this.env;
35
- };
36
- KoomiPayClient.prototype.checkout = function (payload, opts) {
37
- if (opts === void 0) { opts = {}; }
38
- return tslib_1.__awaiter(this, void 0, void 0, function () {
39
- var response, error_1;
40
- return tslib_1.__generator(this, function (_a) {
41
- switch (_a.label) {
42
- case 0:
43
- if (!!opts) {
44
- this.setConfig(opts);
45
- }
46
- _a.label = 1;
47
- case 1:
48
- _a.trys.push([1, 3, , 4]);
49
- return [4 /*yield*/, axios_1.default.post("".concat(this.config.baseApiUri, "/koomipay/checkout"), payload, {
50
- headers: {
51
- "X-API-KEY": this.apiKey,
52
- },
53
- })];
54
- case 2:
55
- response = _a.sent();
56
- return [2 /*return*/, response];
57
- case 3:
58
- error_1 = _a.sent();
59
- console.log("[DEBUG] Checkout error", error_1);
60
- throw new Error("Error when checkout, please check your payload");
61
- case 4: return [2 /*return*/];
62
- }
63
- });
64
- });
65
- };
66
- KoomiPayClient.prototype.instantCheckout = function (payload, opts) {
67
- if (opts === void 0) { opts = {}; }
68
- return tslib_1.__awaiter(this, void 0, void 0, function () {
69
- var response, error_2;
70
- return tslib_1.__generator(this, function (_a) {
71
- switch (_a.label) {
72
- case 0:
73
- if (!!opts) {
74
- this.setConfig(opts);
75
- }
76
- _a.label = 1;
77
- case 1:
78
- _a.trys.push([1, 3, , 4]);
79
- return [4 /*yield*/, axios_1.default.post("".concat(this.config.baseApiUri, "/koomipay/instant-checkout"), payload, {
80
- headers: {
81
- "X-API-KEY": this.apiKey,
82
- },
83
- })];
84
- case 2:
85
- response = _a.sent();
86
- return [2 /*return*/, response];
87
- case 3:
88
- error_2 = _a.sent();
89
- console.log("[DEBUG] Instant Checkout error", error_2);
90
- throw new Error("Error when checkout, please check your payload");
91
- case 4: return [2 /*return*/];
92
- }
93
- });
94
- });
95
- };
96
- return KoomiPayClient;
97
- }());
98
- exports.KoomiPayClient = KoomiPayClient;
@@ -1,2 +0,0 @@
1
- export { CheckoutContainer } from "../components/CheckoutContainer";
2
- export { createClient } from "../lib/client";
@@ -1,20 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.classNameObject = exports.classNames = void 0;
4
- var tslib_1 = require("tslib");
5
- function classNames(classNameHash) {
6
- return Object.entries(classNameHash)
7
- .map(function (pair, i) { return (pair[1] ? pair[0] : null); })
8
- .filter(function (x) { return x; })
9
- .join(' ');
10
- }
11
- exports.classNames = classNames;
12
- function classNameObject(classNameString) {
13
- if (!classNameString)
14
- return {};
15
- return classNameString.split(" ").reduce(function (prev, className) {
16
- var _a;
17
- return (tslib_1.__assign(tslib_1.__assign({}, prev), (_a = {}, _a[className] = true, _a)));
18
- }, {});
19
- }
20
- exports.classNameObject = classNameObject;