UNPKG

vexor

Version:

A single SDK to integrate Stripe, Paypal, Mercadopago, Talo, Square and more with the same code. Vexor makes integrations painless: simplify checkouts, subscriptions, marketplaces, connect accounts, webhooks and more. Integrate payment gateways in minutes

20 lines (16 loc) 60.8 kB
'use strict'; var uuid = require('uuid'); var xe = require('stripe'); var pr = require('crypto'); var lr = require('https'); var fr = require('buffer-crc32'); var mercadopago = require('mercadopago'); function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } var xe__default = /*#__PURE__*/_interopDefault(xe); var pr__default = /*#__PURE__*/_interopDefault(pr); var lr__default = /*#__PURE__*/_interopDefault(lr); var fr__default = /*#__PURE__*/_interopDefault(fr); var d={MERCADO_PAGO:{name:"mercadopago",base_url:{production:"https://api.mercadopago.com",sandbox:"https://api.mercadopago.com"},connect_auth_url:"https://auth.mercadopago.com"},STRIPE:{name:"stripe",base_url:{production:"https://www.stripe.com",sandbox:"https://sandbox.stripe.com"}},PAYPAL:{name:"paypal",base_url:{production:"https://api-m.paypal.com",sandbox:"https://api-m.sandbox.paypal.com"}},TALO:{name:"talo",base_url:{production:"https://api.talo.com.ar",sandbox:"https://sandbox-api.talo.com.ar"}},SQUARE:{name:"square",base_url:{production:"https://connect.squareup.com",sandbox:"https://connect.squareupsandbox.com"}}};var er=async(r,e)=>{var o,n,t,a,s,p,c,i;try{let l=(n=(o=r.openSource)==null?void 0:o.platforms)==null?void 0:n.mercadopago;if(!l)throw new Error("MercadoPago credentials not found");let u=l.access_token;if(!u)throw new Error("MercadoPago access token not found");let f=(s=(a=(t=r.openSource)==null?void 0:t.platforms)==null?void 0:a.mercadopago)==null?void 0:s.sandbox,y=e.items.map(h=>({...h,id:h.id||uuid.v4()})),m=uuid.v4(),g={items:y,binary_mode:!0,metadata:{identifier:m},external_reference:m,back_urls:{success:((p=e.options)==null?void 0:p.successRedirect)||"http://localhost:3000",pending:((c=e.options)==null?void 0:c.pendingRedirect)||"http://localhost:3000",failure:((i=e.options)==null?void 0:i.failureRedirect)||"http://localhost:3000"}},S=f?d.MERCADO_PAGO.base_url.sandbox:d.MERCADO_PAGO.base_url.production,w=await(await fetch(`${S}/checkout/preferences`,{method:"POST",body:JSON.stringify(g),headers:{"Content-Type":"application/json",Authorization:`Bearer ${u}`}})).json();return {message:"Mercadopago checkout created",payment_url:w.init_point,raw:w,identifier:m}}catch(l){throw console.error("Error creating MercadoPago checkout",l),l}},K=er;var or=async(r,e)=>{var n,t,a,s,p;let o=uuid.v4();try{let c=(t=(n=r.openSource)==null?void 0:n.platforms)==null?void 0:t.stripe;if(!c)throw new Error("Stripe credentials not found");let i=c.secret_key;if(!i)throw new Error("Stripe secret key not found");let l=new xe__default.default(i),u=e.items.map(m=>{var g;return {price_data:{currency:((g=e.options)==null?void 0:g.currency)||"usd",product_data:{name:m.title},unit_amount:Math.round(m.unit_price*100)},quantity:m.quantity}}),f={payment_method_types:["card"],line_items:u,mode:"payment",metadata:{identifier:o},payment_intent_data:{metadata:{identifier:o}},allow_promotion_codes:((a=e.options)==null?void 0:a.allow_promotion_codes)??!1,success_url:((s=e.options)==null?void 0:s.successRedirect)||"http://localhost:3000/success",cancel_url:((p=e.options)==null?void 0:p.failureRedirect)||"http://localhost:3000/failure"},y=await l.checkout.sessions.create(f);return {message:"Payment checkout created",payment_url:y.url,raw:{...y},identifier:o}}catch(c){throw console.error("Error creating Stripe checkout",c),c}},G=or;var C=async(r,e,o)=>{try{let n=Buffer.from(`${r}:${e}`).toString("base64");return (await(await fetch(`${o}/v1/oauth2/token`,{method:"POST",body:"grant_type=client_credentials",headers:{Authorization:`Basic ${n}`}})).json()).access_token}catch(n){throw console.error("Failed to generate Access Token:",n),n}};var nr=async(r,e)=>{var o,n,t,a,s,p;try{let c=(n=(o=r.openSource)==null?void 0:o.platforms)==null?void 0:n.paypal;if(!c)throw new Error("Paypal credentials not found");let i=c.secret_key;if(!i)throw new Error("Paypal secret key not found");let l=c.client_id;if(!l)throw new Error("Paypal client id not found");let f=(c==null?void 0:c.sandbox)===!0?d.PAYPAL.base_url.sandbox:d.PAYPAL.base_url.production,y=await C(l,i,f),m=`${f}/v2/checkout/orders`,g=e.items.map(_=>{var b;return {name:_.title,unit_amount:{currency_code:((b=e.options)==null?void 0:b.currency)||"USD",value:_.unit_price.toFixed(2)},quantity:_.quantity.toString(),description:_.description||`${_.title} - ${_.quantity} unit(s)`}}),S=g.reduce((_,b)=>_+parseFloat(b.unit_amount.value)*parseInt(b.quantity),0),x={intent:"CAPTURE",purchase_units:[{amount:{currency_code:((t=e.options)==null?void 0:t.currency)||"USD",value:S.toFixed(2),breakdown:{item_total:{currency_code:((a=e.options)==null?void 0:a.currency)||"USD",value:S.toFixed(2)}}},items:g}],application_context:{return_url:((s=e.options)==null?void 0:s.successRedirect)||"http://localhost:3000",cancel_url:((p=e.options)==null?void 0:p.failureRedirect)||"http://localhost:3000"}},w=await fetch(m,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${y}`},body:JSON.stringify(x)}),h=await w.json();return w.ok?{message:"Paypal checkout created successfully",payment_url:h.links.find(b=>b.rel==="approve").href,raw:h,identifier:h.id}:(console.error("PayPal API Error:",{status:w.status,statusText:w.statusText,body:h,requestPayload:x}),{payment_url:"",message:h.message||"Failed to create PayPal order. Make sure that you are using the correct credentials for the environment. If your project is sandbox, make sure that you are using sandbox credentials. The identifier in this error is the paypal-debug-id",raw:h.details||[],identifier:w.headers.get("paypal-debug-id")})}catch(c){throw console.error("Error creating Paypal checkout",c),c}},Y=nr;var q=async({user_id:r,client_id:e,client_secret:o,url:n})=>await fetch(`${n}/users/${r}/tokens`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:e,client_secret:o})}).then(a=>a.json());var ar=async(r,e)=>{var o,n,t,a,s,p;try{let c=(n=(o=r.openSource)==null?void 0:o.platforms)==null?void 0:n.talo;if(!c)throw new Error("Talo credentials not found");let i=c.user_id,l=c.client_id,u=c.client_secret;if(!i||!l||!u)throw new Error("Talo credentials not found");let f=(c==null?void 0:c.sandbox)===!0,y=f?"sandbox":"production",m=f?d.TALO.base_url.sandbox:d.TALO.base_url.production,g=await q({user_id:i,client_id:l,client_secret:u,url:m});if(!((t=g.data)!=null&&t.token))return {raw:"talo_token_error",message:"Error getting Talo token.",payment_url:"null",identifier:"null"};let S=g.data.token,x=e.items.map(k=>({...k,id:k.id||uuid.v4()})),w=uuid.v4(),h=x.reduce((k,V)=>k+V.unit_price*V.quantity,0),_=x.map(k=>`${k.title} x${k.quantity}`).join(", "),b={price:{currency:((a=e.options)==null?void 0:a.currency)||"ARS",amount:Number(h)},user_id:i,redirect_url:((s=e.options)==null?void 0:s.successRedirect)||"http://localhost:3000/success",motive:_,external_id:w||uuid.v4(),webhook_url:"",payment_options:((p=e.options)==null?void 0:p.paymentMethods)||["crypto"]};c.webhooks_url&&(b.webhook_url=`${c.webhooks_url}?source_news=webhooks&mode=${y}&vexorPlatform=talo`);let P=await fetch(`${m}/payments/`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${S}`},body:JSON.stringify(b)}).then(k=>k.json());return P.code!==200?{message:"talo_payment_error",raw:P,payment_url:"null",identifier:"null"}:{message:"Talo checkout created",payment_url:P.data.payment_url,raw:P,identifier:w}}catch(c){throw console.error("Error creating Talo checkout",c),c}},J=ar;var B=()=>"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){var e=Math.random()*16|0,o=r==="x"?e:e&3|8;return o.toString(16)});var pe=async({url:r,accessToken:e})=>{try{let o=await fetch(`${r}/v2/locations`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`}});if(!(o!=null&&o.ok))throw new Error(`HTTP error! status: ${o.status} Make sure the request is made from the server not from the client side`);return await o.json()}catch(o){throw console.error("Error fetching Square location:",o),o}};var ir=async(r,e)=>{var o,n,t,a;try{let s=(n=(o=r.openSource)==null?void 0:o.platforms)==null?void 0:n.square;if(!s)throw new Error("Square credentials not found");let p=s.access_token;if(!p)throw new Error("Square access token not found");let c=(s==null?void 0:s.sandbox)===!0,i=c?d.SQUARE.base_url.sandbox:d.SQUARE.base_url.production,l=c?"sandbox":"production",u=await pe({url:i,accessToken:p});if(!((t=u.locations)!=null&&t.length))return {raw:u,identifier:"Square_token_error",message:"Error getting Square token.",payment_url:""};let f=u.locations[0].id,y=e.items.map(h=>({...h,id:h.id||uuid.v4()})),m=y.reduce((h,_)=>h+_.unit_price*_.quantity,0),g=y.map(h=>`${h.title} x${h.quantity}`).join(", "),S={idempotency_key:B(),quick_pay:{name:g,price_money:{amount:Number(m*100),currency:((a=e.options)==null?void 0:a.currency)||"USD"},location_id:f},webhook_url:""};s.webhooks_url&&(S.webhook_url=`${s.webhooks_url}?source_news=webhooks&mode=${l}&vexorPlatform=Square`);let x=await fetch(`${i}/v2/online-checkout/payment-links`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`},mode:"no-cors",body:JSON.stringify(S)}).then(h=>h.json()),w=x.related_resources.orders[0].id;return {message:"Payment checkout created",payment_url:x.payment_link.url,raw:x,identifier:w}}catch(s){throw console.error("Error creating Square checkout",s),s}},H=ir;var cr=r=>{var e;return Object.keys(((e=r.openSource)==null?void 0:e.platforms)||{}).length>0},E={isOpenSource:cr};var de=r=>Object.assign(e=>r.createCheckout(e.platform,e),{mercadopago:e=>r.createCheckout("mercadopago",e),stripe:e=>r.createCheckout("stripe",e),paypal:e=>r.createCheckout("paypal",e),talo:e=>r.createCheckout("talo",e),square:e=>r.createCheckout("square",e)});async function ue(r,e,o){if(E.isOpenSource(r)){let t;switch(e){case d.MERCADO_PAGO.name:t=await K(r,o);break;case d.STRIPE.name:t=await G(r,o);break;case d.PAYPAL.name:t=await Y(r,o);break;case d.TALO.name:t=await J(r,o);break;case d.SQUARE.name:t=await H(r,o);break;default:throw new Error(`Unsupported platform: ${e}`)}return t}else {let t=await fetch(`${r.apiUrl}/payments`,{method:"POST",headers:{"Content-Type":"application/json","x-vexor-key":r.publishableKey,"x-vexor-platform":e,"x-vexor-project-id":r.projectId},body:JSON.stringify(o)}),a=await t.json();if(!t.ok){let s=a.message||"An unknown error occurred";throw new Error(`Payment request failed: ${s}`)}return a}}var le=async(r,e)=>{var o,n;try{let t=(n=(o=e.openSource)==null?void 0:o.platforms)==null?void 0:n.mercadopago;if(!t)throw new Error("MercadoPago credentials not found");let a=t.sandbox?d.MERCADO_PAGO.base_url.sandbox:d.MERCADO_PAGO.base_url.production,s=await fetch(`${a}/preapproval_plan/search?q=${r}&sort=date_created&criteria=desc&limit=1`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.access_token}`}}),p=await s.json();if(!s.ok)throw new Error("Failed to retrieve MercadoPago data");return p.results[0]}catch(t){throw console.error("Error retrieving MercadoPago preapproval plan",t),t}};var $=async(r,e)=>{try{let t=(await le(r,e)).external_reference.split(";").filter(Boolean).reduce((a,s)=>{let[p,c]=s.split(":");return a[p.toLowerCase()]=c,a},{});return {access_token:t.access_token,public_key:t.public_key,refresh_token:t.refresh_token}}catch(o){throw console.error("Error getting MercadoPago connected account credentials",o),o}};var me=({x_signature:r,mercadopagoWebhookSecret:e,data_id:o,x_request_id:n})=>{var i,l,u,f,y,m;let t=(u=(l=(i=r==null?void 0:r.split(","))==null?void 0:i[0])==null?void 0:l.split("="))==null?void 0:u[1],a=(m=(y=(f=r==null?void 0:r.split(","))==null?void 0:f[1])==null?void 0:y.split("="))==null?void 0:m[1],s=`id:${o};request-id:${n};ts:${t};`,p=!1;return pr__default.default.createHmac("sha256",e).update(s).digest("hex")===a&&(p=!0),p};var X=async(r,e)=>{var l,u,f,y,m,g,S,x,w;let o=new URL(e.url),n=new URLSearchParams(o.searchParams),t=n.get("data.id"),a=n.get("mode"),s=n.get("seller"),p=e.headers.get("x-signature"),c=e.headers.get("x-request-id"),i=await e.json();try{let h=(u=(l=r.openSource)==null?void 0:l.platforms)==null?void 0:u.mercadopago;if(!h)throw new Error("MercadoPago credentials not found");let _=h.access_token,b=h.webhook_secret;if(!_)throw new Error("MercadoPago access token not found");if(!b)throw new Error("MercadoPago webhook secret not found");let P=(h==null?void 0:h.sandbox)===!0,k=P?d.MERCADO_PAGO.base_url.sandbox:d.MERCADO_PAGO.base_url.production;if(!P&&(!p||!c||!t))return console.log("Invalid request. The request does not contain the required headers."),{message:"Invalid request. The request does not contain the required headers.",status:"error",transmissionId:c||"",identifier:"",timeStamp:new Date().toISOString(),orderId:"",eventType:"",platform:d.MERCADO_PAGO.name,resource:null};if((i.live_mode||!P)&&!me({x_signature:p,mercadopagoWebhookSecret:b,data_id:t,x_request_id:c}))throw new Error("Invalid signature");let V;switch(i.entity){case"preapproval_plan":V=`https://api.mercadopago.com/preapproval_plan/${i.data.id}`;break;case"preapproval":V=`https://api.mercadopago.com/preapproval/${i.data.id}`;break;default:V=`https://api.mercadopago.com/v1/payments/${i.data.id}`;break}let v=await $(s,r);if(!v.access_token)throw new Error("Seller credentials not found");let R=await(await fetch(V,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${a==="connect"?v.access_token:_}`}})).json(),T="",A="Event processed",I="pending";switch(i.action.trim()){case"payment.created":{A="Payment created with mercadopago transaction id: "+i.data.id,T=((f=R.metadata)==null?void 0:f.identifier)||R.external_reference||"",R.status==="approved"&&(I="paid");break}case"payment.updated":A="Payment updated with mercadopago transaction id: "+i.data.id,R.status&&(I=R.status),T=((y=R.metadata)==null?void 0:y.identifier)||R.external_reference||"";break;case"created":if(A="Subscription preapproval created with mercadopago transaction id: "+i.data.id,T=((m=R.metadata)==null?void 0:m.identifier)||R.external_reference||"",R.status&&(I=R.status),i.entity!=="preapproval_plan"&&i.entity!=="preapproval")if(i.entity==="authorized_payment"){let O=await(await fetch(`https://api.mercadopago.com/authorized_payments/${i.data.id}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${_}`}})).json();A=`Subscription payment authorization created with ID: ${i.data.id}. Debit date: ${new Date(O.debit_date).toLocaleDateString()}`,T=((g=O.metadata)==null?void 0:g.identifier)||O.external_reference||"",R=O,I=O.status;}else {let O=await(await fetch(`https://api.mercadopago.com/v1/payments/${i.data.id}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${_}`}})).json();O.status===404&&(I="pending",A="Subscription preapproval created with mercadopago transaction id: "+i.data.id+" but the subscription was not found in Mercadopago. This may occur if the user has not paid yet, even though, mercadopago emits an update. \u26A0\uFE0F THIS RESPONSE WILL NOT CONTAIN ANY IDENTIFIER."),T=((S=O.metadata)==null?void 0:S.identifier)||O.external_reference||"",R=O;}break;case"updated":A="Subscription updated with mercadopago transaction id: "+i.data.id,R.status&&(I=R.status),T=((x=R.metadata)==null?void 0:x.identifier)||R.external_reference||"",R.status===404&&(I="pending",A="Subscription update received with mercadopago transaction id: "+i.data.id+" but the subscription was not found in Mercadopago. This may occur if the user has not paid yet, even though, mercadopago emits an update. \u26A0\uFE0F THIS RESPONSE WILL NOT CONTAIN ANY IDENTIFIER."),R.status==="authorized"&&R.next_payment_date>new Date&&(I=R.status),T=((w=R.metadata)==null?void 0:w.identifier)||R.external_reference||"";break;default:{console.error("Unhandled event type:",i.action),A="Mercadopago events supported: payment.created, created, updated, payment.updated";break}}return {message:A,status:I,transmissionId:c||"",identifier:T,timeStamp:new Date().toISOString(),orderId:i.data.id,eventType:i.action,platform:d.MERCADO_PAGO.name,resource:R}}catch(h){return console.error(h),{message:"Error processing MercadoPago webhook",status:"error",transmissionId:c||"",identifier:"",timeStamp:new Date().toISOString(),orderId:"",eventType:"",platform:d.MERCADO_PAGO.name,resource:null}}};async function ur(r,e,o=10){var n;for(let t=0;t<o;t++){if(console.log("Awaiting Stripe confirmation..."),!e){await new Promise(s=>setTimeout(s,1e3*(t+1)));continue}let a=await r.subscriptions.retrieve(e);if((n=a.metadata)!=null&&n.identifier)return a;await new Promise(s=>setTimeout(s,1e3*(t+1)));}throw new Error("Subscription metadata not available after retries")}var Q=async(r,e)=>{var a,s,p,c;let o=await e.text(),n=JSON.parse(o),t=e.headers.get("Stripe-Signature");if(!t)return {message:"Missing signature",status:"error",transmissionId:"",identifier:"",timeStamp:new Date().toISOString(),orderId:"",eventType:"",platform:d.STRIPE.name,resource:null};try{let i=(s=(a=r.openSource)==null?void 0:a.platforms)==null?void 0:s.stripe,l=i==null?void 0:i.public_key,u=i==null?void 0:i.secret_key,f=i==null?void 0:i.webhook_secrets;if(!l)throw new Error("Stripe public key not found");if(!u)throw new Error("Stripe secret key not found");if(!(f!=null&&f.length))throw new Error("Stripe webhook secrets not found");let m=(i==null?void 0:i.sandbox)===!0?d.STRIPE.base_url.sandbox:d.STRIPE.base_url.production,g=null,S=new xe__default.default(u,{typescript:!0});for(let b of f)try{g=S.webhooks.constructEvent(o,t,b);break}catch{console.log("Webhook signature verification failed with a secret, trying next one if available");continue}if(!g)return console.error("Webhook signature verification failed with all secrets"),{message:"Webhook signature verification failed",status:"error",transmissionId:"",identifier:"",timeStamp:new Date().toISOString(),orderId:"",eventType:"",platform:d.STRIPE.name,resource:null};let x=n.data.object.billing_reason==="subscription_create"||n.data.object.mode==="subscription",w="Event processed",h="pending",_="";switch(g.type){case"checkout.session.completed":if(w="Payment created with order id: "+n.data.object.metadata.identifier,h=n.data.object.payment_status,_=n.data.object.metadata.identifier,x){let b=n.data.object.subscription,P=await S.subscriptions.update(b,{metadata:{identifier:n.data.object.metadata.identifier}});w="Subscription created and updated with identifier: "+n.data.object.metadata.identifier,_=n.data.object.metadata.identifier;}break;case"invoice.payment_succeeded":if(_=n.data.object.metadata.identifier,w="Payment succeeded with invoice id: "+n.data.object.metadata.identifier,h=n.data.object.payment_status||n.data.object.status,x){let b=n.data.object.subscription||((c=(p=n.data.object.parent)==null?void 0:p.subscription_details)==null?void 0:c.subscription);try{let P=await ur(S,b);w="Subscription payment succeeded and updated with id: "+P.metadata.identifier,n.data.object.metadata.identifier=P.metadata.identifier,_=P.metadata.identifier;}catch(P){console.error("Failed to get subscription metadata:",P),h="pending",w="Subscription payment processed, but metadata not yet available";}}break;case"account.updated":h="success",w="Account updated with id: "+n.data.object.metadata.identifier,_=n.data.object.metadata.identifier;break;default:return console.error("Unhandled event type:",g.type),{message:`Stripe events supported: checkout.session.completed, invoice.payment_succeeded. Using vexor.webhook() with unsupported events may result in unnecessary operations charges. Please ensure you only use supported events to optimize your usage.`,status:"error",transmissionId:"",identifier:"",timeStamp:new Date().toISOString(),orderId:"",eventType:"",platform:d.STRIPE.name,resource:null}}return {message:w,status:h,transmissionId:n.data.object.id,identifier:_,timeStamp:new Date().toISOString(),orderId:n.data.object.payment_intent||n.data.object.id,eventType:g.type,platform:d.STRIPE.name,resource:n.data.object}}catch(i){throw console.error(i),i;}};function fe(r){switch(r.toUpperCase()){case"SHA256WITHRSA":return "RSA-SHA256";case"SHA1WITHRSA":return "RSA-SHA1";default:throw new Error(`Unsupported authentication algorithm: ${r}`)}}async function ye(r){return new Promise((e,o)=>{lr__default.default.get(r,n=>{let t="";n.on("data",a=>{t+=a;}),n.on("end",()=>{e(t);});}).on("error",n=>{o(n);});})}async function he(r,e,o,n){try{let t=await ye(o),a=fe(n),s=pr__default.default.createVerify(a);s.update(r);let p=Buffer.from(e,"base64");return s.verify(t,p)}catch(t){return console.error("Error verifying signature:",t),!1}}var we=async(r,e)=>{var o,n,t,a,s,p,c,i,l;try{let u=(t=(n=(o=r.openSource)==null?void 0:o.platforms)==null?void 0:n.paypal)==null?void 0:t.secret_key;if(!u)throw new Error("Paypal secret key not found");let f=(p=(s=(a=r.openSource)==null?void 0:a.platforms)==null?void 0:s.paypal)==null?void 0:p.client_id;if(!f)throw new Error("Paypal client id not found");let m=((l=(i=(c=r.openSource)==null?void 0:c.platforms)==null?void 0:i.paypal)==null?void 0:l.sandbox)===!0?d.PAYPAL.base_url.sandbox:d.PAYPAL.base_url.production,g=await C(f,u,m);return await fetch(`${m}/v2/checkout/orders/${e}/capture`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${g}`}})}catch(u){throw console.error("Error capturing paypal payment:",u),new Error("Error capturing paypal payment")}};var Z=async(r,e)=>{var l,u,f,y;let o=await e.text(),n=e.headers,t=n.get("paypal-transmission-id"),a=n.get("paypal-transmission-time"),s=n.get("paypal-cert-url"),p=n.get("paypal-auth-algo"),c=n.get("paypal-transmission-sig"),i=parseInt("0x"+fr__default.default(Buffer.from(o)).toString("hex"));try{let m=JSON.parse(o),g=(u=(l=r.openSource)==null?void 0:l.platforms)==null?void 0:u.paypal;if(!g)throw new Error("Paypal credentials not found");let S=g.secret_key,x=g.webhook_id;if(!S)throw new Error("Paypal secret key not found");if(!x)throw new Error("Paypal webhook id not found");let w;switch(m.event_type){case"CHECKOUT.ORDER.APPROVED":w=m.resource.id;break;case"PAYMENT.CAPTURE.COMPLETED":w=(y=(f=m.resource.supplementary_data)==null?void 0:f.related_ids)==null?void 0:y.order_id;break;case"BILLING.SUBSCRIPTION.ACTIVATED":w=m.resource.id;break;case"BILLING.SUBSCRIPTION.REACTIVATED":w=m.resource.id;break;case"PAYMENT.SALE.COMPLETED":w=m.resource.billing_agreement_id;break;default:return console.error("Unhandled event type:",m.event_type),{message:"Unhandled event type: "+m.event_type,status:"error",platform:d.PAYPAL.name,resource:null,eventType:m.event_type,transmissionId:t||"",identifier:"",timeStamp:new Date().toISOString(),orderId:""}}let h=`${t}|${a}|${x}|${i}`;if(!await he(h,c,s,p))throw new Error("Invalid signature");let b="pending",P="Event processed";switch(m.event_type){case"CHECKOUT.ORDER.APPROVED":let v=await(await we(r,m.resource.id)).json();v.error?P="Error capturing payment: "+v.error:P="Payment approved with order id: "+w;break;case"PAYMENT.CAPTURE.COMPLETED":P="Payment captured with order id: "+w,b="paid";break;case"BILLING.SUBSCRIPTION.ACTIVATED":P="Subscription activated with id: "+w,b="active";break;case"PAYMENT.SALE.COMPLETED":P="Subscription payment completed with id: "+w,b="paid";break;case"BILLING.SUBSCRIPTION.REACTIVATED":P="Subscription reactivated with id: "+w,b="active";break;case"PAYMENT.CAPTURE.REFUNDED":P="Payment captured refunded with id: "+w,b="refunded";break;default:P="Unhandled event type: "+m.event_type;}return {message:P,status:b,platform:d.PAYPAL.name,identifier:w,transmissionId:t,timeStamp:a,orderId:w,eventType:m.event_type,resource:m.resource}}catch(m){return console.error(m),{message:"Error processing Paypal webhook",status:"error",transmissionId:t||"",identifier:"",timeStamp:new Date().toISOString(),orderId:"",eventType:"",platform:d.PAYPAL.name,resource:"null"}}};var Pe=async(r,e)=>{var i,l,u;let o=(l=(i=r.openSource)==null?void 0:i.platforms)==null?void 0:l.talo;if(!o)throw new Error("Talo credentials not found");let n=(o==null?void 0:o.sandbox)===!0,a=n?d.TALO.base_url.sandbox:d.TALO.base_url.production,s=await q({user_id:o.user_id,client_id:o.client_id,client_secret:o.client_secret,url:a});if(!((u=s.data)!=null&&u.token))throw new Error("Talo token not found");let p=s.data.token;return await fetch(`${a}/payments/${e}`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`}}).then(f=>f.json())};var ee=async(r,e)=>{var o,n,t;try{let a=await e.text(),s=JSON.parse(a),p=(n=(o=r.openSource)==null?void 0:o.platforms)==null?void 0:n.talo;if(!p)throw new Error("Talo credentials not found");let c=p.user_id,i=p.client_id,l=p.client_secret;if(!c||!i||!l)throw new Error("Talo credentials are incomplete");let u=await Pe(r,((t=s.data)==null?void 0:t.id)||s.paymentId),f=u.data.status;return (f==="SUCCESS"||f==="OVERPAID")&&(f="paid"),{message:s.message,status:f,platform:d.TALO.name,identifier:u.data.external_id,transmissionId:s.paymentId,timeStamp:new Date().toISOString(),orderId:u.data.id,eventType:s.message,resource:u}}catch(a){throw console.log("Talo webhook error:",a),a}};var ge=({request:r,webhooks_url:e,webhook_signature_key:o,signature:n})=>{try{let t=Buffer.from(e+r,"utf-8"),a=Buffer.from(o,"utf-8"),s=pr__default.default.createHmac("sha256",a);return s.update(t),s.digest("base64")===n}catch(t){return console.error("Error verifying Square signature:",t),!1}};var re=async(r,e)=>{var t,a;let o=await e.text(),n=e.headers.get("x-square-hmacsha256-signature");try{let s=JSON.parse(o),p=(a=(t=r.openSource)==null?void 0:t.platforms)==null?void 0:a.square;if(!p)throw new Error("Paypal credentials not found");let c=p.access_token,i=p.application_id,l=p.webhooks_url,u=p.webhook_signature_key;if(!c)throw new Error("Square access token not found");if(!i)throw new Error("Square application id not found");if(!l)throw new Error("Square webhooks url not found");if(!u)throw new Error("Square webhook signature key not found");if(!ge({request:o,signature:n,webhook_signature_key:u,webhooks_url:l}))throw new Error("Invalid signature");let y="",m="";switch(s.type){case"payment.updated":y=s.data.object.payment.order_id,m=s.data.object.payment.status;break;case"order.updated":y=s.data.object.order_updated.order_id,m=s.data.object.order_updated.state;break;default:return console.error("Unhandled event type:",s.type),{message:"Unhandled event type: "+s.type,status:"unhandled_event_type",platform:d.SQUARE.name,identifier:"",transmissionId:"",timeStamp:new Date().toISOString(),orderId:"",eventType:"",resource:"null"}}return {message:"Event processed",status:m,platform:d.SQUARE.name,identifier:y,transmissionId:s.data.id,timeStamp:new Date().toISOString(),orderId:y,eventType:s.type,resource:s.data}}catch(s){return console.error(s),{message:"Error processing Square webhook",status:"error",transmissionId:"",identifier:"",timeStamp:new Date().toISOString(),orderId:"",eventType:"",platform:d.SQUARE.name,resource:""}}};var Se=r=>Object.assign(e=>r.handleWebhook(e),{mercadopago:e=>r.handleWebhook(e),stripe:e=>r.handleWebhook(e),paypal:e=>r.handleWebhook(e),talo:e=>r.handleWebhook(e),square:e=>r.handleWebhook(e)});async function _e(r,e){var p;let o=e.headers,n=new URL(e.url),t=new URLSearchParams(n.searchParams),a;if(o.get("paypal-transmission-id")?a="paypal":o.get("stripe-signature")?a="stripe":(p=o.get("referer"))!=null&&p.includes("mercadopago")?a="mercadopago":t.get("vexorPlatform")==="talo"?a="talo":o.get("x-square-hmacsha256-signature")&&(a="square"),!a)throw new Error("Unsupported payment platform or missing signature header");if(E.isOpenSource(r)){let c;switch(a){case d.MERCADO_PAGO.name:c=await X(r,e);break;case d.STRIPE.name:c=await Q(r,e);break;case d.PAYPAL.name:c=await Z(r,e);break;case d.TALO.name:c=await ee(r,e);break;case d.SQUARE.name:c=await re(r,e);break;default:throw new Error(`Unsupported platform: ${a}`)}return c}else {let c=await e.text();if(!r.secretKey)throw new Error("Missing VEXOR_SECRET_KEY environment variable");let i=new Request(`${r.apiUrl}/webhooks/${a}?${t.toString()}`,{method:e.method,headers:new Headers(o),body:c});return i.headers.set("x-vexor-key",r.secretKey),i.headers.set("x-vexor-platform",a),i.headers.set("x-vexor-project-id",r.projectId),await(await fetch(i)).json()}}var j=(r,e)=>{if(e==="mercadopago")switch(r){case"month":return "months";case"day":return "days";default:return r}if(e==="paypal")switch(r){case"day":return "DAY";case"week":return "WEEK";case"month":return "MONTH";case"year":return "YEAR";default:return r}return r};var gr=async(r,e)=>{var o,n;try{let t=(n=(o=r.openSource)==null?void 0:o.platforms)==null?void 0:n.mercadopago;if(!t)throw new Error("MercadoPago credentials not found");let a=t.access_token;if(!a)throw new Error("MercadoPago access token not found");let s=j(e.interval,d.MERCADO_PAGO.name),p=new mercadopago.MercadoPagoConfig({accessToken:a}),c=new mercadopago.PreApprovalPlan(p),i=uuid.v4(),l={reason:e.name,auto_recurring:{frequency:1,frequency_type:s,transaction_amount:e.price,currency_id:e.currency},payment_methods_allowed:{payment_types:[{id:"credit_card"}],payment_methods:[{id:"credit_card"}]},back_url:e.successRedirect,external_reference:i,status:"active"},u=await c.create({body:l});return {message:"Mercadopago subscription created",payment_url:u.init_point,raw:u,identifier:i}}catch(t){throw console.error("Error creating MercadoPago subscription",t),t}},te=gr;var Sr=async(r,e)=>{var o,n,t,a,s,p,c;try{let i=(n=(o=r.openSource)==null?void 0:o.platforms)==null?void 0:n.paypal;if(!i)throw new Error("Paypal credentials not found");let l=i.secret_key;if(!l)throw new Error("Paypal secret key not found");let u=i.client_id;if(!u)throw new Error("Paypal client id not found");let y=(i==null?void 0:i.sandbox)===!0?d.PAYPAL.base_url.sandbox:d.PAYPAL.base_url.production,m=await C(u,l,y),g=`${y}/v1/catalogs/products`,S={name:e.name,description:e.description,type:"SERVICE",category:"SOFTWARE"},x=await fetch(g,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${m}`},body:JSON.stringify(S)});if(!x.ok)throw new Error(`Failed to create product: ${x.statusText}`);let w=await x.json(),h=j(e.interval,d.PAYPAL.name),_=`${y}/v1/billing/plans`,b={product_id:w.id,name:e.name,description:e.description,billing_cycles:[{frequency:{interval_unit:h,interval_count:1},tenure_type:"REGULAR",sequence:1,total_cycles:0,pricing_scheme:{fixed_price:{value:e.price.toString(),currency_code:e.currency}}}],payment_preferences:{auto_bill_outstanding:!0,setup_fee:{value:"0",currency_code:e.currency},setup_fee_failure_action:"CONTINUE",payment_failure_threshold:3},taxes:{percentage:"0",inclusive:!1}},P=await fetch(_,{method:"POST",headers:{Authorization:`Bearer ${m}`,"PayPal-Request-Id":b.product_id,Accept:"application/json","Content-Type":"application/json",Prefer:"return=representation"},body:JSON.stringify(b)});if(!P.ok){let A=(await P.json()).details;throw new Error(`Failed to create plan: ${JSON.stringify(A)}`)}let k=await P.json(),V=`${y}/v1/billing/subscriptions`,v={plan_id:k.id,quantity:"1",application_context:{brand_name:e.name,locale:"en-US",shipping_preference:"NO_SHIPPING",user_action:"SUBSCRIBE_NOW",payment_method:{payer_selected:"PAYPAL",payee_preferred:"IMMEDIATE_PAYMENT_REQUIRED"},return_url:e.successRedirect,cancel_url:e.failureRedirect??`${e.successRedirect}?canceled=true`},subscriber:{name:{given_name:((a=(t=e.customer)==null?void 0:t.name)==null?void 0:a.split(" ")[0])??"",surname:((p=(s=e.customer)==null?void 0:s.name)==null?void 0:p.split(" ")[1])??""},email_address:(c=e.customer)==null?void 0:c.email}},M=await fetch(V,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${m}`,Prefer:"return=representation"},body:JSON.stringify(v)});if(!M.ok)throw new Error(`Failed to create subscription: ${M.statusText}`);let R=await M.json();return M.ok?{message:"Paypal subscription created successfully",payment_url:R.links.find(A=>A.rel==="approve").href,raw:R,identifier:R.id}:(console.error("PayPal API Error:",{status:M.status,statusText:M.statusText,body:R,requestPayload:v}),{payment_url:"",message:R.message||"Failed to create PayPal subscription. Make sure that you are using the correct credentials for the environment. If your project is sandbox, make sure that you are using sandbox credentials. The identifier in this error is the paypal-debug-id",raw:R.details||[],identifier:M.headers.get("paypal-debug-id")})}catch(i){throw console.error("Error creating Paypal subscription",i),i}},oe=Sr;var xr=async(r,e)=>{var n,t,a;let o=uuid.v4();try{let s=(t=(n=r.openSource)==null?void 0:n.platforms)==null?void 0:t.stripe;if(!s)throw new Error("Stripe credentials not found");let p=s.secret_key;if(!p)throw new Error("Stripe secret key not found");let c=new xe__default.default(p),i=j(e.interval,d.STRIPE.name),l=await c.checkout.sessions.create({payment_method_types:["card"],mode:"subscription",billing_address_collection:"auto",customer_email:(a=e.customer)==null?void 0:a.email,success_url:e.successRedirect,cancel_url:e.failureRedirect??`${e.successRedirect}?canceled=true`,allow_promotion_codes:e.allow_promotion_codes??!1,line_items:[{price_data:{currency:e.currency,product_data:{name:e.name,description:e.description??void 0},unit_amount:Math.round(e.price*100),recurring:{interval:i}},quantity:1}],...e.free_trial_days&&e.free_trial_days>0?{subscription_data:{trial_period_days:e.free_trial_days}}:{},metadata:{identifier:o}});return {message:"Subscription checkout created",payment_url:l.url,raw:{...l},identifier:o}}catch(s){if(console.error(s),s instanceof xe__default.default.errors.StripeError)return {payment_url:"",raw:JSON.stringify(s),identifier:s.type,message:s.message};throw s}},ne=xr;var be=r=>Object.assign(e=>r.createSubscription(e.platform,e),{mercadopago:e=>r.createSubscription("mercadopago",e),stripe:e=>r.createSubscription("stripe",e),paypal:e=>r.createSubscription("paypal",e)});async function Re(r,e,o){if(E.isOpenSource(r)){let t;switch(e){case d.MERCADO_PAGO.name:t=await te(r,o);break;case d.STRIPE.name:t=await ne(r,o);break;case d.PAYPAL.name:t=await oe(r,o);break;default:throw new Error(`Unsupported platform: ${e}`)}return t}else {let t=await fetch(`${r.apiUrl}/subscriptions`,{method:"POST",headers:{"Content-Type":"application/json","x-vexor-key":r.publishableKey,"x-vexor-platform":e,"x-vexor-project-id":r.projectId},body:JSON.stringify(o)}),a=await t.json();if(!t.ok){let s=a.message||"An unknown error occurred";throw new Error(`Subscription request failed: ${s}`)}return a}}var Rr=r=>new Promise(e=>setTimeout(e,r)),ke=3,kr=1e3,ae=8e3,Er=async(r,e)=>{var t,a;let n=Date.now();for(let s=0;s<ke;s++){console.log("Searching for Stripe operation: ",e);try{if(Date.now()-n>ae)throw new Error("Operation timed out - data may still be processing. Please try again in a few seconds.");let p=(a=(t=r.openSource)==null?void 0:t.platforms)==null?void 0:a.stripe;if(!p)throw new Error("Stripe credentials not found");let c=p.secret_key;if(!c)throw new Error("Stripe secret key not found");let i=new xe__default.default(c);try{return {message:"Stripe payment intent retrieved",raw:await i.paymentIntents.retrieve(e),identifier:e,type:"payment"}}catch{try{return {message:"Stripe subscription retrieved",raw:await i.subscriptions.retrieve(e),identifier:e,type:"subscription"}}catch{try{return {message:"Stripe invoice retrieved",raw:await i.invoices.retrieve(e),identifier:e,type:"invoice"}}catch{try{return {message:"Stripe charge retrieved",raw:await i.charges.retrieve(e),identifier:e,type:"charge"}}catch{let[m,g,S,x]=await Promise.all([i.paymentIntents.search({query:`metadata["identifier"]:"${e}"`}),i.subscriptions.search({query:`metadata["identifier"]:"${e}"`}),i.invoices.search({query:`metadata["identifier"]:"${e}"`}),i.charges.search({query:`metadata["identifier"]:"${e}"`})]),w=m.data[0],h=g.data[0],_=S.data[0],b=x.data[0],P=w||h||_||b;if(!P)throw new Error("No Stripe operation found with this identifier");return {message:"Stripe operation retrieved",raw:P,identifier:e,type:w?"payment":h?"subscription":_?"invoice":"charge"}}}}}}catch(p){if(s<ke-1&&Date.now()-n<=ae){let c=Math.min(kr*Math.pow(1.5,s),ae-(Date.now()-n));if(c<=0)throw new Error("Operation timed out - data may still be processing. Please try again in a few seconds.");console.log(`Error on attempt ${s+1}, retrying in ${c}ms...`,p),await Rr(c);continue}throw new Error("Operation not found or still processing. Please try again in a few seconds.")}}throw new Error("Operation not found or still processing. Please try again in a few seconds.")},U=Er;var Vr=async(r,e)=>{var o,n;try{let t=(n=(o=r.openSource)==null?void 0:o.platforms)==null?void 0:n.stripe;if(!t)throw new Error("Stripe credentials not found");let a=t.secret_key;if(!a)throw new Error("Stripe secret key not found");let s=new xe__default.default(a),p=await U(r,e.identifier);if(!p)throw new Error("Stripe operation not found");let c=p.raw.customer,i=await s.billingPortal.sessions.create({customer:c,return_url:e.returnUrl});return {message:"Subscription checkout created",portal_url:i.url,raw:{...i},identifier:e.identifier}}catch(t){if(console.error(t),t instanceof xe__default.default.errors.StripeError)return {portal_url:"",raw:JSON.stringify(t),identifier:e.identifier,message:t.message};throw t}},se=Vr;var Ve=r=>Object.assign(e=>r.createPortal(e.platform,e),{mercadopago:e=>r.createPortal("mercadopago",e),stripe:e=>r.createPortal("stripe",e),paypal:e=>r.createPortal("paypal",e)});async function Ae(r,e,o){if(E.isOpenSource(r)){let t;switch(e){case d.STRIPE.name:t=await se(r,o);break;default:throw new Error(`Unsupported platform: ${e}`)}return t}else {let t=await fetch(`${r.apiUrl}/portals`,{method:"POST",headers:{"Content-Type":"application/json","x-vexor-key":r.publishableKey,"x-vexor-platform":e,"x-vexor-project-id":r.projectId},body:JSON.stringify(o)}),a=await t.json();if(!t.ok){let s=a.message||"An unknown error occurred";throw new Error(`Portal request failed: ${s}`)}return a}}var Ar=async(r,e)=>{var o,n,t,a,s;try{let p=(n=(o=r.openSource)==null?void 0:o.platforms)==null?void 0:n.mercadopago;if(!p)throw new Error("MercadoPago credentials not found");if(!p.access_token)throw new Error("MercadoPago access token not found");let i=p.client_id;if(!i)throw new Error("MercadoPago client id not found");let{redirectUrl:l,countryCode:u}=e,f=(s=(a=(t=r.openSource)==null?void 0:t.platforms)==null?void 0:a.mercadopago)==null?void 0:s.sandbox;if(!u||!["AR","BR","CL","CO","MX","PE","UY"].includes(u))throw new Error("Unsupported country - Mercadopago is not supported in this country. Supported countries: AR (Argentina), BR (Brazil), CL (Chile), CO (Colombia), MX (Mexico), PE (Peru), UY (Uruguay)");let m=f?d.MERCADO_PAGO.base_url.sandbox:d.MERCADO_PAGO.base_url.production,g=B(),S;u?S=`${d.MERCADO_PAGO.connect_auth_url}.${u.toLowerCase()}`:S=d.MERCADO_PAGO.connect_auth_url;let x=`${S}/authorization?client_id=${i}&response_type=code&platform_id=mp&state=${g}&redirect_uri=${l}`;return {message:"MercadoPago connect link generated",connect_url:x,identifier:g.trim(),state:g,raw:x}}catch(p){throw console.error("Error creating MercadoPago connect link",p),p}},Ce=Ar;var Cr=async(r,e)=>{var o,n;try{let t=(n=(o=r.openSource)==null?void 0:o.platforms)==null?void 0:n.mercadopago;if(!t)throw new Error("MercadoPago credentials not found");let a=t.client_id;if(!a)throw new Error("MercadoPago client id not found");let s=t.client_secret;if(!s)throw new Error("MercadoPago client secret not found");let p=t.access_token;if(!p)throw new Error("MercadoPago access token not found");let c=t.sandbox,{url:i}=e,l=i.split("code=")[1],u=i.split("state=")[1],f=i.split("?")[0],y={client_id:a,client_secret:s,grant_type:"authorization_code",redirect_uri:f,code:l,test_token:c},m=c?d.MERCADO_PAGO.base_url.sandbox:d.MERCADO_PAGO.base_url.production,S=await(await fetch(`${m}/oauth/token`,{method:"POST",body:JSON.stringify(y),headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}})).json(),x={items:[{title:"Connected Account Credentials",description:"connected_account_credentials",quantity:1,unit_price:10}],binary_mode:!0},h=await(await fetch(`${m}/checkout/preferences`,{method:"POST",body:JSON.stringify(x),headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`}})).json(),_=h.items[0].currency_id,b={reason:u.trim(),auto_recurring:{frequency:1,frequency_type:"months",repetitions:12,billing_day:10,billing_day_proportional:!1,free_trial:{frequency:1,frequency_type:"months"},transaction_amount:15,currency_id:_},binary_mode:!0,external_reference:`ACCESS_TOKEN:${S.access_token};PUBLIC_KEY:${S.public_key};REFRESH_TOKEN:${S.refresh_token};`,back_url:f},k=await(await fetch(`${m}/preapproval_plan`,{method:"POST",body:JSON.stringify(b),headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`}})).json();if(S.error||k.error||h.error)throw console.error("Failed to connect MercadoPago account",S),new Error("Failed to connect MercadoPago account");return {message:"MercadoPago connected account credentials generated",identifier:u,state:u,raw:S}}catch(t){throw console.error("Error creating MercadoPago connect link",t),t}},Te=Cr;var Ir=async(r,e)=>{var o,n;try{let t=(n=(o=r.openSource)==null?void 0:o.platforms)==null?void 0:n.stripe;if(!t)throw new Error("Stripe credentials not found");let a=t.secret_key;if(!a)throw new Error("Stripe secret key not found");let{redirectUrl:s,countryCode:p,express:c}=e,i=uuid.v4(),l=new xe__default.default(a,{typescript:!0}),u={country:p,controller:{},capabilities:{transfers:{requested:!0},card_payments:{requested:!c}},metadata:{identifier:i}};c?(u.controller={losses:{payments:"application"},fees:{payer:"application"},stripe_dashboard:{type:"express"}},p!=="US"&&(u.tos_acceptance={service_agreement:"recipient"})):u.controller={losses:{payments:"stripe"},fees:{payer:"account"},stripe_dashboard:{type:"full"}};let f=await l.accounts.create(u),y=await l.accountLinks.create({account:f.id,refresh_url:s,return_url:s,type:"account_onboarding"}),m=await l.customers.create({name:`vexor_connect_${f.email}`,email:f.email||"",metadata:{identifier:i,account_id:f.id}});return {message:"Stripe connect link generated",connect_url:y.url,identifier:i,raw:{...y}}}catch(t){throw console.error(t),t}},Oe=Ir;var N=(r,e,o)=>{if(typeof e=="number")return e;if(typeof e=="string"){if(e.endsWith("%"))return parseFloat(e)/100*o;{let n=parseFloat(e);if(!isNaN(n)){if(r==="mercadopago")return n;if(r==="stripe")return n*100}}}throw new Error("Invalid fee format")};var vr=async(r,e)=>{var a,s,p,c,i;let{items:o,options:n,seller:t}=e;if(!o||o.length===0)throw new Error("Items are required.");if(!t||!(t!=null&&t.identifier))throw new Error("Seller identifier is required.");try{let l=(s=(a=r.openSource)==null?void 0:a.platforms)==null?void 0:s.mercadopago;if(!l)throw new Error("MercadoPago credentials not found");if(!l.access_token)throw new Error("MercadoPago access token not found");let f=await $(t.identifier,r);if(!f)throw new Error("MercadoPago seller credentials not found");if(!l.client_id)throw new Error("MercadoPago client id not found");let g=((i=(c=(p=r.openSource)==null?void 0:p.platforms)==null?void 0:c.mercadopago)==null?void 0:i.sandbox)?d.MERCADO_PAGO.base_url.sandbox:d.MERCADO_PAGO.base_url.production,S=e.items.map(k=>({...k,id:k.id||uuid.v4()})),x=uuid.v4(),w=S.reduce((k,V)=>k+V.unit_price*V.quantity,0),h=N("mercadopago",t.fee??0,w),_={items:S,binary_mode:!0,metadata:{identifier:x,seller:t.identifier},external_reference:x,marketplace_fee:h,back_urls:{success:(n==null?void 0:n.successRedirect)||"",pending:(n==null?void 0:n.pendingRedirect)||"",failure:(n==null?void 0:n.failureRedirect)||""},notification_url:""};l.webhooks_url&&(_.notification_url=`${l.webhooks_url}?source_news=webhooks&mode=connect&seller=${t.identifier}`);let P=await(await fetch(`${g}/checkout/preferences`,{method:"POST",body:JSON.stringify(_),headers:{"Content-Type":"application/json",Authorization:`Bearer ${f.access_token}`}})).json();return {message:"MercadoPago connect payment link generated",payment_url:P.init_point,identifier:x,raw:P}}catch(l){throw console.error("Error creating MercadoPago connected account checkout",l),l}},ve=vr;var Mr=async(r,e,o)=>{var n,t;try{let a=(t=(n=r.openSource)==null?void 0:n.platforms)==null?void 0:t.mercadopago;if(!a)throw new Error("MercadoPago credentials not found");let s=a.access_token;if(!s)throw new Error("MercadoPago access token not found");let c=(a==null?void 0:a.sandbox)===!0?d.MERCADO_PAGO.base_url.sandbox:d.MERCADO_PAGO.base_url.production;return {message:"Mercadopago operation retrieved",raw:(await(await fetch(`${c}/v1/payments/search?sort=date_created&criteria=desc&external_reference=${e}&begin_date=NOW-364DAYS&end_date=NOW`,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o?o.access_token:s}`}})).json()).results[0],identifier:e}}catch(a){throw console.error("Error retrieving MercadoPago operation",a),a}},W=Mr;var Br=async(r,e)=>{var t,a;let{identifier:o,seller:n}=e;if(!o)throw new Error("Identifier is required.");if(!n||!(n!=null&&n.identifier))throw new Error("Seller identifier is required.");try{let s=(a=(t=r.openSource)==null?void 0:t.platforms)==null?void 0:a.mercadopago;if(!s)throw new Error("MercadoPago credentials not found");let p=await $(n.identifier,r);if(!p)throw new Error("MercadoPago seller credentials not found");let c=await W(r,o,p);if(!c.raw)throw new Error("MercadoPago payment not found");let l=(s==null?void 0:s.sandbox)===!0?d.MERCADO_PAGO.base_url.sandbox:d.MERCADO_PAGO.base_url.production,u=c.raw.id,f=B(),y=await fetch(`${l}/v1/payments/${u}/refunds`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${p.access_token}`,"X-Idempotency-Key":f}}).then(m=>m.json());if(y.error)throw new Error(y.error);return {message:"MercadoPago payment refunded",identifier:o,raw:y}}catch(s){throw console.error("Error refunding MercadoPago payment",s),s}},Me=Br;var L=async(r,e)=>{var o,n;try{let t=(n=(o=e.openSource)==null?void 0:o.platforms)==null?void 0:n.stripe;if(!t)throw new Error("Stripe credentials not found");let a=t.secret_key;if(!a)throw new Error("Stripe access token not found");let p=await new xe__default.default(a,{typescript:!0}).customers.search({query:`metadata["identifier"]:"${r}"`});if(!p)throw new Error("Stripe account not found");if(!p.data.length)throw new Error("Stripe account not found");if(!p.data[0].metadata.account_id)throw new Error("Stripe account not found");let c=p.data[0].metadata.account_id,i=p.data[0].metadata.identifier;return {account_id:c,identifier:i}}catch(t){throw console.error("Error getting MercadoPago connected account credentials",t),t}};var Dr=async(r,e)=>{var o,n;try{let t=(n=(o=r.openSource)==null?void 0:o.platforms)==null?void 0:n.stripe;if(!t)throw new Error("Stripe credentials not found");let a=t.secret_key;if(!a)throw new Error("Stripe access token not found");let{account_identifier:s}=e,p=new xe__default.default(a,{typescript:!0}),c=await L(s,r),i=await p.accounts.createLoginLink(c.account_id);return {message:"Stripe connect link generated",dashboard_url:i.url,identifier:c.identifier,raw:{...i}}}catch(t){throw console.error(t),t}},Be=Dr;var qr=async(r,e)=>{var l,u,f,y;let{items:o,options:n,seller:t,currency:a}=e;if(!o||o.length===0)throw new Error("Items are required.");if(!t||!(t!=null&&t.identifier))throw new Error("Seller identifier is required.");let s=(u=(l=r.openSource)==null?void 0:l.platforms)==null?void 0:u.stripe;if(!s)throw new Error("Stripe credentials not found");let p=s.secret_key;if(!p)throw new Error("Stripe secret key not found");let c=new xe__default.default(p,{typescript:!0}),i=uuid.v4();try{let m=(y=(f=r.openSource)==null?void 0:f.platforms)==null?void 0:y.stripe;if(!m)throw new Error("MercadoPago credentials not found");if(!m.secret_key)throw new Error("Stripe secret key not found");let S=await L(t.identifier,r);if(!S)throw new Error("Stripe seller credentials not found");let x=o.map(P=>({price_data:{currency:a||"usd",product_data:{name:P.title},unit_amount:Math.round(P.unit_price*100)},quantity:P.quantity})),w=x.reduce((P,k)=>P+k.price_data.unit_amount*k.quantity,0),h=N("stripe",t.fee??0,w),_={payment_method_types:["card"],line_items:x,mode:"payment",metadata:{identifier:i,seller_id:t.identifier},payment_intent_data:{application_fee_amount:h,transfer_data:{destination:S.account_id},metadata:{identifier:i,seller_id:t.identifier}},success_url:n==null?void 0:n.successRedirect,cancel_url:n==null?void 0:n.failureRedirect},b=await c.checkout.sessions.create(_);return {message:"Stripe connect checkout session created",payment_url:b.url,raw:{...b},identifier:i}}catch(m){throw console.error("Error creating Stripe connected account checkout",m),m}},je=qr;var Wr=async(r,e)=>{var p,c,i,l;let{identifier:o,seller:n}=e;if(!o)throw new Error("Identifier is required.");if(!n||!(n!=null&&n.identifier))throw new Error("Seller identifier is required.");let t=(c=(p=r.openSource)==null?void 0:p.platforms)==null?void 0:c.stripe;if(!t)throw new Error("Stripe credentials not found");let a=t.secret_key;if(!a)throw new Error("Stripe secret key not found");let s=new xe__default.default(a,{typescript:!0});try{let u=(l=(i=r.openSource)==null?void 0:i.platforms)==null?void 0:l.stripe;if(!u)throw new Error("MercadoPago credentials not found");if(!u.secret_key)throw new Error("Stripe secret key not found");if(!await L(n.identifier,r))throw new Error("Stripe seller credentials not found");let m=await U(r,o);if(!m)throw new Error("Payment not found");let g=m.raw.id;return {message:"Stripe connect refund created",raw:{...await s.refunds.create({payment_intent:g,refund_application_fee:!0,reverse_transfer:!0})},identifier:o}}catch(u){throw console.error("Error creating Stripe connected account checkout",u),u}},Ue=Wr;var De=r=>Object.assign(e=>r.createConnect(e.platform,e),{mercadop