iOS H5頁面調用微信或者支付寶進行支付

一說支付,大多數人都會理解支付方式是下載微信和支付寶SDK進行支付,但是其實還有其他的方式,就是H5調用系統支付寶和微信進行支付。

H5支付可能很多人認爲是加載完頁面剩下的就是頁面完成即可,但是實際沒有那麼簡單。

下面介紹一下H5調用支付寶和微信支付。

首先是支付寶,支付寶在支付這一塊是非常專業的他的代碼也是非常簡單的。既然是H5調用,那麼就少不了網址攔截。這裏加載頁面我是使用的WebView

這裏說一下,這裏微信和支付寶都是使用這個方法裏進行

- (BOOL) webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType) navigationType;

首先是支付寶,這裏我們要攔截包含下面的內容的鏈接

alipay://alipayclient

下面就是代碼了。

    if([[request.URL absoluteString] containsString:@"alipay://alipayclient"]) {
        NSArray* urlBaseArr = [[request.URL absoluteString] componentsSeparatedByString:@"?"];
        NSString* urlBaseStr = urlBaseArr.firstObject;
        NSString* urlNeedDecode = urlBaseArr.lastObject;
        NSString* afterDecodeStr =[self URLDecodedString:urlNeedDecode];
        NSString* afterHandleStr = [afterDecodeStr stringByReplacingOccurrencesOfString:@"alipays" withString:@"設置的支付寶URLSchemes"];
        NSString* finalStr = [NSString stringWithFormat:@"%@?%@",urlBaseStr,[self URLEncodeString:afterHandleStr]];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:finalStr]]) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:finalStr]];
            }
        });
        return NO;
    }

下面是上面代碼中使用的兩個方法

 //  OC 做URLEncode的方法
 -  (NSString *)URLEncodeString:(NSString*)str {
     NSString *unencodedString = str;
     NSString *encodedString = (NSString *) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)unencodedString,NULL,(CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8));
     return encodedString;
 }
  
 - (NSString*)URLDecodedString:(NSString*)str {
     NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)str, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
     return decodedString;
 }

這樣在點擊支付寶支付的時候會直接調起支付寶完成支付,這裏有一個重點,就是URLSchemes,如果不設置,取消支付或者支付完成,會直接進入safari瀏覽器,所以這裏我們要設置一下

下來就是Appdelegate我們收到支付寶支付成功的回掉

// NOTE: 9.0以後使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    NSString *urlStr = [NSString stringWithFormat:@"%@",url];
    if ([url.host isEqualToString:@"safepay"]) {
        // 支付跳轉支付寶錢包進行支付,處理支付結果,此處發送通知,哪裏需要接受通知處理,哪裏就接受
        [[NSNotificationCenter defaultCenter]postNotificationName:@"AlipaySDK" object:nil userInfo:nil];
    }
}

到此設置完成

下面是微信,微信就比較麻煩,沒有支付寶簡單,廢話不多說直接上代碼

if ([[request.URL absoluteString] rangeOfString:@"https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?"].location != NSNotFound) {
        //設置redirect_url,如果存在redirect_url,那麼需要替換redirect_url對應的值(替換內容爲,自已公司支付的網頁域名)
        NSString *redirect_url = @"&redirect_url=自已公司支付的網頁域名";
        NSString *newUrl = [NSString stringWithFormat:@"%@%@",absoluteUrl,redirect_url];
        //字符串進行替換,讓回調之後返回自己的app
        newUrl = [newUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        NSLog(@"newUrl - - - - - - %@",newUrl);
        NSMutableURLRequest *newRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:newUrl]];
        NSDictionary *headers = [request allHTTPHeaderFields];
        BOOL hasReferer = [headers objectForKey:@"Referer"]!=nil;
        if (hasReferer) {
            return YES;
        } else {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:newUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
                    [request setHTTPMethod:@"GET"];
                    [request setValue:@"自已公司支付的網頁域名://" forHTTPHeaderField: @"Referer"];
                    [self.myWebView loadRequest:request];
                });
            });
            return NO;
        }
    }

當然這裏我們也需要設置URLSchemes

下來就是Appdelegate我們收到微信支付成功的回掉

    if ([urlStr rangeOfString:@"自已公司支付的網頁域名"].location != NSNotFound) {
        //此處發送通知,哪裏需要接受通知處理,哪裏就接受
        [[NSNotificationCenter defaultCenter] postNotificationName:@"WeChatH5PayNotification" object:url.absoluteString];
    }

至此,H5支付完成

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