跳至主要内容

iOS realizes H5 payment (WeChat, Alipay) native encapsulation

 原文链接


preface

Payment is divided into app payment, H5 payment and code scanning payment. App payment is generally used in apps, and the corresponding payment SDK needs to be integrated. H5 payment is mostly used for web pages. If your app doesn’t want to integrate the payment SDK and wants to realize the payment function, you can use H5 payment in the project. This article mainly talks about how to package H5 payment into a native callable component.

1. H5 payment process

Note: the following is the payment process of webpage H5, and the original call needs to modify some processes

1.1 wechat payment

  • Unified order, access to wechat middle page address mweb_ url
  • Page redirection to wechat middle page
  • Wechat middle page initiates payment request
  • Safari browser intercepts payment request and opens wechat app to start payment (if in app, you need to intercept payment request in shouldstartloadwithrequest: method and open wechat)

Wechat middle page to redirect again_ url

1.2 Alipay payment

  • Initiate a web payment request, and H5 submits a form.
  • Page redirection to Alipay cashier page
  • Launch the APP payment request and start countdown. If you open the Alipay timeout page and jump to the web payment interface, if you call Alipay, the countdown will end.
  • After payment, the page will jump to return_ The URL page needs to be triggered manually by the user.

2. The idea of native packaging

Open a new WebView to load the payment middle page, intercept the payment request from the middle page and call up payment, then close the WebView and the process ends.

WebView needs to be added to the window (or the view of the current controller) and set a size (invisible to the naked eye). When webView is not displayed when using wkwebview, the H5 request will be suspended, which will result in the Alipay page unable to evoke the payment request.

3. Code implementation

See code Notes for specific steps

