iOS實現(xiàn)H5支付(微信、支付寶)原生封裝-創(chuàng)新互聯(lián)

前言

成都創(chuàng)新互聯(lián)服務(wù)緊隨時代發(fā)展步伐,進行技術(shù)革新和技術(shù)進步,經(jīng)過十多年的發(fā)展和積累,已經(jīng)匯集了一批資深網(wǎng)站策劃師、設(shè)計師、專業(yè)的網(wǎng)站實施團隊以及高素質(zhì)售后服務(wù)人員,并且完全形成了一套成熟的業(yè)務(wù)流程,能夠完全依照客戶要求對網(wǎng)站進行網(wǎng)站建設(shè)、成都做網(wǎng)站、建設(shè)、維護、更新和改版,實現(xiàn)客戶網(wǎng)站對外宣傳展示的首要目的,并為客戶企業(yè)品牌互聯(lián)網(wǎng)化提供全面的解決方案。

支付分APP支付、H5支付、掃碼支付等。app支付一般在app中使用,并且需要集成相應(yīng)的支付SDK,H5支付多用于網(wǎng)頁。如果你的APP不想集成支付SDK,又想實現(xiàn)支付功能,你可以在項目中使用H5支付。本文主要講述如何將H5支付封裝成一個原生可調(diào)用的組件。

1.H5支付流程

注:以下為網(wǎng)頁H5支付流程,原生調(diào)用需要修改部分流程

1.1 微信支付

  • 統(tǒng)一下單,獲取微信中間頁地址mweb_url
  • 頁面重定向到微信中間頁
  • 微信中間頁發(fā)起支付請求
  • safari瀏覽器攔截支付請求打開微信APP開始支付(如果在app中,需要在shouldStartLoadWithRequest:方法里面攔截支付請求,并打開微信)

微信中間頁重新向到redirect_url

1.2 支付寶支付

  • 發(fā)起網(wǎng)頁支付請求,H5為一個form表單提交。
  • 頁面重定向到支付寶收銀臺頁面
  • 發(fā)起APP支付請求,并且開始倒計時,如果打開支付寶超時頁面跳轉(zhuǎn)到網(wǎng)頁支付界面,如果喚起支付寶,倒計時結(jié)束。
  • 支付完畢頁面跳轉(zhuǎn)到return_url頁面,需用戶手動觸發(fā)。

2.原生封裝思路

新開一個webView加載支付中間頁,攔截中間頁支付請求并喚起支付,然后關(guān)閉webView流程結(jié)束。

webView需要加到window(或者當(dāng)前控制器的view上),并設(shè)置一個大小(肉眼不可見就行)。因為使用wkwebview時,webView不顯示的情況下,H5請求會被掛起,會導(dǎo)致支付寶頁面不能喚起支付請求。

3.代碼實現(xiàn)

具體步驟見代碼注釋

@interface HJH5WebPayManager()<UIWebViewDelegate>

@property (nonatomic,strong) UIWebView *payWebview;

@property (nonatomic,strong) void(^sendPayResult)(HJH5SendWebPayResult);

@end

@implementation HJH5WebPayManager

+(instancetype)sharedInstance{
 static dispatch_once_t once ;
 static HJH5WebPayManager *_instace = nil;
 dispatch_once(&once, ^{
 _instace = [[self alloc] init];
 });
 return _instace;
}

