
import tenpay = require('tenpay');
import path = require('path');

/*
包名：com.bantu.sgzzyz
APPID：wx1d3cd5cd2f065358
AppSecret：ebf099c41da57edf8693b5bb234d9b31
商户号：1272966801
APISECRET：ABCabc328BantuPKU726BANTUMPRCghb
*/

const config = {
    appid: 'wx1d3cd5cd2f065358',
    mchid: '1272966801',
    partnerKey: 'ABCabc328BantuPKU726BANTUMPRCghb',
    pfx: require('fs').readFileSync(path.resolve(__dirname, '../../../../../key/weixinpay/apiclient_cert.p12')),
    notify_url: "https://" + "10.29.176.166" + "/order/weixinpaycallback",//支付回调网址
    spbill_create_ip: '127.0.0.1'
};
// 方式一
const api = new tenpay(config);
// 调试模式
// const api = new tenpay(config, true);
// 沙盒模式(用于微信支付验收)
// const sandboxAPI = await tenpay.sandbox(config);




/**
   * 微信下单
   *
   * @param {number} price 价格订单金额(分)
   * @param {string} message 商品信息
   * @param {string} localOrderID 本地订单号
   *
   */
export async function applyOrderWX(localOrderID: string, price: number, message: string) {
    let data = {
        out_trade_no: localOrderID,
        body: message,//'商品简单描述',
        total_fee: price,//'订单金额(分)',
    }
    console.log('applyOrderWX :', data)
    let result = await api.getAppParams(data)
    // { appid: 'wx1d3cd5cd2f065358',
    // partnerid: '1272966801',
    // prepayid: 'wx12171213153829021f7cfe9413f0a20000',//微信订单号
    // package: 'Sign=WXPay',
    // noncestr: 'OohMyaHNK0iP77uh',
    // timestamp: '1620810734',
    // sign: '7A1B41C577E78602344D03DE4A2F7B0A' }
    console.log('applyOrderWX result: ', result)
    if (result.appid == config.appid && result.partnerid == config.mchid) {
        return { code: 0, data: result };
    }
    return { code: -1, data: JSON.stringify(result) };
}



/**
   * 微信查询支付结果
   *
   * @param {number} serverId 区Id
   * @param {string} roleId 角色Id
   * @param {string} localOrderID 本地订单号
   *
   */
export async function checkOrderWX(localOrderID: string) {
    let data = {
        out_trade_no: localOrderID,
    }
    console.log('checkOrderWX :', data)
    let result = await api.orderQuery(data)
    //     { return_code: 'SUCCESS',
    //   return_msg: 'OK',
    //   result_code: 'SUCCESS',
    //   mch_id: '1272966801',
    //   appid: 'wx1d3cd5cd2f065358',
    //   device_info: '',
    //   trade_state: 'NOTPAY',
    //   total_fee: '6',
    //   out_trade_no: 'nMeyvwjJSmNXPmfGcr6kzalTR3jlp7jW',
    //   trade_state_desc: '订单未支付',
    //   nonce_str: 'aJevQOtSDgvNDbtQ',
    //   sign: '955CE5F8AA2F046DA66E0A5DA56B338A' }
    console.log('checkOrderWX result: ', result)
    if (result.appid == config.appid && result.mch_id == config.mchid) {
        return { code: 1, data: result };
    }
    return { code: 0, data: JSON.stringify(result) };
}