通过H5直接打开微信支付

前两天通过H5集成了一款游戏,游戏中集成了微信支付。但是我们的产品对H5跳转微信充值有一定要求,我大致说明一下。

前言:直接使用[[UIApplication sharedApplication] openURL:request.URL]; 这句代码只是跳转了safari浏览器,这样不满足我们产品的需求,另外在safari浏览器中还会有一个弹窗,”是否打开微信“。
如果使用SFSafariViewController也会出现是否打开微信的弹窗。

在这里需要引进一个概念 URL重定向

1、一般情况下服务器端会给一个象征着H5页面调起充值页面的链接。这个链接就是我们所需要的链接,请注意一定要确保这个链接是可用的。
2、在项目的Info.plist中添加一个URL Schemes(用于跳回我们项目),如下图所示在这里插入图片描述这个URL schemes 是跳转到微信支付无论成功失败,要返回本app的依据,当然这个依据要让微信知道,请往下看:
3、流程中最重要的一步 使用webview加载(load)这个url,注意仅仅是load这个url即可,不需要讲webview展示出来,也不需要设置位置什么的,但是要设置代理。

4、直接看代码:

#import "XLLianyunPayWK.h"
#import <WebKit/WebKit.h>

static const NSString *CompanyFirstDomainByWeChatRegister = @"xianlaigame.com";
#define XDX_URL_TIMEOUT 10

@interface XLLianyunPayWK()<WKUIDelegate,WKNavigationDelegate>


@property (nonatomic,strong) WKWebView * wkweb;


@end

@implementation XLLianyunPayWK

//创建webview
- (void)createWKWebView{
    WKWebViewConfiguration * configura = [[WKWebViewConfiguration alloc] init];
    WKUserContentController * userCont = [[WKUserContentController alloc] init];
    configura.userContentController = userCont;
    self.wkweb = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configura];
    [self.wkweb loadRequest: [NSURLRequest requestWithURL:[NSURL URLWithString:self.targetUrl]]];
    self.wkweb.navigationDelegate = self;
    self.wkweb.UIDelegate = self;
}

// 开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    [SVProgressHUD show];
}


- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    NSLog(@"加载完成");
    [SVProgressHUD dismiss];
}


#pragma mark - WKNavigation Delegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSLog(@"---- 跳转 ----- ");
    NSURLRequest *request        = navigationAction.request;
    NSString     *scheme         = [request.URL scheme];
    // decode for all URL to avoid url contains some special character so that it wasn't load.
    NSString     *absoluteString = [navigationAction.request.URL.absoluteString stringByRemovingPercentEncoding];
    NSLog(@"Current URL is %@",absoluteString);
    
    static NSString *endPayRedirectURL = nil;
    
//     Wechat Pay, Note : modify redirect_url to resolve we couldn't return our app from wechat client.
    if ([absoluteString hasPrefix:@"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb"] && ![absoluteString hasSuffix:[NSString stringWithFormat:@"redirect_url=XLHY.%@://",CompanyFirstDomainByWeChatRegister]]) {
        decisionHandler(WKNavigationActionPolicyCancel);
        
#warning Note : The string "xiaodongxie.cn://" must be configured by wechat background. It must be your company first domin. You also should configure "URL types" in the Info.plist file.
        
        // 1. If the url contain "redirect_url" : We need to remember it to use our scheme replace it.
        // 2. If the url not contain "redirect_url" , We should add it so that we will could jump to our app.
        //  Note : 2. if the redirect_url is not last string, you should use correct strategy, because the redirect_url's value may contain some "&" special character so that my cut method may be incorrect.
        NSString *redirectUrl = nil;
        if ([absoluteString containsString:@"redirect_url="]) {
            NSRange redirectRange = [absoluteString rangeOfString:@"redirect_url"];
            endPayRedirectURL =  [absoluteString substringFromIndex:redirectRange.location+redirectRange.length+1];
            redirectUrl = [[absoluteString substringToIndex:redirectRange.location] stringByAppendingString:[NSString stringWithFormat:@"redirect_url=XLHY.%@://",CompanyFirstDomainByWeChatRegister]];
        }else {
            redirectUrl = [absoluteString stringByAppendingString:[NSString stringWithFormat:@"&redirect_url=XLHY.%@://",CompanyFirstDomainByWeChatRegister]];
        }
        
        NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:redirectUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:XDX_URL_TIMEOUT];
        newRequest.allHTTPHeaderFields = request.allHTTPHeaderFields;
        newRequest.URL = [NSURL URLWithString:redirectUrl];
        [webView loadRequest:newRequest];
        return;
    }
    
    // Judge is whether to jump to other app.
    if (![scheme isEqualToString:@"https"] && ![scheme isEqualToString:@"http"]) {
        decisionHandler(WKNavigationActionPolicyCancel);
        if ([scheme isEqualToString:@"weixin"]) {
            // The var endPayRedirectURL was our saved origin url's redirect address. We need to load it when we return from wechat client.
            if (endPayRedirectURL) {
                [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:endPayRedirectURL] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:XDX_URL_TIMEOUT]];
            }
        }else if ([scheme isEqualToString:[NSString stringWithFormat:@"XLHY.%@",CompanyFirstDomainByWeChatRegister]]) {
            
        }
        
        BOOL canOpen = [[UIApplication sharedApplication] canOpenURL:request.URL];
        if (canOpen) {
            [[UIApplication sharedApplication] openURL:request.URL];
            self.openBlock();
        }
        return;
    }
    
    decisionHandler(WKNavigationActionPolicyAllow);
}

