"use strict";function e(e){return e&&"object"==typeof e&&"default"in e?e.default:e}var t=e(require("crypto")),n=e(require("querystring"));const r=Object.prototype.toString,o=Object.prototype.hasOwnProperty;function u(e,t){return o.call(e,t)}function i(e){return"[object Object]"===r.call(e)}function s(e){return"function"==typeof e}const a=/_(\w)/g,d=/[A-Z]/g;function c(e){return e.replace(a,(e,t)=>t?t.toUpperCase():"")}function p(e){return e.replace(d,e=>"_"+e.toLowerCase())}function f(e,t){let n,r;switch(t){case"snake2camel":r=c,n=a;break;case"camel2snake":r=p,n=d}for(const o in e)if(u(e,o)&&n.test(o)){const n=r(o);e[n]=e[o],delete e[o],i(e[n])?e[n]=f(e[n],t):Array.isArray(e[n])&&(e[n]=e[n].map(e=>f(e,t)))}return e}function l(e){return f(e,"snake2camel")}function y(e){return f(e,"camel2snake")}function h(e){return function(e,t="-"){e=e||new Date;const n=[];return n.push(e.getFullYear()),n.push(("00"+(e.getMonth()+1)).substr(-2)),n.push(("00"+e.getDate()).substr(-2)),n.join(t)}(e=e||new Date)+" "+function(e,t=":"){e=e||new Date;const n=[];return n.push(("00"+e.getHours()).substr(-2)),n.push(("00"+e.getMinutes()).substr(-2)),n.push(("00"+e.getSeconds()).substr(-2)),n.join(t)}(e)}function m(e={},t){if(!t||!e)return e;const n=["_pre","_purify","_post"];t._pre&&(e=t._pre(e));let r={shouldDelete:new Set([])};if(t._purify){const e=t._purify;for(const t in e)e[t]=new Set(e[t]);r=Object.assign(r,e)}if(i(t))for(const o in t){const u=t[o];s(u)&&-1===n.indexOf(o)?e[o]=u(e):"string"==typeof u&&-1===n.indexOf(o)&&(e[o]=e[u],r.shouldDelete.add(u))}else s(t)&&(e=t(e));if(r.shouldDelete)for(const t of r.shouldDelete)delete e[t];return t._post&&(e=t._post(e)),e}function g(e,t){const n=new e(t);return new Proxy(n,{get:function(e,t){if("function"==typeof e[t]&&0!==t.indexOf("_")&&e._protocols&&e._protocols[t]){const n=e._protocols[t];return async function(r){r=m(r,n.args);let o=await e[t](r);return o=m(o,n.returnValue),o}}return e[t]}})}var _={decryptData:function(e,n,r=""){const o=t.createDecipheriv("aes-128-cbc",n,r);o.setAutoPadding(!0);let u=o.update(e,"base64","utf8");return u+=o.final("utf8"),u},md5:function(e,n="utf8"){return t.createHash("md5").update(e,n).digest("hex")},sha256:function(e,n,r="utf8"){return t.createHmac("sha256",n).update(e,r).digest("hex")},getSignStr:function(e){return Object.keys(e).filter(t=>"sign"!==t&&void 0!==e[t]&&""!==e[t]).sort().map(t=>t+"="+e[t]).join("&")},getNonceStr:function(e=16){let t="";for(;t.length${Object.keys(e).map(t=>i(e[t])?`<${t}>`:`<${t}>`).join("")}`},parseXML:function(e){const t=/<(?:xml|root).*?>([\s|\S]*)<\/(?:xml|root)>/.exec(e)[1],n={},r=/<(.*?)>(?:){0,1}<\/.*?>/g;let o=null;for(;o=r.exec(t);)n[o[1]]=o[2];return n},isXML:function(e){return/^(<\?xml.*\?>)?(\r?\n)*(.|\r?\n)*<\/xml>$/i.test(e.trim())}};function w(e,t){t.forEach(t=>{e[t]=Number(e[t])})}var b={unifiedOrder:{args:{_purify:{shouldDelete:["subject"]}}},getOrderInfo:{args:{_purify:{shouldDelete:["subject"]}}},orderQuery:{returnValue:function(e){w(e,["cashFee","totalFee","couponCount"]),e.couponList=[];const t=e.couponCount||0;for(let n=0;n{e[t]=Number(e[t])*n})}var R={unifiedOrder:{args:{_pre:e=>(A(e,["totalFee"],.01),e),totalAmount:"totalFee",buyerId:"openid"},returnValue:{transactionId:"tradeNo"}},getOrderInfo:{args:{_pre:e=>(A(e,["totalFee"],.01),e),buyerId:"openid",totalAmount:"totalFee"}},orderQuery:{args:{tradeNo:"transactionId"},returnValue:{_pre:e=>(A(e,["totalAmount","settleAmount","buyerPayAmount","payAmount","pointAmount","invoiceAmount","receiptAmount","chargeAmount","mdiscountAmount","discountAmount"],100),e),transactionId:"tradeNo",openid:"buyerUserId",tradeState:function(e){switch(e.tradeStatus){case"WAIT_BUYER_PAY":return"USERPAYING";case"TRADE_CLOSED":return"CLOSED";case"TRADE_SUCCESS":return"SUCCESS";case"TRADE_FINISHED":return"FINISHED";default:return e.tradeStatus}},totalFee:"totalAmount",settlementTotalFee:"settleAmount",feeType:"transCurrency",cashFeeType:"payCurrency",cashFee:"buyerPayAmount",fundBillList:function(e){return e.fundBillList?e.fundBillList.map(e=>(e.amount=100*Number(e.amount),e.realAmount=100*Number(e.realAmount),e)):[]},tradeSettleDetailList:function(e){return e.tradeSettleDetailList?e.tradeSettleDetailList.map(e=>(e.amount=100*Number(e.amount),e)):[]},_purify:{shouldDelete:["tradeStatus"]}}},cancelOrder:{args:{tradeNo:"transactionId"},returnValue:{transactionId:"tradeNo"}},closeOrder:{args:{tradeNo:"transactionId"},returnValue:{transactionId:"tradeNo"}},refund:{args:{_pre:e=>(A(e,["refundFee","sendBackFee"],.01),e),tradeNo:"transactionId",refundAmount:"refundFee",outRequestNo:"outRefundNo",refundCurrency:"refundFeeType",refundReason:"refundDesc",goodsDetail:function(e){return e.goodsDetail?e.goodsDetail.map(e=>(e.price=Number(e.price)/100,e)):[]},refundRoyaltyParameters:function(e){return e.refundRoyaltyParameters?e.refundRoyaltyParameters.map(e=>(e.amount=Number(e.amount)/100,e)):[]}},returnValue:{_pre:e=>(A(e,["refundFee","presentRefundBuyerAmount","presentRefundDiscountAmount","presentRefundMdiscountAmount"],100),e),transactionId:"tradeNo",openid:"buyerUserId",cashRefundFee:"presentRefundBuyerAmount",refundId:"refundSettlementId",cashFeeType:"refundCurrency",refundDetailItemList:function(e){return e.refundDetailItemList?e.refundDetailItemList.map(e=>(e.amount=100*Number(e.amount),e.realAmount=100*Number(e.realAmount),e)):[]},refundPresetPaytoolList:function(e){return e.refundPresetPaytoolList?e.refundPresetPaytoolList.map(e=>(e.amount=100*Number(e.amount),e)):[]}}},refundQuery:{args:{tradeNo:"transactionId",outRequestNo:"outRefundNo"},returnValue:{_pre:e=>(A(e,["totalAmount","refundAmount","sendBackFee","presentRefundBuyerAmount","presentRefundBuyerAmount","presentRefundMdiscountAmount"],100),e),transactionId:"tradeNo",outRefundNo:"outRequestNo",totalFee:"totalAmount",refundFee:"refundAmount",refundDesc:"refundReason",refundId:"refundSettlementId",refundRoyaltys:function(e){return e.refundRoyaltys?e.refundRoyaltys.map(e=>(e.refundAmount=100*Number(e.refundAmount),e)):[]},refundDetailItemList:function(e){return e.refundDetailItemList?e.refundDetailItemList.map(e=>(e.amount=100*Number(e.amount),e.realAmount=100*Number(e.realAmount),e)):[]}}},verifyPaymentNotify:{returnValue:{_pre:e=>(A(e,["invoiceAmount","receiptAmount","buyerPayAmount","totalAmount","pointAmount"],100),e),openid:"buyerId",transactionId:"tradeNo",totalFee:"totalAmount",cashFee:"buyerPayAmount",resultCode:function(e){return e.tradeStatus.replace("TRADE_","")},fundBillList:function(e){return e.fundBillList?JSON.parse(e.fundBillList).map(e=>(e.amount=100*Number(e.amount),e)):[]}}}};class F extends class{constructor(e={}){if(!e.appId)throw new Error("appId required");if(!e.privateKey)throw new Error("privateKey required");e.sandbox&&(e.gateway="https://openapi.alipaydev.com/gateway.do"),this.options=Object.assign({},{gateway:"https://openapi.alipay.com/gateway.do",timeout:5e3,charset:"utf-8",version:"1.0",signType:"RSA2",timeOffset:8,keyType:"PKCS8"},e);const t="PKCS8"===this.options.keyType?"PRIVATE KEY":"RSA PRIVATE KEY";this.options.privateKey=this._formatKey(this.options.privateKey,t),this.options.alipayPublicKey&&(this.options.alipayPublicKey=this._formatKey(this.options.alipayPublicKey,"PUBLIC KEY"))}_formatKey(e,t){return`-----BEGIN ${t}-----\n${e}\n-----END ${t}-----`}_formatUrl(e,t){let n=e;const r=["app_id","method","format","charset","sign_type","sign","timestamp","version","notify_url","return_url","auth_token","app_auth_token"];for(const e in t)if(r.indexOf(e)>-1){const r=encodeURIComponent(t[e]);n=`${n}${n.includes("?")?"&":"?"}${e}=${r}`,delete t[e]}return{execParams:t,url:n}}_getSign(e,n){const r=n.bizContent||null;delete n.bizContent;const o=Object.assign({method:e,appId:this.options.appId,charset:this.options.charset,version:this.options.version,signType:this.options.signType,timestamp:h((u=this.options.timeOffset,new Date(Date.now()+6e4*((new Date).getTimezoneOffset()+60*(u||0)))))},n);var u;r&&(o.bizContent=JSON.stringify(y(r)));const i=y(o),s=Object.keys(i).sort().map(e=>{let t=i[e];return"[object String]"!==Array.prototype.toString.call(t)&&(t=JSON.stringify(t)),`${e}=${t}`}).join("&"),a=t.createSign(I[this.options.signType]).update(s,"utf8").sign(this.options.privateKey,"base64");return Object.assign(i,{sign:a})}async _exec(e,t={},n={}){const r=this._getSign(e,t),{url:o,execParams:u}=this._formatUrl(this.options.gateway,r),{status:i,data:s}=await uniCloud.httpclient.request(o,{method:"POST",data:u,dataType:"text",timeout:this.options.timeout});if(200!==i)throw new Error("request fail");const a=JSON.parse(s),d=e.replace(/\./g,"_")+"_response",c=a[d],p=a.error_response;if(c){if(!n.validateSign||this._checkResponseSign(s,d)){if(!c.code||"10000"===c.code){return{errCode:0,errMsg:c.msg||"",...l(c)}}const e=c.sub_code?`${c.sub_code} ${c.sub_msg}`:""+(c.msg||"unkonwn error");throw new Error(e)}throw new Error("返回结果签名错误")}if(p)throw new Error(p.sub_msg||p.msg||"接口返回错误");throw new Error("request fail")}_checkResponseSign(e,n){if(!this.options.alipayPublicKey||""===this.options.alipayPublicKey)return console.warn("options.alipayPublicKey is empty"),!0;if(!e)return!1;const r=this._getSignStr(e,n),o=JSON.parse(e).sign,u=t.createVerify(I[this.options.signType]);return u.update(r,"utf8"),u.verify(this.options.alipayPublicKey,o,"base64")}_getSignStr(e,t){let n=e.trim();const r=e.indexOf(t+'"'),o=e.lastIndexOf('"sign"');return n=n.substr(r+t.length+1),n=n.substr(0,o),n=n.replace(/^[^{]*{/g,"{"),n=n.replace(/\}([^}]*)$/g,"}"),n}_notifyRSACheck(e,n,r){const o=Object.keys(e).sort().filter(e=>e).map(t=>{let n=e[t];return"[object String]"!==Array.prototype.toString.call(n)&&(n=JSON.stringify(n)),`${t}=${decodeURIComponent(n)}`}).join("&");return t.createVerify(I[r]).update(o,"utf8").verify(this.options.alipayPublicKey,n,"base64")}_checkNotifySign(e){const t=e.sign;if(!this.options.alipayPublicKey||!t)return!1;const n=e.sign_type||this.options.signType||"RSA2",r={...e};delete r.sign,r.sign_type=n;return!!this._notifyRSACheck(r,t,n)||(delete r.sign_type,this._notifyRSACheck(r,t,n))}_verifyNotify(e){if(!e.headers)throw new Error("通知格式不正确");let t;for(const n in e.headers)"content-type"===n.toLowerCase()&&(t=e.headers[n]);if(!1!==e.isBase64Encoded&&-1===t.indexOf("application/x-www-form-urlencoded"))throw new Error("通知格式不正确");const r=n.parse(e.body);if(this._checkNotifySign(r))return l(r);throw new Error("通知验签未通过")}}{constructor(e){if(!e.alipayPublicKey)throw new Error("调用支付时需传入支付宝公钥(alipayPublicKey)");super(e),this._protocols=R}async _request(e,t){const n={};t.notifyUrl&&(n.notifyUrl=t.notifyUrl,delete t.notifyUrl),n.bizContent=t;return await this._exec(e,n,{validateSign:!0})}async unifiedOrder(e){return await this._request("alipay.trade.create",Object.assign({sellerId:this.options.mchId},e))}async getOrderInfo(e){switch(this.options.clientType){case"app-plus":{delete e.openid;const t={};e.notifyUrl&&(t.notifyUrl=e.notifyUrl,delete e.notifyUrl),t.bizContent=e;const n=this._getSign("alipay.trade.app.pay",t),{url:r,execParams:o}=this._formatUrl("",n);return(r+"&biz_content="+encodeURIComponent(o.biz_content)).substr(1)}case"mp-alipay":{const t=await this.unifiedOrder(e);if(!t.tradeNo)throw new Error("获取支付宝交易号失败");return t.tradeNo}default:throw new Error("不支持的客户端类型,支付宝支付下单仅支持App、支付宝小程序")}}async orderQuery(e){return await this._request("alipay.trade.query",e)}async cancelOrder(e){return await this._request("alipay.trade.cancel",e)}async closeOrder(e){return await this._request("alipay.trade.close",e)}async refund(e){return await this._request("alipay.trade.refund",e)}async refundQuery(e){return await this._request("alipay.trade.fastpay.refund.query",e)}verifyPaymentNotify(e){return super._verifyNotify(e)}}var N={initWeixin:function(e={}){return e.clientType=e.clientType||__ctx__.PLATFORM,g(S,e)},initAlipay:function(e={}){return e.clientType=e.clientType||__ctx__.PLATFORM,g(F,e)}};module.exports=N;