@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"]) {
 //Wechat secure domain name
 NSString *wxScheme = @"";
 NSString *referer = [NSString stringWithFormat:@"%@://",wxScheme];
 //Will redirect_ Replace the URL with scheme, and you can only jump back to the app after wechat payment, otherwise you will open Safari browser (because of redirect)_ The URL is usually an HTTP address.)
 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];
 //Set the authorized domain name and forge the referer header, because the middle page of wechat will check the referer header, and the value corresponding to the referer needs to contain the security domain name
 [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"]){
 // if it's Alipay, HTML should correspond to a form form submit script, which needs to be loaded by loadString method.
 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{
 //Illegal HTML, error returned
 handle(HJH5SendWebPayResultOther);
 return;
 }
 
 
 //Fault tolerant processing, 20 seconds did not evoke payment, when the error processing.
 __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{
//Page loading failed with 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;
 //Intercept wechat payment request and open wechat
 if([newUrl rangeOfString:@"weixin://wap/pay"].location != NSNotFound){
 //Judge whether wechat can be opened
 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){
 // intercept the Alipay payment request and replace the fromAppUrlScheme parameter to the current APP's scheme to complete the payment and return the APP function.
 NSString *aliScheme = @ "Alipay pays scheme, payment can be completed through scheme to return to current 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(), ^{
   // judge whether Alipay can be opened.
   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

3.1 introduction

Call this method to call – (void) loadwebpaytransitionpage: (nsstring *) HTML handleblock: (void (^) (hjh5sendwebpayresult)) handle

Among them, html is WeChat middle page address and Alipay form form script. For example:

WeChat:   https://wx.tenpay.com ? xxxx

Alipay: <form name= “alipaysubmit” action=xxxx></form><script>document.forms[‘   alipaysubmit ‘].submit();</ script>

See 1. H5 payment process. After placing an order, wechat can obtain the middle page address. For payment, form form is required to submit and load the middle page.

3.2 error handling

typedef NS_ENUM(NSUInteger,HJH5SendWebPayResult) {
 Hjh5sendwebpayresultsuccess = 0, // login successful
 Hjh5sendwebpayresultloadfail, // payment page loading failed
 HJH5SendWebPayResultSendFail, // switch failure, probably without adding WeChat or Alipay.
 Hjh5sendwebpayresultother // other
};

If the payment request is sent successfully, it means that the H5 payment initiation is completed, and the specific payment result needs to be obtained by querying the background. Therefore, we need to deal with some unusual situations, such as page loading failure, WeChat or Alipay did not install exception handling.

4. Description

This scheme can unify the process of WeChat and Alipay H5 payment, and implicitly display the middle page of payment, which will not affect the routing of H5 single page application. App does not need to integrate the payment SDK and can bypass Apple scanning code.

Because the Alipay payment process has changed to the same as WeChat, Alipay’s Web payment function has been cut down and can only be paid by opening Alipay APP. This is also the deficiency of this scheme.

Summary of wechat H5 payment by IOS app

Here, this article about the iOS implementation of H5 payment (WeChat, Alipay) native encapsulation is introduced here. More related iOS H5 payment contents, please search the previous articles of developpaer or continue to browse the relevant articles below, I hope you will support developpaer more!

评论

此博客中的热门博文

Resolving errSecInternalComponent errors during code signing

原文链接 One code signing issue I commonly see, both here on DevForums and in my Day Job™ with DTS, is that the codesign command fails with errSecInternalComponent. This issue crops up in a wide variety of circumstances and the correct fix depends on the specific problem. This post is my attempt to clarify the potential causes of this error and help folks resolve it. If you have any questions or comments about this, please start a new thread, tagging it with Code Signing so that I see it. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" Resolving errSecInternalComponent errors during code signing In some circumstances the codesign command might fail with the error errSecInternalComponent. For example: % codesign -s "Apple Development" "MyTrue" MyTrue: errSecInternalComponent This typically affects folks who are signing code in a nonstandard environm...

iOS:检测使用VPN或Proxy

参考链接: https://www.jianshu.com/p/c3b950dbf86a https://gist.github.com/PramodJoshi/4faad4c91f7dcb4eb9b06be8390c01db http://noodlecode.net/2018/04/check-if-ios-app-is-connected-to-vpn 第一种方法 需要导入框架CFNetwork 然后,这个方法是mrc的:需要添加-fno-objc-arc的flag 代码如下: + ( BOOL )getProxyStatus { NSDictionary *proxySettings = NSMakeCollectable ([( NSDictionary *) CFNetworkCopySystemProxySettings () autorelease]); NSArray *proxies = NSMakeCollectable ([( NSArray *) CFNetworkCopyProxiesForURL (( CFURLRef )[ NSURL URLWithString: @"http://www.google.com" ], ( CFDictionaryRef )proxySettings) autorelease]); NSDictionary *settings = [proxies objectAtIndex: 0 ]; NSLog ( @"host=%@" , [settings objectForKey:( NSString *)kCFProxyHostNameKey]); NSLog ( @"port=%@" , [settings objectForKey:( NSString *)kCFProxyPortNumberKey]); NSLog ( @"type=%@" , [settings objectForKey:( NSString *)kCFProxyTypeKey]); if ([[settings object...

去广告DNS设置,国内ADGuard DNS方案,手机电脑iOS去广告,保护隐私

 原文链接 之前分享过使用mac系统搭建adguard home,这几个月用下来零零散散基本上也被弃用了。主要原因是因为需要保持电脑一直开机。但是我的电脑是笔记本,存在移动各个地域的情况,也就是说只能够屏蔽电脑自身,对于手机而言不太现实。今天偶然发现dnspod推出了高级版的公共解析。dnspod背靠腾讯云,肯定是合法合规的公共解析服务,这个高级版用起来不错。 国内自己搭建解析服务是违法行为,所以这也是为什么使用dnspod的原因。 后台截图 开始使用 首先我们先进入dnspod的公共解析页面,点击开始使用。 专业版公共解析 dnspod会提供几种预设,我们选择「开发者」即可 开发者 然后你就成功的申请到自己个人使用的dns了! 更新拦截规则 我们可以将常见的广告过滤规则加入到dns中。我们在顶部选项卡中选择「拦截规则」。 拦截规则设置 打开adguard adguard 绑定iOS设备 推荐使用描述文件的方式,删除配置时删除描述文件即可。 描述文件 绑定macOS 推荐使用描述文件的方式,删除配置时删除描述文件即可。 描述文件 mac需要在「系统偏好设置」的「网络」中查看是否正在运行。 代理 如果没有运行需要点击「···」来启动服务。 启动服务 绑定路由器 找到自己路由器的DHCP设置,修改dns,然后记得绑定自己的ip。 修改dns 绑定ip 费用 目前有300万次/月的免费额度,但没有超出之后的价格。300万次一个人比较难用完,可以放心使用。 我个人使用iOS设备两台、智能家居、电脑两台,日均请求数大致2万/日。 判断是否搭建成功 可以通过查看日志的方式,日志大概有半小时到一小时的延迟,请耐心等待。