iOS 解决H5支付跳转到微信或者支付宝App及返回原App问题

其中XXX代表Scheme

主要是这个方法,请他的方法是辅助这个方法的

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {

    //以下是微信支付和支付宝支付完成或取消后,要回调APP所需的处理
    NSString *url = navigationAction.request.URL.absoluteString;
    if ([url containsString:@"weixin://wap/pay"]) {
        self.load = NO;
        NSLog(@"-00--%@---%@",navigationAction.request.URL,navigationAction.request.allHTTPHeaderFields);
        //第二步到这 吊起微信支付
        [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
        decisionHandler(WKNavigationActionPolicyCancel);
    }
    else if ([url containsString:@"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?"] && !self.load) {
        //发起微信支付后先到这里 我们要做的是设置Referer这个参数,解决回调到safari 浏览器,而不是APP 问题。。(借助URL Scheme 唤起APP 相关知识)
        NSURLRequest *request = navigationAction.request;
        NSMutableURLRequest *newRequest = [[NSMutableURLRequest alloc] init];
        newRequest.allHTTPHeaderFields = request.allHTTPHeaderFields;
        [newRequest setValue:@"XXX://" forHTTPHeaderField: @"Referer"];
        //这里记住redirect_url的值,回调APP的时候用通知重新加载redirect_url,要不然会白屏(什么也不加载)
        if (!self.redirect_url.length) {
            self.redirect_url = [[self getParameter:@"redirect_url" urlStr:[request.URL absoluteString]] BJCF_urlDecodedString];
        }
        NSString *requestUrl = [self deleteParameter:@"redirect_url" WithOriginUrl:[request.URL absoluteString]];
        //这个地址加了redirect_url这个回调的网址,会回调浏览器,修改redirect_url的值,这里redirect_url要传的值, 就是上面Referer的值,这样就会回调APP了
        NSString *urlStr = [NSString stringWithFormat:@"%@&redirect_url=XXX://", requestUrl];

        newRequest.URL = [NSURL URLWithString:urlStr];
        [webView loadRequest:newRequest];
        self.load = YES;
        decisionHandler(WKNavigationActionPolicyCancel);
    }
    // 以下是支付宝
    else if ([url containsString:@"alipay://alipayclient"]) {
        NSMutableString *param = [[url BJCF_urlDecodedString] mutableCopy];
        NSRange range = [param rangeOfString:@"{"];
        // 截取 json 部分
        NSString *param1 = [param substringFromIndex:range.location];
        if ([param1 containsString:@"fromAppUrlScheme"]) {
            NSData *jsonData = [param1 dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
            if (![json isKindOfClass:[NSDictionary class]]) {
                decisionHandler(WKNavigationActionPolicyAllow);
                return;
            }
            NSMutableDictionary *dicM = [json mutableCopy];
            dicM[@"fromAppUrlScheme"] = @"XXX";
            NSString *jsonStr = [dicM yy_modelToJSONString]; // 这里为伪代码, 自行转成json
            NSString *encodedString = [jsonStr BJCF_urlEncodedString];
            // 只替换 json 部分
            [param replaceCharactersInRange:NSMakeRange(range.location, param.length - range.location)  withString:encodedString];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:param]];
        }
        decisionHandler(WKNavigationActionPolicyCancel);
    }
    else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

在APPdelegate里发送通知

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options {
    if ([[url scheme] isEqualToString:@"XXX"]) {
        //发送通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"payReturn" object:nil];
    }
    return true;  
}

在webView的控制器里添加通知

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payBack) name:@"payReturn" object:nil];
}

微信支付回来,需要去加载指定页面,要不然会白屏

- (void)payBack {
    if (self.redirect_url.length) {
        NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.redirect_url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60.0];
        [self.wkWebView loadRequest:request];
    }
}

删除或获取URL中的某个参数

//获取URL中的某个参数:
- (NSString *)getParameter:(NSString *)parameter urlStr:(NSString *)url {
    NSError *error;
    if (!url) {
        return @"";
    }
    NSString *regTags = [[NSString alloc] initWithFormat:@"(^|&|\\?)+%@=+([^&]*)(&|$)",parameter];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags options:NSRegularExpressionCaseInsensitive error:&error];
    NSArray *matches = [regex matchesInString:url options:0 range:NSMakeRange(0, [url length])];
    for (NSTextCheckingResult *match in matches) {
        NSString *tagValue = [url substringWithRange:[match rangeAtIndex:2]]; //分组2所对应的串
        return tagValue;
    }
    return @"";
}

//删除URL中的某个参数:
- (NSString *)deleteParameter:(NSString *)parameter WithOriginUrl:(NSString *)originUrl {
    NSString *finalStr = [NSString string];
    NSMutableString * mutStr = [NSMutableString stringWithString:originUrl];
    NSArray *strArray = [mutStr componentsSeparatedByString:parameter];
    NSMutableString *firstStr = [strArray objectAtIndex:0];
    NSMutableString *lastStr = [strArray lastObject];
    NSRange characterRange = [lastStr rangeOfString:@"&"];
    if (characterRange.location != NSNotFound) {
        NSArray *lastArray = [lastStr componentsSeparatedByString:@"&"];
        NSMutableArray *mutArray = [NSMutableArray arrayWithArray:lastArray];
        [mutArray removeObjectAtIndex:0];
        NSString *modifiedStr = [mutArray componentsJoinedByString:@"&"];
        finalStr = [[strArray objectAtIndex:0]stringByAppendingString:modifiedStr];
    }
    else {
        //以'?'、'&'结尾
        finalStr = [firstStr substringToIndex:[firstStr length] - 1];
    }
    return finalStr;
}

你可能感兴趣的:(iOS 解决H5支付跳转到微信或者支付宝App及返回原App问题)