iOS H5微信支付總結

功能描述

  • 1、webView加載H5頁面
  • 2、點擊微信支付,調起微信客戶端支付
  • 3、支付完成,返回APP

操作流程

  • 1、調起微信的項目設置
選中‘TARGETS’一欄,在‘info’中的‘LSApplicationQueriesSchemes’添加‘weixin’,已添加過的可以忽略此步驟
  • 2、H5攔截微信支付請求,跳轉微信
  • 2.1 WKWebView
// 實際使用時可以攔截weixin://wap/pay前綴的判斷
#pragma mark - WKNavigationDelegate
//! WKWeView在每次加載請求前會調用此方法來確認是否進行請求跳轉
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    // 先打印此方法攔截的所有請求
    // NSLog(@"\n ==== %@" ,navigationAction.request.URL.absoluteString);
    // decisionHandler(WKNavigationActionPolicyAllow);
    // return ;

    NSURLRequest *request        = navigationAction.request;
    NSString     *scheme         = [request.URL scheme];

    if (![scheme isEqualToString:@"https"] && ![scheme isEqualToString:@"http"]) {
        if ([scheme isEqualToString:@"weixin"]) {
            decisionHandler(WKNavigationActionPolicyCancel);
            BOOL canOpen = [[UIApplication sharedApplication] canOpenURL:request.URL];
            if (canOpen) {
                [[UIApplication sharedApplication] openURL:request.URL];
            }
            return;
        }
        decisionHandler(WKNavigationActionPolicyAllow);
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}
  • 2.2 UIWebView
NSString *reqUrl = request.URL.absoluteString;
    if ([reqUrl hasPrefix:@"weixin://"]) {
        if([[UIApplication sharedApplication] openURL:[NSURL URLWithString:reqUrl]]) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:reqUrl]];
        } else {
            [DLLoading DLToolTipInWindow:@"請安裝微信"];
            return NO;
        }
    }
  • 3、APP端更改redirect_url,實現回到APP

調用支付的時候一定會有一條URL::https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb&redirect_url =**********,通過測試得出支付返回的時候會加載redirect_url,當你的redirect_url是網址的時候,必定會跳轉到瀏覽器,瀏覽器有個特性就是當你的url是****://的時候,會查找你的schemes(iOS系統應該在跳轉瀏覽器之前自己有了判斷是網址才進瀏覽器,****://直接會調用APP),從而可以跳轉到APP,所以要修改這個redict_url的值爲你的schemes的值加上://,就實現跳轉回APP。

  • 3.1 WKWebView
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    NSURLRequest *request = navigationAction.request;
    NSString *absoluteString = [navigationAction.request.URL.absoluteString stringByRemovingPercentEncoding];
    
    // 攔截WKWebView加載的微信支付統一下單鏈接, 將redirect_url參數修改爲喚起自己App的URLScheme
    if ([absoluteString hasPrefix:@"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb"] && ![absoluteString hasSuffix:[NSString stringWithFormat:@"redirect_url=a1.company.com://wxpaycallback/"]]) {
        decisionHandler(WKNavigationActionPolicyCancel);
        NSString *redirectUrl = nil;
        if ([absoluteString containsString:@"redirect_url="]) {
            NSRange redirectRange = [absoluteString rangeOfString:@"redirect_url"];
            redirectUrl = [[absoluteString substringToIndex:redirectRange.location] stringByAppendingString:[NSString stringWithFormat:@"redirect_url=a1.company.com://wxpaycallback/"]];
        } else {
            redirectUrl = [absoluteString stringByAppendingString:[NSString stringWithFormat:@"redirect_url=a1.company.com://wxpaycallback/"]];
        }
        NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:redirectUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
        newRequest.allHTTPHeaderFields = request.allHTTPHeaderFields;
        newRequest.URL = [NSURL URLWithString:redirectUrl];
        [webView loadRequest:newRequest];
        return;
    }
  decisionHandler(WKNavigationActionPolicyAllow);
    return;
}
  • 3.2UIWebView
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    static const NSString*schemeString =@"a1.company.com";
    static const NSString*redirectString =@"redirect_url";

//更改微信參數redirect_url
    if ([reqUrl hasPrefix:jumpString] && ![reqUrl containsString:changeredirectString]) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                NSRange redirectRange = [reqUrl rangeOfString:@"redirect_url"];
                //更改reidrect_url爲scheme地址
                NSString *redirectUrl = [[reqUrl substringToIndex:redirectRange.location] stringByAppendingString:changeredirectString];
                //記錄本來跳轉的地址 用於APP回來之後的刷新
                NSArray *reloadArr = [reqUrl componentsSeparatedByString:@"redirect_url="];
                if (reloadArr.count > 1) {
                    self.reloadURL = [[reloadArr lastObject] stringByRemovingPercentEncoding];
                } else {
                    self.reloadURL = [NSString stringWithFormat:@"https:%@",schemeString];
                }
                //發送請求
                NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:redirectUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
                [request setHTTPMethod:@"GET"];
                //referer爲空會提示"出現商家參數格式有誤,請聯繫商家解決"
                //設置Referer 此地址必須註冊到商戶後臺
                [request setValue:@"jxjywechat.cdeledu.com://" forHTTPHeaderField:@"Referer"];
                [self.webView loadRequest:request];
            });
        });
        return NO;
    }

注:a1.company.com 爲微信後臺註冊二級域名(服務端人員提供)
一級域名也可以,其中一級域名格式www.xxx.com,二級域名格式xxx.xxx.com
[request setValue:a1.company.com :// forHTTPHeaderField: @"Referer"];
這個a1.company.com :// 後面的://一定要加,這個實際是你要跳轉的地址,就是你支付後回跳到你的APP的地址

  • 4、重新加載正確的url

上一步回來的時候是個白屏,因爲你的url是錯誤的,H5也不能識別,所以我們要重新加載之前保存的正確的url

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSString *reqUrl = request.URL.absoluteString;

if ([reqUrl isEqualToString:[NSString stringWithFormat:@"%@://",schemeString]]) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.reloadURL] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
                [self.webView loadRequest:request];
            });
        });
        return NO;
    }
return YES;
}
  • 5、URL Types配置

選中‘TARGETS’一欄,在‘info’中的‘URL Types’添加一項,URL Schemes 填寫‘a1.company.com’

  • 6、支付取消或完成後跳轉到APP內

也可以在payResult中執行step4的操作

AppDelegate中實現
// iOS 9.0
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    if ([url.absoluteString containsString:@"account.test.com://"]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:url];
    }
    return YES;
}

WebViewController中實現
在viewDidLoad中監聽
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payResult:) name:@"test" object:nil];

- (void)payResult:(NSNotification *)noti {
   
}

注:在shouldStartLoadWithRequest代理方法中執行的這幾個操作 都需要在if中return NO,否則會出現連續跳轉的問題

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