React Js 微信支付 簡單封裝

本文出自:

http://blog.csdn.net/wyk304443164/

/**
 * Created by wuyakun on 2017/5/8.
 */

import common from './common';
import Fetch from './FetchIt';
import API_URL from "./url";

let Pay = {};

/**
 * 支付的回調
 */
let payCallback;

/**
 * 開始支付--這個方法其實是從後臺請求微信支付簽名。成功繼續,失敗回調
 * @param _order_id 傳order_id即可
 * @param _thisObj 傳this即可
 * @param _payType 支付類型--暫時只有微信
 * @param _callback 回調 true or false
 */

Pay.done = function (_order_id, _thisObj, _payType, _callback) {
    let postData = {
        order_id: _order_id,
    };
    if (typeof _callback === "function") {
        payCallback = _callback;
    }
    Fetch.postObjData(API_URL.mobile.payUrl, postData).then((data) => {
        this.doneResponse(data);
    }).catch(() => {
        payCallback(false);
    });
};

Pay.doneResponse = function (result) {
    this.callPay(result);
};

Pay.callPay = function (code) {
    if (typeof WeixinJSBridge === "undefined") {
        if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', this.jsApiCall, false);
        } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', this.jsApiCall);
            document.attachEvent('onWeixinJSBridgeReady', this.jsApiCall);
        }
    } else {
        this.jsApiCall(code);
    }
};

Pay.jsApiCall = function (code) {
    WeixinJSBridge.invoke('getBrandWCPayRequest', code, function (res) {
        if (!common.isNull(res) && !common.isNull(res.err_msg) && res.err_msg.indexOf('ok') > 0) {
            payCallback(true);
        } else {
            payCallback(false);
        }
    });
};

//退款---------------------沒有了!!!!!!!!!!
let Refund = {};

//退款
Refund.done = function (order_id, callback) {
    let postData = {
        order_id: order_id,
    };
    Fetch.postObjData(API_URL.mobile.refundUrl, postData).then((data) => {
        console.log(data);
        if (typeof callback === "function") {
            callback();
        }
        //需要判斷是否成功
    });
};

export {Pay as default, Refund}

調用也很簡單

import Pay from '../../common/PayRefund';

startPay = () => {
        let id = '7018253979853';
        let _that = this;

        Pay.done(id, _that, 1, is_true => {
            if (is_true) {
                // 支付成功後的邏輯
                alert('支付成功');
            } else {
                // 支付失敗後的邏輯
                alert('支付失敗');
            }
        });
    };

其中this和payType其實並沒有用到,只是方便以後使用,退款是直接訪問後臺,功能去掉了。 我就沒寫。需要的小夥伴自己添加即可。別忘了引入

<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章