在看这篇文章之前,相信大家对集成支付宝SDK实现客户端支付已经很熟悉了,这里就不啰嗦了。下面要解决的是如何在不集成支付宝SDK的情况下,使用H5加载支付宝支付链接直接打开支付宝进行支付,并且在支付完成之后跳回APP的问题。
上面的文章的思路是使用WKWebView拦截 alipay://alipayclient 请求,追加或修改参数 fromAppUrlScheme为你自己的URLScheme值,生成新的NSURL,然后用 [[UIApplication sharedApplication] openURL:] 打开即可,但是关于如何追加或修改参数fromAppUrlScheme,文章中没有提到。
我的想法是拦截之后先使用正则匹配,然后判断是否包含fromAppUrlScheme参数,如果包含替换掉参数的值,如果不包含就自己生成然后插入。
代码如下:
// WKWebView代理
// 如果不添加这个,那么WKWebview无法跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
WKNavigationActionPolicy actionPolicy = WKNavigationActionPolicyAllow;
//允许
NSString *urlString = [[navigationAction.request URL] absoluteString];
urlString = [urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//判断是否是支付宝连接
if ([urlString hasPrefix:@"alipay://alipayclient/?"]||
[urlString hasPrefix:@"alipays://alipayclient/?"]){
[self openAlipayWithURLString:urlString];
}
//这句是必须加上的,不然会异常
decisionHandler(actionPolicy);
}
- (void)openAlipayWithURLString:(NSString *)urlString{
NSString *regex = @"\"fromAppUrlScheme\":\"\\w+\"";
//要替换的
NSString *replacement = @"\"fromAppUrlScheme\":\"你的UrlScheme\"";
NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:regex
options:NSRegularExpressionCaseInsensitive
error:nil];
NSInteger count = [regularExpression numberOfMatchesInString:urlString
options:NSMatchingReportProgress
range:NSMakeRange(0, urlString.length)];
NSURL *payURL;
if (count > 0) {//如果包含,就替换掉
NSString *resultStr = urlString;
// 替换匹配的字符串
resultStr = [regularExpression stringByReplacingMatchesInString:urlString
options:NSMatchingReportProgress
range:NSMakeRange(0, urlString.length)
withTemplate:replacement];
NSString *payUrlStr = [resultStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
payURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",payUrlStr]];
}
else{//如果不包含,就插入
NSString *replaceStr = @",\"fromAppUrlScheme\":\"你的UrlScheme\"}";
//获取最后一个字符串
NSString *lastStr = [urlString substringFromIndex:urlString.length - 1];
//替换
NSString *resultStr = [urlString stringByReplacingOccurrencesOfString:lastStr withString:replaceStr];
NSString *payUrlStr = [resultStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
payURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",payUrlStr]];
}
//跳转支付宝
if (@available(iOS 10.0, *)) {
[[UIApplication sharedApplication] openURL:payURL options:@{} completionHandler:nil];
}
else {
[[UIApplication sharedApplication] openURL:payURL];
}
}