-(void)loadWebPayTransitionPage:(NSString *)html handleBlock:(void (^)(HJH5SendWebPayResult))handle{
 NSMutableURLRequest *request = nil;
 if ([html hasPrefix:@"https://wx.tenpay.com"]) {
 //微信安全域名
 NSString *wxScheme = @"";
 NSString *referer = [NSString stringWithFormat:@"%@://",wxScheme];
 //將redirect_url替換成scheme,微信支付完畢才能跳回APP,否則會打開Safari瀏覽器(因為redirect_url一般為一個HTTP的地址)
 NSRange range = [html rangeOfString:@"redirect_url="];
 NSString *reqUrl;
 if (range.length>0) {
  reqUrl = [html substringToIndex:range.location+range.length];
  reqUrl = [reqUrl stringByAppendingString:referer];
 }else{
  reqUrl = [html stringByAppendingString:[NSString stringWithFormat:@"&redirect_url=%@",referer]];
 }
 request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:reqUrl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
 //設(shè)置授權(quán)域名,偽造Referer頭,因為微信中間頁會檢驗Referer頭,并且Referer對應(yīng)的值需要包含安全域名
 [request setValue:referer forHTTPHeaderField:@"Referer"];
 if (self.payWebview) {
  [self.payWebview removeFromSuperview];
  self.payWebview = nil;
 }
 self.payWebview = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 0.1, 0.1)];
 self.sendPayResult = handle;
 [[UIApplication sharedApplication].keyWindow addSubview:self.payWebview];
 self.payWebview.delegate = self;
 [self.payWebview loadRequest:request];
 }else if ([html hasPrefix:@"<form"]){
 //如果是支付寶,html對應(yīng)的應(yīng)該是一段form表單提交腳本,需要調(diào)用loadString方法加載
 if (self.payWebview) {
  [self.payWebview removeFromSuperview];
  self.payWebview = nil;
 }
 self.payWebview = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 0.1, 0.1)];
 self.sendPayResult = handle;
 [[UIApplication sharedApplication].keyWindow addSubview:self.payWebview];
 self.payWebview.delegate = self;
 NSString *payStr = html;
 NSString *htmlString = [NSString stringWithFormat:@"htmlString:<html> \n"
    "<head> \n"
    "<meta name=\"viewport\" content=\"initial-scale=1.0, maximum-scale=1.0, user-scalable=no\" /> \n"
    "<style type=\"text/css\"> \n"
    "body {font-size:16px;}\n"
    "</style> \n"
    "</head> \n"
    "<body>"
    "%@"
    "</body>"
    "</html>",payStr];
 [self.payWebview loadHTMLString:htmlString baseURL:nil];
 
 }else{
 //非法html,返回錯誤
 handle(HJH5SendWebPayResultOther);
 return;
 }
 
 
 //容錯處理,20秒沒喚起支付,當(dāng)錯誤處理。
 __weak typeof(self) weakSelf = self;
 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(20 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
 if (weakSelf.sendPayResult) {
  weakSelf.sendPayResult(HJH5SendWebPayResultOther);
 }
 [weakSelf endPayment];
 });
}


- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
//頁面加載失敗,返回錯誤
 if (self.sendPayResult) {
 self.sendPayResult(HJH5SendWebPayResultLoadFail);
 }
 [self endPayment];
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
 NSURL *url = request.URL;
 NSString *newUrl = url.absoluteString;
 //攔截微信支付請求,并打開微信
 if([newUrl rangeOfString:@"weixin://wap/pay"].location != NSNotFound){
 //判斷是否能打開微信
 if ([[UIApplication sharedApplication] canOpenURL:url]) {
  if (@available(iOS 10.0, *)){
  [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
  }else{
  [[UIApplication sharedApplication] openURL:url];
  }
  if (self.sendPayResult) {
  self.sendPayResult(HJH5SendWebPayResultSuccess);
  }
  [self endPayment];
 }else{
  if (self.sendPayResult) {
  self.sendPayResult(HJH5SendWebPayResultSendFail);
  }
  [self endPayment];
 }
 return NO;
 }else if([newUrl rangeOfString:@"alipay://alipayclient/?"].location != NSNotFound){
 //攔截支付寶支付請求,并且替換fromAppUrlScheme參數(shù)為當(dāng)前APP的scheme,實現(xiàn)支付完畢返回APP功能。
 NSString *aliScheme = @"支付寶支付scheme,支付完畢可通過scheme返回到當(dāng)前APP";
 newUrl = [HJStringHelper decodeURL:newUrl];
 NSString *parameterString = [newUrl stringByReplacingOccurrencesOfString:@"alipay://alipayclient/?" withString:@""];
 NSError *error = nil;
 id dict = [NSJSONSerialization JSONObjectWithData:[parameterString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
 if (!error) {
  if ([dict isKindOfClass:[NSMutableDictionary class]]) {
  dict[@"fromAppUrlScheme"] = aliScheme;
  NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
  if (!error) {
   parameterString = [HJStringHelper escapeURL:[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]];
   NSString *payUrl = [NSString stringWithFormat:@"alipay://alipayclient/?%@",parameterString];
   dispatch_async(dispatch_get_main_queue(), ^{
   //判斷是否能打開支付寶
   if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:payUrl]]) {
    if (@available(iOS 10.0, *)){
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:payUrl] options:@{} completionHandler:nil];
    }else{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:payUrl]];
    }
    if (self.sendPayResult) {
    self.sendPayResult(HJH5SendWebPayResultSuccess);
    }
    [self endPayment];
   }else{
    if (self.sendPayResult) {
    self.sendPayResult(HJH5SendWebPayResultSendFail);
    }
    [self endPayment];
   }
   });
  }
  }
 }
 return NO;
 }else{
 return YES;
 }
}

-(void)endPayment{
 self.sendPayResult = nil;
 [self.payWebview removeFromSuperview];
 self.payWebview = nil;
}

@end

另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)建站bm7419.com,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機、免備案服務(wù)器”等云主機租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。

當(dāng)前題目:iOS實現(xiàn)H5支付(微信、支付寶)原生封裝-創(chuàng)新互聯(lián)
當(dāng)前URL:http://bm7419.com/article6/djphig.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供用戶體驗、微信小程序品牌網(wǎng)站制作、建站公司搜索引擎優(yōu)化、網(wǎng)站建設(shè)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站建設(shè)