首页 热点资讯 义务教育 高等教育 出国留学 考研考公
您的当前位置:首页正文

iOS集成支付宝和微信支付SDK

2024-12-20 来源:花图问答
1. 支付宝SDK集成

实现思路:
1.下载支付宝SDK
2.集成SDK到项目中,参考官方集成文档。
3.调起支付宝SDK

NSString *appScheme = @"smartarena";
        
// NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
NSString *sdkParam = dict[@"sdkParam"];
NSString *orderString = [NSString stringWithFormat:@"%@",sdkParam];
// NOTE: 调用支付结果开始支付
[[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"payOrder reslut = %@",resultDic);
            [[NSNotificationCenter defaultCenter] postNotificationName:@"AliPayEnded" object:resultDic];
        }];

4.支付宝回调自己的app

appDelegate中处理回调的url, 通过通知的方式通知订单页面做出跳转响应。

为了兼容iOS的不同版本,需要在不同的openURL代理中处理支付宝的回调代码

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if ([url.host isEqualToString:@"safepay"]) { //支付宝付款成功后的回调
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"AliPay result = %@",resultDic);
            [[NSNotificationCenter defaultCenter] postNotificationName:@"AliPayEnded" object:resultDic];
        }];
        return YES;
    }
//iOS9 之前使用的接口
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    if ([url.host isEqualToString:@"safepay"]) {
        //跳转支付宝钱包进行支付,处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"AliPay result = %@",resultDic);
            [[NSNotificationCenter defaultCenter] postNotificationName:@"AliPayEnded" object:resultDic];
        }];
        return YES;
    }

5.订单页收到支付返回通知后的处理

- (void)aliPayEndedWithNotification:(NSNotification *)notification {
    NSDictionary *resultDict = notification.object;
    NSString *resultStatus = [NSString stringWithFormat:@"%@", [resultDict objectForKey:@"resultStatus"]];
    NSString *resultMessage = resultDict[@"memo"];
    NSInteger statusCode = [resultStatus integerValue];
    switch (statusCode) {
        case AliPayResultSucceed:
        case AlipayResultInProgress:
        case AlipayResultUnkown:
        {
            //跳转逻辑
            //[self pushToOrderInfoVC];
        }
            break;
        case AliPayResultCancelledByUser:
        case AliPayResultNetworkError:
        default:
        {
            [self.view showInfo:resultMessage autoHidden:YES interval:2.0];
        }
            break;
    }
}
注意事项:
  1. 调起支付宝SDK时传入的orderPay字符串参数是按一定顺序拼接起来的加过签的参数串,通常由服务端拼接好传给前端。
  2. 调起支付宝SDK时的fromScheme是支付宝回调app的重要依据,通常为app在info中配置的URL Scheme.
参考文章:
2. 微信支付SDK集成

1.下载并集成微信SDK,如果之前集成过友盟或微信分享,则无需再集成。
2.Project-Info中,添加微信的AppKey

微信AppKey.png

3.appDelegate.m中注册微信的appkey

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //微信支付
    [WXApi registerApp:SA_WX_APPKEY];
}

4.调起微信SDK

 PayReq *request = [[PayReq alloc] init];
request.partnerId = reqParam[@"partnerid"];
request.prepayId= reqParam[@"prepayid"];
request.package = @"Sign=WXPay";
request.nonceStr= dict[@"nonceStr"];
request.timeStamp = [dict[@"timestampLong"] intValue];
request.sign = reqParam[@"sign"];
[WXApi sendReq:request];

5.微信支付结束后的回调

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    if ([url.absoluteString hasPrefix:SA_WX_APPKEY]) {
        return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
    }
}
//iOS9以前的版本
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    if ([url.absoluteString hasPrefix:SA_WX_APPKEY]) {
        return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
    }

微信的回调是通过onResp:代理处理的,故封装了一个单例类WXApiManager来处理微信的回调。

WXApiManager.h

#import "WXApi.h"

@interface WXApiManager : NSObject <WXApiDelegate>

+ (instancetype)sharedManager;

@end

WXApiManager.m

@interface WXApiManager()
@end

@implementation WXApiManager

#pragma mark - LifeCycle
+ (instancetype)sharedManager {
    static dispatch_once_t onceToken;
    static WXApiManager *instance;
    dispatch_once(&onceToken, ^{
        instance = [[WXApiManager alloc] init];
    });
    return instance;
}

#pragma mark - WXApiDelegate
- (void)onResp:(BaseResp *)resp
{
    if([resp isKindOfClass:[PayResp class]]){
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"WXPayEnded" object:resp];
        
        
        //支付返回结果,实际支付结果需要去微信服务器端查询
        NSString *strMsg;
        
        switch (resp.errCode) {
            case WXSuccess:
                strMsg = @"支付结果:成功!";
                NSLog(@"支付成功-PaySuccess,retcode = %d", resp.errCode);
                break;
                
            default:
                strMsg = [NSString stringWithFormat:@"支付结果:失败!retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                NSLog(@"错误,retcode = %d, retstr = %@", resp.errCode,resp.errStr);
                break;
        }
    }
}


@end

6.订单页收到支付返回通知后的处理

- (void)wxPayEndedWithNotification:(NSNotification *)notification {
    id object = notification.object;
    if ([object isKindOfClass:[BaseResp class]]) {
      BaseResp *baseResp = (BaseResp *)object;
        switch (baseResp.errCode) {
            case WXSuccess:
            {
                //跳转逻辑
                //[self pushToOrderInfoVC];
            }
                break;
            case WXErrCodeUserCancel:
                break;
                
            default:
            {
                [self.view showInfo:baseResp.errStr autoHidden:YES interval:2.0];
            }
                break;
        }
    }
}
注意事项

iOS9以后,微信/支付宝支付成功后点击左上角的返回也能返回到app,但是会收不到微信/支付宝的回调信息。

解决方案:

在支付页面监听UIApplicationDidBecomeActiveNotification,当监听到返回app的事件后,主动请求服务端,如果发现order已经支付,则主动跳转。

显示全文