小程序web-view网页调取小程序支付功能

本文介绍如何在小程序的web-view中调用小程序自身的支付功能。通过在payment.html页面引入微信JSSDK,修改立即支付按钮代码,并在小程序端创建对应页面及配置JS文件,实现了web与小程序之间的支付交互。

原理:利用JSSDK提供的wx.miniProgram.navigateTo接口传递小程序支付接口必要的参数,在小程序里调起支付

1.payment.html
(1)引入微信JSSDK

<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>

(2)修改立即支付按钮代码

<a id="btn_pay_submit" data-url="<{link app=b2c ctl=mobile_checkout act=dopayment args0=$order.order_id}>?pay=<{$order.pay_app}>">立即支付</a>

(3)JS

/**
 * 返回url参数
 * @param {String} key 想要获取的参数key
 * @param {String} url 网址链接
 * @returns {String} key对应的value,如果没有则返回null
 */
function getParam(key, url) {
    const spTxt = '?'
    const spIdx = url.indexOf(spTxt);

    if(spIdx == -1) return false;

    const paramStr = url.split(spTxt)[1];
    let reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)", "i");
    let val = paramStr.match(reg); 
    
    if (val != null) return unescape(val[2]); 
    return null; 
} 

// 按钮逻辑修改
$("#btn_pay_submit").on("click", function(){
    let url = $(this).attr("data-url");
    let wxapp = getParam('pay', url);

    // 如果在小程序环境且支付方式为小程序支付就请求接口获取支付所需参数
    // bill_id是支付结果页所需要的参数
    if (window.__wxjs_environment === 'miniprogram' && wxapp == 'wxpayinwxapp') {
        $.ajax({
            type: "GET",
            dataType:"json",                    
            url: "<{link app=b2c ctl=mobile_checkout act=xcx_dopayment args0=$order.order_id}>?openid=<{$openid}>",
            success: function(res) {
                if (!res.error) {
                    let params = '?billId='+res['bill_id']+'&timestamp='+res['timeStamp']+'&nonceStr='+res['nonceStr']+'&'+res['package']+'&signType='+res['signType']+'&paySign='+res['paySign']+'&orderId=<{$order.order_id}>';
                    
                    wx.miniProgram.navigateTo({
                        url: '/pages/wxpay/wxpay' +  params
                    });
                } else {
                    alert('error:', res.error);
                }
            }
        });
    } else {
        // 其他情况则继续走原来的逻辑
        location.href = url;
    }
})

// 支付方式代码修改
$('#pay_confirm').on('click', function () {
    var order_id = '<{$order.order_id}>';
    var pay_id = $("input[name='pay-check']:checked").val();
    var link = '/index.php/m/checkout-payment-' + order_id + '-0-' + pay_id + '.html';
    $.getJSON(link, function (re) {
    });
    $('#pay_show').html($("input[name='pay-check']:checked").attr('data-name'));
    // 把'href'改为'data-url'
    $("#btn_pay_submit").attr('data-url', '<{link app=b2c ctl=mobile_checkout act=dopayment args0=$order.order_id}>?pay=' + pay_id);
    $('#pay_mask').hide();
    $('#pay_actionsheet').removeClass('weui-actionsheet_toggle');
});

2.小程序
(1)新建小程序页面

{
    "pages": [
        "pages/index/index",
        "pages/wxpay/wxpay"
    ]
}

(2)index.js

const config = require('../../config/config.js');
Page({
    data: {
        url: ''
    },
    
    onLoad: function(options) {
        const _this = this;
        
        // code给后端获取openid用
        // wxapppay=xcx给后端标识为小程序
        wx.login({
            success(res) {
                if (res.code) {
                    let url = config.BASE_HOST + '/m/index.html?wxapppay=xcx&code=' + res.code;
                    
                    _this.setData({
                        url: url
                    });
                } 
            }
        })
    },
})

(3)index.wxml

<web-view src="{{url}}"></web-view>

(4)wxpay.js

const config = require('../../config/config.js');
Page({
    data: {
    },

    onLoad: function(options) {
        console.log(options);
        this.requestPayment(options);
    },

    requestPayment(options) {
        const _this = this;

        // 调起微信支付
        wx.requestPayment({
            // 相关支付参数
            'timeStamp': options.timestamp,
            'nonceStr': options.nonceStr,
            'package': 'prepay_id=' + options.prepay_id,
            'signType': options.signType,
            'paySign': options.paySign,
            'success': function(res) {
                console.log("success res", res);
                _this.backToResult(options);
            },
            // 小程序支付失败的回调通知
            'fail': function(res) {
                console.log("fail res", res);
                _this.backToResult(options);
            }
        });
    },

    backToResult(options) {
        // 定义小程序页面集合
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2];
        const url = config.BASE_HOST + '/m/checkout-payresult-' + options.billId + ' .html';
        console.log("url", url);

        prevPage.setData({
            url: url,
        });
        wx.navigateBack();
    }
})
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值