5、这个代码是可以直接使用的,但是要注意:static const NSString *CompanyFirstDomainByWeChatRegister = @"xianlaigame.com"; 这个静态全局变量要与刚才url scheme 保持一致。注意URL SCHEME 中的那个XLHY可以不写。

6、webview的那个代理方法中所有redirect_url=XLHY这个位置中的XLHY,可以自由替换,但是请和URL scheme 中保持一致。

总结:这个方法中非常重要的一个概念是:url重定向,至于什么是重定向,我将在下篇博客说明;
我是磊怀 2849765859 是我的QQ 欢迎联系我

<think>嗯,用户想了解在Vue3的H5项目中如何调用微信支付。首先,我得回忆一下微信支付H5环境下的流程。记得微信支付需要商户账号,并且要配置支付域名,确保安全。然后,用户的前端需要生成支付参数,比如时间戳、随机字符串,可能还要后端参与签名。 接下来,用户可能遇到的问题包括配置错误,比如支付域名没设置好,或者参数不正确导致无法调起支付。另外,微信支付需要JSAPI,所以可能需要引入微信的JS文件,或者使用npm包。然后,在Vue3中,应该在生命周期钩子中初始化支付,比如onMounted,或者当用户点击支付按钮时触发。 可能还需要和后端配合,后端生成预支付订单,返回必要的参数给前端,前端用这些参数调用wx.chooseWXPay或者新的JSAPI方法。需要注意测试环境,微信支付可能只能在正式域名下生效,所以测试时可能需要内网穿透工具如ngrok。 另外,跨平台兼容性也要考虑,不同浏览器或微信内置浏览器的支持情况。还要处理支付成功或失败的回调,更新订单状态,跳转页面等。可能还要提醒用户关于SPA应用的路由问题,避免支付后页面跳转导致的问题。 最后,可能需要给出代码示例,比如如何引入微信JS,如何通过axios获取支付参数,然后调用微信的API。同时,提醒用户注意安全,签名要在后端完成,避免暴露密钥。</think>在 Vue3 的 H5 项目中调用微信支付,主要流程分为以下几个关键步骤: ### 一、前期准备 1. **微信商户平台** - 注册并开通微信支付商户账号 - 获取商户号(mch_id)和 API 密钥(API Key) - 配置支付域名(需备案域名) 2. **公众号/服务号** - 认证服务号(H5支付需关联服务号) - 获取公众号 AppID ### 二、核心流程 ```javascript // 示例代码(需配合后端) async function initWechatPay() { // 1. 获取预支付参数 const { appId, nonceStr, package: prepay_id, signType, paySign, timestamp } = await axios.post('/api/create-order', { amount: 100, product: 'VIP会员' }); // 2. 调用微信支付接口 if (typeof WeixinJSBridge === 'undefined') { alert('请在微信内置浏览器中打开'); return; } WeixinJSBridge.invoke('getBrandWCPayRequest', { appId, // 公众号ID timeStamp: timestamp.toString(), // 时间戳 nonceStr, // 随机字符串 package: prepay_id, // 预支付ID signType, // 签名方式 paySign // 加密签名 }, (res) => { // 3. 处理支付结果 if (res.err_msg === 'get_brand_wcpay_request:ok') { alert('支付成功'); router.push('/success'); } else { alert('支付失败: ' + res.err_msg); } }); } ``` ### 三、注意事项 1. **签名验证** - 所有参数必须由后端生成签名(前端切勿暴露 API Key) - 签名算法推荐使用 HMAC-SHA256 2. **环境要求** - 必须通过微信内置浏览器打开 - 安卓设备需使用 `WeixinJSBridge` 调用 - iOS 设备也可使用 `window.wx.chooseWXPay` 3. **支付域名** - 需在微信商户平台配置支付授权目录 - 例如:`https://yourdomain.com/pay/` ### 四、常见问题 1. **无法调起支付** - 检查域名是否备案且正确配置 - 验证签名算法是否正确 - 确保时间戳单位为秒 2. **跨平台问题** - 非微信浏览器需引导用户用微信打开 - 可通过 URL Scheme 实现应用跳转 3. **支付状态同步** - 建议在支付成功后轮询查询订单状态 - 同时配置微信支付结果异步通知 ### 五、调试技巧 1. 使用微信开发者工具调试 2. 通过 `vConsole` 查看日志 3. 利用 `ngrok` 实现本地调试穿透 实际开发中需要与后端紧密配合,确保预支付订单生成、签名验证等环节正确实现。建议参考微信官方文档的最新 H5 支付规范。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值