PayPal支付開發之退款處理(node.js---Koa2)

應該也有人跟我一樣拿回調的PaymentID去退款的。然後就報錯。找不到訂單。

第一步:

獲取saleid,這個是支付成功之後在execute方法裏返回的參數。(payment.transactions[0].related_resources[0].sale.id)

業務層:

async function MerchantsArefund_PayPal(ctx) {
    var saleid = ctx.request.body.PayerID //退款ID
    var data = { amount: { total: ctx.request.body.refundAmount, currency: 'USD' } }
    var whereStr = {
        openId: "nick_chen123456789",
        physicalOrderId: "202006301518123456789",
        Status: 1
    }
    var updateStr = {//修改訂單狀態
        $set: {
            Status: 4,
            e_expressTime: util.getTime()
        }
    }
    await physicalImpl.RefundDirectly_PayPalImpl(saleid, data, whereStr, updateStr).then(res => {
        ctx.body = res
    }).catch(e => {
        console.log(e);
        ctx.body = { code: 201, msg: "服務器繁忙!" };
        throw e;
    })
}

邏輯層:

async function RefundDirectly_PayPalImpl(saleid, data, whereStr, updateStr) {
    var paypal = require('paypal-rest-sdk');
    require('../configuretion');
    return new Promise((resolv) => {
        paypal.sale.refund(saleid, data, function (error, refund) {
            if (error) {
                console.error(JSON.stringify(error));
                resolv({ code: 201, msg: "退款失敗" })
            } else {
                console.log("Refund Sale Response");
                console.log(refund);
                if (refund.state == "completed") {
                    MongoClient.connect(config.Mongose.url, { useNewUrlParser: true }, function (err, db) {
                        if (err) throw err;
                        var dbo = db.db("petshop");
                        dbo.collection("physicalOrders").updateOne(whereStr, updateStr, function (err, res) {
                            if (err) throw err;
                            if (res.result.ok == 1 && res.result.n == 1) {
                                resolv({ code: 200, msg: "退款成功" })
                            } else {
                                resolv({ code: 201, msg: "退款失敗" })
                            }
                        })
                    })
                } else {
                    resolv({ code: 201, msg: "退款失敗" })
                }
            }
        })
    })
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章