@abdias1998/feexpay_lite
Version:
SDK React officiel pour intégrer les paiements FeexPay dans vos applications React
2 lines (1 loc) • 37.3 kB
JavaScript
;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),c=require("react"),Oe=({selectedCountry:r,onChange:i})=>e.jsxs("div",{className:"relative",children:[e.jsxs("select",{value:r,onChange:t=>i(t.target.value),className:"block w-full px-2 py-2 pr-8 border rounded-md appearance-none focus:outline-none focus:ring-2 focus:ring-primary-orange text-xs",children:[e.jsx("option",{value:"BENIN",children:"🇧🇯 Benin"}),e.jsx("option",{value:"BURKINA_FASO",children:"🇧🇫 Burkina Faso"}),e.jsx("option",{value:"CONGO_BRAZZAVILLE",children:"🇨🇬 Congo Brazzaville"}),e.jsx("option",{value:"COTE_D_IVOIRE",children:"🇨🇮 Côte d'Ivoire"}),e.jsx("option",{value:"SENEGAL",children:"🇸🇳 Sénégal"}),e.jsx("option",{value:"TOGO",children:"🇹🇬 Togo"})]}),e.jsx("div",{className:"absolute inset-y-0 right-0 flex items-center px-2 pointer-events-none",children:e.jsx("svg",{className:"w-4 h-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M19 9l-7 7-7-7"})})})]}),J={MTN:["0142","0146","0150","0151","0152","0153","0154","0156","0157","0159","0161","0162","0166","0167","0169","0190","0191","0192","0193","0196","0197"],MOOV:["0145","0155","0158","0160","0163","0164","0165","0168","0194","0195","0198","0199"],CELTIIS:["0140","0141","0143","0144","0147"]},q={BENIN:{MTN:.017,MOOV:.017,CELTIIS:.017,CORIS:.017},COTE_D_IVOIRE:{MTN:.029,MOOV:.029,ORANGE:.029,WAVE:.032},BURKINA_FASO:{MOOV:.032,ORANGE:.039},CONGO_BRAZZAVILLE:{MTN:.03},SENEGAL:{ORANGE:.019,FREE:.019},TOGO:{TOGOCOM:.03,MOOV:.03}},Se={BENIN:{MTN:"MTN",MOOV:"MOOV",CELTIIS:"CELTIIS BJ",CORIS:"CORIS"},COTE_D_IVOIRE:{MTN:"MTN CI",MOOV:"MOOV CI",ORANGE:"ORANGE CI",WAVE:"WAVE CI"},BURKINA_FASO:{MOOV:"MOOV BF",ORANGE:"ORANGE BF"},CONGO_BRAZZAVILLE:{MTN:"MTN CG"},SENEGAL:{ORANGE:"ORANGE SN",FREE:"FREE SN"},TOGO:{TOGOCOM:"TOGOCOM TG",MOOV:"MOOV TG"}},we=(r,i)=>J.MTN.includes(r)?"MTN":J.MOOV.includes(r)?"MOOV":J.CELTIIS.includes(r)?"CELTIIS":null,Y=r=>{switch(r){case"BENIN":return["MTN","MOOV","CELTIIS"];case"COTE_D_IVOIRE":return["MTN","MOOV","ORANGE"];case"BURKINA_FASO":return["MOOV","ORANGE"];case"CONGO_BRAZZAVILLE":return["MTN"];case"SENEGAL":return["ORANGE","FREE"];case"TOGO":return["TOGOCOM","MOOV"];default:return["MTN","MOOV"]}},Ie=(r,i,t,n,u)=>{if(n==="CARD"&&(u==="VISA"||u==="MASTERCARD"))return Math.ceil(r*.045);const a=q[i];let p=0;a&&a[t]&&(p=a[t]);const o=r*p;return Math.ceil(o)},Q=(r,i)=>{const t=Se[r];return t&&t[i]?t[i]:i.toLowerCase()},ke=({selectedNetwork:r,onChange:i,country:t})=>{const n=Y(t);return c.useEffect(()=>{n.length>0&&!n.includes(r)&&i(n[0])},[t,r,n,i]),e.jsxs("div",{className:"relative",children:[e.jsx("select",{value:r,onChange:u=>i(u.target.value),className:"block w-full px-2 py-2 pr-8 border rounded-md appearance-none focus:outline-none focus:ring-2 focus:ring-primary-orange text-xs",children:n.map(u=>e.jsx("option",{value:u,children:u.replace("_"," ")},u))}),e.jsx("div",{className:"absolute inset-y-0 right-0 flex items-center px-2 pointer-events-none",children:e.jsx("svg",{className:"w-4 h-4 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M19 9l-7 7-7-7"})})})]})},Le=({isOpen:r,onClose:i,status:t,message:n})=>{if(c.useEffect(()=>{if(t==="SUCCESSFUL"||t==="SUCCESS"){const o=setTimeout(()=>{i()},5e3);return()=>clearTimeout(o)}},[t,i]),!r)return null;const u=()=>{switch(t){case"SUCCESSFUL":case"SUCCESS":return e.jsx("div",{className:"w-16 h-16 mx-auto mb-4 bg-green-100 rounded-full flex items-center justify-center",children:e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-10 w-10 text-green-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})})});case"FAILED":return e.jsx("div",{className:"w-16 h-16 mx-auto mb-4 bg-red-100 rounded-full flex items-center justify-center",children:e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-10 w-10 text-red-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})});case"PENDING":return e.jsx("div",{className:"w-16 h-16 mx-auto mb-4 bg-yellow-100 rounded-full flex items-center justify-center",children:e.jsxs("svg",{className:"animate-spin h-10 w-10 text-yellow-500",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.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"})]})});case"TIMEOUT":return e.jsx("div",{className:"w-16 h-16 mx-auto mb-4 bg-gray-100 rounded-full flex items-center justify-center",children:e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-10 w-10 text-gray-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})})});default:return null}},a=()=>{switch(t){case"SUCCESSFUL":case"SUCCESS":return"Continuer";case"FAILED":case"TIMEOUT":return"Réessayer";default:return"Fermer"}},p=()=>{switch(t){case"SUCCESSFUL":case"SUCCESS":return"bg-green-500 hover:bg-green-600";case"FAILED":return"bg-red-500 hover:bg-red-600";case"TIMEOUT":return"bg-gray-500 hover:bg-gray-600";default:return"bg-gray-500 hover:bg-gray-600"}};return e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black bg-opacity-50",children:e.jsxs("div",{className:"bg-white rounded-lg shadow-xl w-full max-w-sm p-6 text-center",children:[u(),e.jsx("h3",{className:"text-xl font-bold mb-2",children:t==="SUCCESSFUL"?"Paiement Réussi":t==="FAILED"?"Paiement Échoué":t==="SUCCESS"?"Paiement Réussi":t==="PENDING"?"Traitement en cours":"Vérification expirée"}),e.jsx("p",{className:"text-gray-600 mb-6",children:n}),e.jsx("button",{onClick:i,className:`w-full ${p()} text-white font-bold py-3 px-4 rounded-md transition-colors duration-300`,children:a()})]})})},Ae=({isOpen:r,onClose:i,onSubmit:t,reference:n})=>{const[u,a]=c.useState(""),[p,o]=c.useState(!1),m=f=>{f.preventDefault(),o(!0),t(u)};return r?e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black bg-opacity-50 overflow-hidden",children:e.jsxs("div",{className:"bg-white rounded-lg shadow-xl w-full max-w-md relative",children:[e.jsxs("div",{className:"flex justify-between items-center border-b p-4",children:[e.jsx("h3",{className:"text-lg font-medium",children:"Confirmation de paiement"}),e.jsx("button",{onClick:i,className:"text-gray-500 hover:text-gray-700",children:e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),e.jsxs("div",{className:"p-6",children:[e.jsx("p",{className:"text-sm text-gray-600 mb-4",children:"Un code de confirmation a été envoyé à votre téléphone. Veuillez le saisir ci-dessous pour finaliser votre paiement."}),e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-sm text-gray-500 mb-1",children:"Référence de transaction:"}),e.jsx("p",{className:"font-medium",children:n})]}),e.jsxs("form",{onSubmit:m,children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Code OTP"}),e.jsx("input",{type:"text",value:u,onChange:f=>a(f.target.value),placeholder:"Entrez le code reçu par SMS",className:"w-full px-4 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary-orange",required:!0})]}),e.jsx("button",{type:"submit",disabled:p,className:"w-full bg-primary-orange text-white py-2 px-4 rounded-md hover:bg-orange-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-orange disabled:opacity-50",children:p?"Traitement en cours...":"Confirmer le paiement"})]})]})]})}):null},de=c.createContext(void 0),fe=()=>{const r=c.useContext(de);if(!r)throw new Error("useFeexPay must be used within a FeexPayProvider");return r},_e={amount:0,description:"",id:"",token:"",mode:"SANDBOX"},Te=({children:r})=>{const[i,t]=c.useState(_e);return e.jsx(de.Provider,{value:{paymentConfig:i,setPaymentConfig:t},children:r})},Fe=async()=>{try{return(await(await fetch("https://api.ipify.org?format=json")).json()).ip}catch{return"unknown"}},me=async r=>{const i=Q(r.country,r.network),t="https://api.feexpay.me/api/transactions/requesttopay/integration";let n=r.phoneNumber.replace(/\+/g,"");if(n.length>=8){const u=n.slice(0,3);n.startsWith(u+u)&&(n=n.slice(u.length))}try{const u=window.location.origin,a=await Fe(),p={phoneNumber:n,amount:r.amount,reseau:i,description:r.description,customId:r.customId,shop:r.id,token:r.token,merchant_domain:u,merchant_ip:a,payment_interface:"REACT",callback_info:r.callback_info||{},currency:r.currency||"XOF",first_name:r.first_name,email:r.email,otp:r.otp||""},o=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.token}`},body:JSON.stringify(p)});if(!o.ok)throw new Error("Payment request failed");return await o.json()}catch(u){throw console.error("Payment request error:",u),u}},Re=async r=>{const i=`https://api.feexpay.me/api/transactions/getrequesttopay/integration/${r}`;try{const t=await fetch(i);if(!t.ok)throw new Error("Status check failed");return await t.json()}catch(t){throw console.error("Status check error:",t),t}},Me=async r=>{const i="https://api.feexpay.me/api/transactions/details";try{const n={network:Q(r.country,r.network),amount:r.amount,shop:r.id},u=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.token}`},body:JSON.stringify(n)});if(!u.ok)throw new Error("Failed to get transaction details");return await u.json()}catch(t){throw console.error("Transaction details error:",t),t}},Pe=async r=>{const i="https://api.feexpay.me/api/transactions/public/initcard";try{const t={phone:r.phone,amount:r.amount,shop:r.id,first_name:r.first_name,last_name:r.last_name,email:r.email,type_card:r.type_card,currency:"XOF"},n=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.token}`},body:JSON.stringify(t)});if(!n.ok)throw new Error("Card payment request failed");return await n.json()}catch(t){throw console.error("Card payment request error:",t),t}},ce=async r=>{const i="https://api.feexpay.me/api/transactions/requesttopay/integration";try{const t="229",n=r.phoneNumber.startsWith("+229")?r.phoneNumber.substring(4):r.phoneNumber.startsWith("229")?r.phoneNumber.substring(3):r.phoneNumber,u={phoneNumber:`229${n}`,country:t,phoneNumberRight:n,amount:r.amount.toString(),currency:"XOF",description:r.description||"Paiement via FeexPay",email:r.email,first_name:r.first_name,otp:r.otp||"",reference:r.reference||"",reseau:"CORIS",shop:r.id,token:r.token,callback_info:r.callback_info||{}},a=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});return{...await a.json(),statusCode:a.status.toString()}}catch(t){throw console.error("Wallet Coris payment request error:",t),t}},he=async r=>{const i=`https://api.feexpay.me/api/shop/${r}/get_shop`;try{const t=await fetch(i);if(!t.ok)throw new Error("Shop retrieval failed");return await t.json()}catch(t){throw console.error("Shop retrieval error:",t),t}},ue=async(r,i,t,n)=>{if(r.preventDefault(),!t())return;const{baseAmount:u,network:a,country:p,paymentConfig:o,generateRandomId:m,fullName:f,email:A,setStateCallbacks:x}=i,{setTransactionReference:_,setPaymentStatus:g,setStatusMessage:T,setStatusModalOpen:w,setIsLoading:y}=x;y(!0);try{const v=n(),h=await me({phoneNumber:v,amount:u,network:a,country:p,description:o.description,customId:o.customId||m(),id:o.id,token:o.token,currency:o.currency||"XOF",callback_info:o.callback_info||{},first_name:f,email:A});if(h.statusCode==="10"){g("INSUFFICIENT_FUNDS"),T("Fonds insuffisants. Veuillez vérifier votre solde et réessayer."),w(!0),y(!1),o.callback&&o.callback({reference:h.reference,status:"FAILED",phoneNumber:v,reseau:a,callback_info:o.callback_info||{},description:o.description,transaction_id:h.reference,message:"Le paiement a échoué. Veuillez vérifier votre solde et réessayer.",amount:o.amount,currency:o.currency||"XOF",first_name:f,email:A}),o.error_callback_url&&(window.location.href=`${o.error_callback_url}?ref=${h.reference}`);return}else if(h.statusCode==="92"){g("FAILED"),T("La transaction a été annulée. Veuillez réessayer."),w(!0),y(!1),o.callback&&o.callback({reference:h.reference,status:"FAILED",phoneNumber:v,reseau:a,callback_info:o.callback_info||{},description:o.description,transaction_id:h.reference,message:"La transaction a été annulée. Veuillez réessayer.",amount:o.amount,first_name:f,email:A,currency:o.currency||"XOF"}),o.error_callback_url&&(window.location.href=`${o.error_callback_url}?ref=${h.reference}`);return}return _(h.reference),pe(h.reference,i,a,n),{reference:h.reference}}catch(v){console.error("Payment error:",v),g("FAILED"),T("Le paiement a échoué. Veuillez réessayer."),w(!0),y(!1)}},pe=(r,i,t,n)=>{let u=0;const a=12;let p=!1,o=null;const{paymentConfig:m,setStateCallbacks:f,fullName:A,email:x}=i,{setPaymentStatus:_,setStatusMessage:g,setStatusModalOpen:T,setIsLoading:w}=f,y=(h,F,R)=>{if(i.isCallbackCalledRef.current)return;i.isCallbackCalledRef.current=!0,o&&clearTimeout(o),_(h),g(F),T(!0),w(!1);const D={reference:r,status:R,phoneNumber:n(),reseau:t,callback_info:m.callback_info||{},description:m.description,transaction_id:r,message:F,amount:m.amount,currency:m.currency||"XOF",first_name:A,email:x};m.callback&&m.callback(D);const M=R==="SUCCESSFUL"||R==="SUCCESS";M&&m.callback_url?window.location.href=`${m.callback_url}?ref=${r}`:!M&&m.error_callback_url&&(window.location.href=`${m.error_callback_url}?ref=${r}`)},v=async()=>{if(!p){u++;try{const h=await Re(r);if(h.reason==="LOW_BALANCE_OR_PAYEE_LIMIT_REACHED_OR_NOT_ALLOWED"){y("INSUFFICIENT_FUNDS","Fonds insuffisants. Veuillez vérifier votre solde et réessayer.","FAILED");return}else if(h.reason==="PAYER NOT FOUND"){y("FAILED","Numéro de téléphone non trouvé. Veuillez vérifier le numéro et réessayer.","FAILED");return}const F=h.status.toUpperCase();switch(F){case"SUCCESSFUL":case"SUCCESS":y("SUCCESSFUL","Paiement réussi !",F);break;case"FAILED":y("FAILED","Le paiement a échoué. Veuillez réessayer.","FAILED");break;case"INSUFFICIENT_FUNDS":y("INSUFFICIENT_FUNDS","Fonds insuffisants. Veuillez vérifier votre solde et réessayer.","INSUFFICIENT_FUNDS");break;case"TIMEOUT":y("TIMEOUT","La vérification du paiement a expiré.","TIMEOUT");break;case"PENDING":u>=a?y("TIMEOUT","La vérification du paiement a expiré. Veuillez vérifier votre compte.","TIMEOUT"):o=setTimeout(v,1e4);break;default:u>=a&&y("TIMEOUT","Statut de transaction inconnu après plusieurs tentatives.","TIMEOUT");break}}catch(h){console.error(`Status check failed for ref ${r}:`,h),u>=a&&y("TIMEOUT","La vérification du paiement a échoué après plusieurs tentatives.","TIMEOUT")}}};return v(),()=>{o&&clearTimeout(o),p=!0}},Ve=({id:r,onClose:i})=>{const[t,n]=c.useState(null);return c.useEffect(()=>{(async()=>{try{const a=await he(r);n(a)}catch(a){console.error("Erreur de récupération du id :",a)}})()},[r]),e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-gray-200",children:[e.jsx("div",{children:e.jsx("img",{src:"https://api.feexpay.me/api/static/feexpay_logo-h.png",width:"100",alt:"Logo"})}),e.jsx("div",{className:"text-right text-xs text-gray-700 ",children:t&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"font-semibold",children:["MARCHAND: ",t.name]}),e.jsxs("div",{className:"text-xs text-gray-500",children:["ID : ",t.reference]})]})}),e.jsx("button",{onClick:i,className:"text-gray-500 hover:text-gray-700",children:e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-6 w-6",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})},De=({isOpen:r,onClose:i})=>{var le;const{paymentConfig:t}=fe(),[n,u]=c.useState(()=>t.case&&["MOBILE","CARD","WALLET"].includes(t.case)?t.case:"MOBILE"),[a,p]=c.useState("BENIN"),[o,m]=c.useState("MTN"),[f,A]=c.useState(""),[x,_]=c.useState(""),[g,T]=c.useState(""),[w,y]=c.useState("VISA"),[v,h]=c.useState(0),[F,R]=c.useState(0),[D,M]=c.useState(0),[X,L]=c.useState(0),[U,P]=c.useState(""),[z,N]=c.useState(!1),[xe,S]=c.useState("PENDING"),[ge,E]=c.useState(""),[Z,j]=c.useState(!1),[ye,W]=c.useState(!1),[ee,Ne]=c.useState(""),[te,re]=c.useState(null),G=c.useRef(!1),se=c.useRef(null),H=c.useCallback((s,l,b,k)=>{const O=Ie(s,l,b,k||n,w);if(M(O),R(s+O),h(s),n==="CARD"&&(w==="VISA"||w==="MASTERCARD"))L(4.5);else{const V=q[l];V&&V[b]?L(V[b]*100):L(0)}},[n,w]),I=c.useCallback(async(s,l,b,k)=>{try{const d=k||n,O=await Me({network:b,country:l,amount:s,id:t.id,token:t.token,callback_info:t.callback_info||{}});if(O&&O.iffees){let V=!1;if(s<=30){const C=q[l];C&&C[b]&&C[b]>0&&(M(1),R(s+1),L(C[b]*100),V=!0)}if(!V){if(O.total!==void 0){const C=O.total-s;M(C),R(O.total)}else H(s,l,b,d);if(d==="CARD")L(4.5);else{const C=q[l];C&&C[b]?L(C[b]*100):L(0)}}}else M(0),R(s),L(0);h(s)}catch(d){console.error("Erreur lors de la récupération des détails de transaction:",d),H(s,l,b,k)}},[n,t.id,t.token,H]);c.useEffect(()=>{t.amount&&(h(t.amount),I(t.amount,a,o))},[t,a,o,I]),c.useEffect(()=>{n==="WALLET"&&(a==="BENIN"?(m("CORIS"),t.amount&&I(t.amount,a,"CORIS",n)):a==="COTE_D_IVOIRE"?(m("WAVE"),t.amount&&I(t.amount,a,"WAVE",n)):(p("BENIN"),m("CORIS"),t.amount&&I(t.amount,"BENIN","CORIS",n)))},[]);const ne=s=>{m(s),t.amount&&I(t.amount,a,s)},be=()=>{_(""),T(""),A(""),y("VISA")},Ee=s=>{if(be(),M(0),R(t.amount||0),L(0),u(s),s==="WALLET")a==="BENIN"?(m("CORIS"),t.amount&&I(t.amount,a,"CORIS",s)):a==="COTE_D_IVOIRE"?(m("WAVE"),t.amount&&I(t.amount,a,"WAVE",s)):(p("BENIN"),m("CORIS"),t.amount&&I(t.amount,"BENIN","CORIS",s));else if(s==="MOBILE"){const l=Y(a);l.length>0&&(l.includes(o)||m(l[0]),t.amount&&I(t.amount,a,o,s))}else s==="CARD"&&t.amount&&I(t.amount,a,o,s)},ae=s=>{if(p(s),n==="WALLET")s==="BENIN"?(m("CORIS"),t.amount&&I(t.amount,s,"CORIS")):s==="COTE_D_IVOIRE"&&(m("WAVE"),t.amount&&I(t.amount,s,"WAVE"));else{const l=Y(s);m(l[0]),t.amount&&I(t.amount,s,l[0])}},oe=s=>{const l=s.target.value;if(a==="BENIN"&&n!=="WALLET"&&l.length>=4){const b=l.substring(0,4),k=we(b);k&&m(k)}A(l)},$=()=>{if(!f)return f;let s=f.replace(/[^0-9]/g,""),l="";switch(a){case"BENIN":l="229";break;case"COTE_D_IVOIRE":l="225";break;case"BURKINA_FASO":l="226";break;case"CONGO_BRAZZAVILLE":l="242";break;case"SENEGAL":l="221";break;case"TOGO":l="228";break;default:return s}return s.startsWith(l+l)&&(s=s.slice(l.length)),s.startsWith(l)?s:l+s},ve=s=>{switch(s){case"BENIN":return"+229";case"COTE_D_IVOIRE":return"+225";case"BURKINA_FASO":return"+226";case"CONGO_BRAZZAVILLE":return"+242";case"SENEGAL":return"+221";case"TOGO":return"+228";default:return""}},Ce=async s=>{var k;if(s.preventDefault(),!K())return;G.current=!1,j(!0);const l=["MOOV CI","ORANGE CI","MOOV BF","ORANGE BF","FREE SN","WAVE CI","ORANGE SN"],b=Q(a,o);if(l.includes(b)){try{const d=await me({phoneNumber:$(),amount:v,network:o,country:a,description:t.description||"Payment",customId:t.customId||"",id:t.id,token:t.token,currency:t.currency||"XOF",callback_info:t.callback_info||{},first_name:x||"",email:g||"",otp:((k=se.current)==null?void 0:k.value)||""});if(d.payment_url&&re(d.payment_url),d.reference)P(d.reference),B(d.reference);else if(!d.payment_url)throw new Error("La réponse de paiement est invalide.")}catch(d){console.error("Payment error:",d),S("FAILED"),E("Le paiement a échoué. Veuillez réessayer."),N(!0)}finally{j(!1)}return}try{if(n==="CARD"){const d=x.split(" "),O=d[0]||"",V=d.slice(1).join(" ")||"",C=await Pe({phone:f,amount:v,id:t.id,first_name:O,last_name:V,email:g,type_card:w,token:t.token,currency:t.currency||"XOF"});C&&C.reference?(P(C.reference),B(C.reference)):(S("FAILED"),E("La demande de paiement par carte a échoué. Veuillez réessayer."),N(!0),j(!1))}else if(n==="MOBILE"){const d=await ue(s,{phoneNumber:f,baseAmount:v,network:o,country:a,paymentConfig:t,transactionReference:U,fullName:x,email:g,generateRandomId:ie,isCallbackCalledRef:G,setStateCallbacks:{setTransactionReference:P,setPaymentStatus:S,setStatusMessage:E,setStatusModalOpen:N,setIsLoading:j}},K,$);d&&d.reference&&B(d.reference)}else if(n==="WALLET")if(a==="BENIN"&&o==="CORIS")try{const O=x.split(" ")[0]||"",V=f.startsWith("+229")?f:`+229${f}`,C=await ce({phoneNumber:V,amount:v,id:t.id,email:g,first_name:O,description:"Paiement via FeexPay",token:t.token,currency:t.currency||"XOF",callback_info:t.callback_info||{}});C.statusCode==="201"?(Ne(C.reference),W(!0),j(!1)):(S("FAILED"),E("La demande de paiement a échoué. Veuillez réessayer."),N(!0),j(!1))}catch(d){console.error("Error in Coris Wallet payment:",d),S("FAILED"),E("Une erreur est survenue lors du traitement du paiement. Veuillez réessayer."),N(!0),j(!1)}else{const O=await ue(s,{phoneNumber:f,baseAmount:v,network:o,country:a,paymentConfig:t,transactionReference:U,generateRandomId:ie,fullName:x,email:g,isCallbackCalledRef:G,setStateCallbacks:{setTransactionReference:P,setPaymentStatus:S,setStatusMessage:E,setStatusModalOpen:N,setIsLoading:j}},K,$);O&&O.reference&&B(O.reference)}}catch(d){console.error("Error in payment submission:",d),S("FAILED"),E("Une erreur est survenue lors du traitement du paiement. Veuillez réessayer."),N(!0),j(!1)}},K=()=>{const s=t.fields_to_hide||[];if(n==="MOBILE"||n==="WALLET"){if(!s.includes("name")&&!x.trim())return E("Veuillez entrer votre nom complet"),N(!0),!1;if(!s.includes("email")&&(!g.trim()||!g.includes("@")))return E("Veuillez entrer une adresse email valide"),N(!0),!1;if(!f.trim()||f.length<8)return E("Veuillez entrer un numéro de téléphone valide"),N(!0),!1;if(n==="WALLET"&&a!=="BENIN"&&a!=="COTE_D_IVOIRE")return E("Seuls le Bénin (Coris) et la Côte d'Ivoire (Wave) sont supportés pour les paiements Wallet"),N(!0),!1}else if(n==="CARD"){if(!x||x.trim().split(" ").length<2)return E("Veuillez entrer votre nom et prénom complets"),S("FAILED"),N(!0),!1;if(!g||!g.includes("@"))return E("Veuillez entrer une adresse email valide"),S("FAILED"),N(!0),!1;if(!f)return E("Veuillez entrer un numéro de téléphone valide"),S("FAILED"),N(!0),!1}return!0},ie=()=>`TRX-${Math.random().toString(36).substring(2,10).toUpperCase()}`,je=async s=>{j(!0);try{const b=x.split(" ")[0]||"",k=f.startsWith("+229")?f:`+229${f}`,d=await ce({phoneNumber:k,amount:v,id:t.id,email:g,first_name:b,description:"Paiement via FeexPay",reference:ee,otp:s,token:t.token,currency:t.currency||"XOF",callback_info:t.callback_info||{}});W(!1),d.reference?d.status==="SUCCESSFUL"||d.status==="SUCCESS"?(S("SUCCESSFUL"),E("Paiement effectué avec succès!"),N(!0),j(!1),t.callback_url&&setTimeout(()=>{window.location.href=`${t.callback_url}?ref=${d.reference}`},2e3)):d.status==="PENDING"?(P(d.reference),B(d.reference)):(S("FAILED"),E(d.message||"La transaction a échoué. Veuillez réessayer."),N(!0),j(!1),t.error_callback_url&&setTimeout(()=>{window.location.href=`${t.error_callback_url}?ref=${d.reference}`},2e3)):(S("FAILED"),E(d.message||"La confirmation du paiement a échoué. Veuillez réessayer."),N(!0),j(!1))}catch{S("FAILED"),E("Une erreur est survenue lors de la confirmation du paiement. Veuillez réessayer."),N(!0),j(!1),W(!1)}},B=s=>{pe(s,{paymentConfig:t,fullName:x,email:g,isCallbackCalledRef:G,setStateCallbacks:{setTransactionReference:P,setPaymentStatus:S,setStatusMessage:E,setStatusModalOpen:N,setIsLoading:j}},o,$)};return r?e.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black bg-opacity-50 overflow-hidden",children:[e.jsxs("div",{className:"bg-white rounded-lg shadow-xl w-full max-w-md relative max-h-[90vh] flex flex-col",children:[te&&e.jsxs("div",{className:"absolute inset-0 bg-white z-10 rounded-lg overflow-hidden",children:[e.jsx("button",{onClick:()=>re(null),className:"absolute top-2 right-2 z-20 bg-gray-200 text-gray-800 rounded-full p-1 hover:bg-gray-300 focus:outline-none","aria-label":"Fermer la passerelle de paiement",children:e.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M6 18L18 6M6 6l12 12"})})}),e.jsx("iframe",{src:te,className:"w-full h-full border-0",title:"Payment Gateway",allow:"payment"})]}),e.jsx(Ve,{id:t.id,onClose:i}),e.jsxs("div",{className:"p-6 overflow-y-auto flex-grow",children:[e.jsx("p",{className:"text-sm text-gray-600 text-center mb-4",children:"Remplissez les champs suivants pour effectuer votre paiement"}),!t.case&&e.jsx("div",{className:"flex justify-center mb-6 border-b pb-4 w-fit gap-2",children:[{label:"Mobile Money",value:"MOBILE",icon:e.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"#D45D00",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"5",y:"2",width:"14",height:"20",rx:"2",ry:"2"}),e.jsx("line",{x1:"12",y1:"18",x2:"12",y2:"18"})]})},{label:"Carte Bancaire",value:"CARD",icon:e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor",children:[e.jsx("path",{d:"M4 4a2 2 0 00-2 2v1h16V6a2 2 0 00-2-2H4z"}),e.jsx("path",{fillRule:"evenodd",d:"M18 9H2v5a2 2 0 002 2h12a2 2 0 002-2V9zM4 13a1 1 0 011-1h1a1 1 0 110 2H5a1 1 0 01-1-1zm5-1a1 1 0 100 2h1a1 1 0 100-2H9z",clipRule:"evenodd"})]})},{label:"Wallet",value:"WALLET",icon:e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",viewBox:"0 0 20 20",fill:"currentColor",children:e.jsx("path",{fillRule:"evenodd",d:"M10 2a1 1 0 00-1 1v1a1 1 0 002 0V3a1 1 0 00-1-1zM4 4h3a3 3 0 006 0h3a2 2 0 012 2v9a2 2 0 01-2 2H4a2 2 0 01-2-2V6a2 2 0 012-2zm2.5 7a1.5 1.5 0 100-3 1.5 1.5 0 000 3zm2.45 4a2.5 2.5 0 10-4.9 0h4.9zM12 9a1 1 0 100 2h3a1 1 0 100-2h-3zm-1 4a1 1 0 011-1h2a1 1 0 110 2h-2a1 1 0 01-1-1z",clipRule:"evenodd"})})}].map(({label:s,value:l,icon:b})=>{const k=n===l;return e.jsxs("div",{className:`flex flex-col items-center px-4 py-2 cursor-pointer rounded border ${k?"bg-[#fff7ed] border-[#D45D00]":"bg-white border-[#D45D00]"}`,onClick:()=>Ee(l),children:[e.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center mb-1",children:b}),e.jsx("span",{className:"text-xs font-medium",children:s})]},l)})}),e.jsxs("div",{className:"space-y-6",children:[!((t.fields_to_hide||[]).includes("email")&&(t.fields_to_hide||[]).includes("name"))&&n!=="CARD"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h2",{className:"font-bold text-gray-800 mb-2 flex items-center",children:[e.jsx("span",{className:"bg-gray-800 text-white rounded-full w-5 h-5 inline-flex items-center justify-center text-xs mr-2",children:"1"}),"Informations Personnelles"]}),!(t.fields_to_hide||[]).includes("name")&&e.jsx("div",{children:e.jsx("input",{type:"text",placeholder:"Nom et Prénoms",className:"w-full px-2 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary-orange text-xs",value:x,onChange:s=>_(s.target.value)})}),!(t.fields_to_hide||[]).includes("email")&&e.jsx("div",{children:e.jsx("input",{type:"email",placeholder:"Email",className:"w-full px-2 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary-orange text-xs",value:g,onChange:s=>T(s.target.value)})})]}):null,e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h2",{className:"font-bold text-gray-800 mb-2 flex items-center",children:[e.jsx("span",{className:"bg-gray-800 text-white rounded-full w-5 h-5 inline-flex items-center justify-center text-xs mr-2",children:n==="CARD"||(t.fields_to_hide||[]).includes("email")&&(t.fields_to_hide||[]).includes("name")?"1":"2"}),n==="CARD"?"Paiement par Carte Bancaire":"Méthodes de paiement"]}),n==="MOBILE"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx("div",{children:e.jsx(Oe,{selectedCountry:a,onChange:ae})}),e.jsx("div",{children:e.jsx(ke,{selectedNetwork:o,onChange:ne,country:a})})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"bg-gray-100 px-3 py-2 border border-r-0 rounded-l-md flex items-center justify-center",children:e.jsx("span",{className:"text-gray-600 text-xs",children:ve(a)})}),e.jsx("input",{type:"tel",placeholder:"Numéro de téléphone sans indicatif",className:"flex-1 px-2 py-2 border rounded-r-md focus:outline-none focus:ring-2 focus:ring-primary-orange text-xs",value:f,onChange:oe})]}),a==="SENEGAL"&&o==="ORANGE"&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"text",ref:se,id:"otp",placeholder:"L’otp de validation",className:"w-full px-2 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary-orange text-xs"}),e.jsx("span",{className:"text-xs text-gray-900",children:"L’otp de validation de la transaction obtenu en tapant #144#391# sur votre téléphone"})]})]}),n==="CARD"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-red-500 text-md",children:"Les paiements par cartes sont momentanément indisponibles."}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Prénom"}),e.jsx("input",{type:"text",placeholder:"Prénom",className:"w-full px-2 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary-orange text-xs",value:x.split(" ")[0]||"",onChange:s=>{const l=x.split(" ").slice(1).join(" ");_(`${s.target.value} ${l}`.trim())}})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Nom"}),e.jsx("input",{type:"text",placeholder:"Nom",className:"w-full px-2 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary-orange text-xs",value:x.split(" ").slice(1).join(" ")||"",onChange:s=>{const l=x.split(" ")[0]||"";_(`${l} ${s.target.value}`.trim())}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Email"}),e.jsx("input",{type:"email",placeholder:"exemple@email.com",className:"w-full px-2 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary-orange text-xs",value:g,onChange:s=>T(s.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Téléphone"}),e.jsx("input",{type:"tel",placeholder:"Numéro de téléphone avec indicatif",className:"w-full px-2 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary-orange text-xs",value:f,onChange:s=>A(s.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Type de carte"}),e.jsxs("select",{className:"w-full px-2 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary-orange text-xs",value:w,onChange:s=>y(s.target.value),children:[e.jsx("option",{value:"VISA",children:"VISA"}),e.jsx("option",{value:"MASTERCARD",children:"MASTERCARD"})]})]})]}),n==="WALLET"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Pays"}),e.jsxs("select",{value:a,onChange:s=>ae(s.target.value),className:"block w-full px-2 py-2 pr-8 border rounded-md appearance-none focus:outline-none focus:ring-2 focus:ring-primary-orange text-xs",children:[e.jsx("option",{value:"BENIN",children:"🇧🇯 Bénin"}),e.jsx("option",{value:"COTE_D_IVOIRE",children:"🇨🇮 Côte d'Ivoire"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Réseau"}),e.jsxs("select",{value:o,onChange:s=>ne(s.target.value),className:"block w-full px-2 py-2 pr-8 border rounded-md appearance-none focus:outline-none focus:ring-2 focus:ring-primary-orange text-xs",disabled:!0,children:[a==="BENIN"&&e.jsx("option",{value:"CORIS",children:"CORIS"}),a==="COTE_D_IVOIRE"&&e.jsx("option",{value:"WAVE",children:"WAVE"})]})]})]}),e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"bg-gray-100 px-3 py-2 border border-r-0 rounded-l-md flex items-center justify-center",children:e.jsx("span",{className:"text-gray-600 text-sm",children:a==="BENIN"?"+229":a==="COTE_D_IVOIRE"?"+225":""})}),e.jsx("input",{type:"tel",placeholder:"Numéro de téléphone sans indicatif",className:"flex-1 px-2 py-2 border rounded-r-md focus:outline-none focus:ring-2 focus:ring-primary-orange text-xs",value:f,onChange:oe})]})]}),e.jsxs("div",{className:"bg-gray-50 p-4 rounded-md",children:[e.jsxs("div",{className:"flex justify-between mb-1",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Montant :"}),e.jsxs("span",{className:"text-sm font-medium",children:[(le=t.amount)==null?void 0:le.toLocaleString("fr-FR")," ",t.currency]})]}),e.jsxs("div",{className:"flex justify-between mb-1",children:[e.jsx("span",{className:"text-sm text-gray-600",children:"Frais* :"}),e.jsx("span",{className:"text-sm font-medium",children:D>0?`${D.toLocaleString("fr-FR")} ${t.currency}`:`0 ${t.currency}`})]}),e.jsxs("div",{className:"flex justify-between font-bold",children:[e.jsx("span",{children:"Montant Total à payer :"}),e.jsxs("span",{children:[F.toLocaleString("fr-FR")," ",t.currency]})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:D>0?`*Les frais de transaction sont de ${X.toFixed(1).replace(".",",")}% du montant.`:"*Aucun frais de transaction applicable pour cette transaction."})]}),e.jsx("div",{className:"pt-2",children:e.jsxs("div",{className:"flex space-x-2",children:[e.jsx("button",{onClick:()=>i(),className:"w-1/3 bg-gray-200 hover:bg-gray-300 text-primary-blue font-bold py-2 px-4 rounded-md transition-colors duration-300 flex items-center justify-center",children:"Retour"}),e.jsxs("button",{onClick:Ce,disabled:Z,className:`w-2/3 bg-primary-orange hover:bg-orange-700 text-white font-bold py-2 px-4 rounded-md transition-colors duration-300 flex items-center justify-center ${Z?"opacity-70 cursor-not-allowed":""}`,children:[Z?e.jsxs("svg",{className:"animate-spin -ml-1 mr-2 h-4 w-4 text-white",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.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"})]}):null,"Payer ",F.toLocaleString("fr-FR")," ",t.currency]})]})})]})]}),e.jsxs("div",{className:"mt-6 text-center text-xs text-gray-500 flex-shrink-0 bg-gray-50 w-full p-2",children:[e.jsx("p",{className:"mt-2",children:"Paiements sécurisés par FeexPay"}),e.jsxs("p",{className:"mt-2",children:["En payant par ce plugin, vous acceptez les ",e.jsx("a",{className:"text-blue-900",style:{textDecoration:"underline"},target:"_blank",href:"https://feexpay.me/fr/terms-and-conditions",children:"conditions générales d'utilisation de FeexPay"})]})]})]})]}),e.jsx(Le,{isOpen:z,onClose:()=>N(!1),status:xe,message:ge}),e.jsx(Ae,{isOpen:ye,onClose:()=>{W(!1),j(!1)},onSubmit:je,reference:ee})]}):null},Be=({amount:r,description:i,id:t,token:n,callback_url:u,mode:a="LIVE",customId:p,fields_to_hide:o,callback:m,currency:f="XOF",case:A,callback_info:x,error_callback_url:_,custom_button:g=!1,buttonText:T=`Payer ${r} ${f}`,buttonClass:w})=>{const[y,v]=c.useState(!1),{setPaymentConfig:h}=fe(),F=c.useRef(null),[R,D]=c.useState(!1),[M,X]=c.useState(null);c.useEffect(()=>{(async()=>{try{await he(t),D(!0)}catch{X("Veuillez vérifier vos identifiants de boutique (ID et token) et rester en mode LIVE.")}})()},[t]);const L=c.useCallback(()=>{h({amount:r,description:i,id:t,token:n,callback_url:u,mode:a,customId:p,fields_to_hide:o,callback:m,currency:f,case:A,callback_info:x,error_callback_url:_}),v(!0)},[r,i,t,n,u,a,p,o,m,f,A,x,_,h]);c.useEffect(()=>{const P=F.current;if(!P)return;const z=()=>{L()};return P.addEventListener("feexpay:trigger",z),()=>{P.removeEventListener("feexpay:trigger",z)}},[L]);const U=()=>{v(!1)};return e.jsxs("div",{ref:F,children:[M?e.jsx("p",{className:"text-red-600 text-sm mb-2",children:M}):R&&!g&&e.jsx("button",{onClick:L,className:w||"bg-primary-orange hover:bg-orange-700 text-white font-bold py-3 px-4 rounded-md transition-colors duration-300 flex items-center justify-center",children:T}),y&&e.jsx(De,{isOpen:y,onClose:U})]})};exports.FeexPayButton=Be;exports.FeexPayProvider=Te;