美文网首页
iOS 简单接入stripe支付(oc版本)

iOS 简单接入stripe支付(oc版本)

作者: 低调的雅痞先生 | 来源:发表于2022-12-17 11:02 被阅读0次

首先,先上stripe官方的链接,官方其实写的已经是很细致细致了,对于新手来说也是很友好的。

官方链接

接下来,话不多说,上活!

第一步,pod 依赖库

    用CocoaPods将Stripe依赖库pod下来,因为我用的oc,所以并没有去pod官方给的StripePaymentsUI,找了和StripePaymentsUI相关的demo,发现里面都是用swift写的,然后我也一直pod不下来,所以我后来放弃了,如果有的小伙伴想用的话,可以试试。(pod 'StripePaymentsUI')。

直接 pod 'Stripe'

第二步,准备相关的key(通常都是问后台要,因为stripe支付基本都是后端来完成的,哈哈)

    这里所说的key是在stripe那边注册账号,申请的对应的测试key以及正式发布key。开发的时候我们用测试的key就可以,因为官方给了对应的测试卡号,可完成测试环节,非常友好。

第三步,代码实现

    1,我在PrefixHeader的全局文件里面定义了两个key,

    #define STRIPE_TEST_PK @"此处为测试的公钥"。

    #define STRIPE_LIVE_PK @"此处为正式环境的公钥"。

    2,在AppDelegate.m中完成Stripe的初始化配置

    1)倒入依赖库的头文件#import <Stripe.h>

    2)初始化配置

    // 配置stripe支付

    [Stripe setDefaultPublishableKey:STRIPE_TEST_PK];

    上面这行代码可以放在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {}这个方法里就行。以上就是完成依赖库的简单初始化了。

    3,支付调用,我这里因为没有StripePaymentsUI可用,然后是自己写的alert弹窗,用的Stripe里面的STPPaymentCardTextField这个控件,实现的信用卡信息的收集。

    在支付调用的类引入头文件

    // Stripe支付

    #import <Stripe.h>

    在需要调用支付的按钮点击事件处,首先要请求后段服务接口,这个接口需要给我们返回所需的ClientSecret,字段名字后台随便定义。

    我这边是在程序里面定义了一个属性变量,用这个变量来存储这个字符串@property (nonatomic,copy) NSString *paymentIntentClientSecret;

    在请求后台接口成功的时候给这个变量赋值,后面需要用。同时在接口请求成功的时候,弹出我们自定义的alert。参考代码如下:

NSDictionary *data_dic = [NSDictionary dictionaryWithDictionary:responseObject[@"data"]];

 weakSelf.paymentIntentClientSecret = [NSString stringWithFormat:@"%@",data_dic[@"paymentIntent"]];

if(!weakSelf.PayAlert) {

                    UIView*pay_alert = [weakSelfshowPayAlert];

                    [appDelegate.windowaddSubview:pay_alert];

                    weakSelf.PayAlert= pay_alert;

                }

弹窗如下图:

如何自定义alert用下面的代码作为参考。定义了一个@property (nonatomic,weak) UIView *PayAlert;    

// showPayAlert

- (UIView *)showPayAlert{

    UIView *payAlert = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height)];

    payAlert.backgroundColor=ClearColor;

    UIView *bla_view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height-300)];

    bla_view.backgroundColor = ColorWithRGB(@"#000000", 0.5);

    [payAlertaddSubview:bla_view];

    UITapGestureRecognizer *bla_view_tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(bla_view_tap_action)];

    [bla_viewaddGestureRecognizer:bla_view_tap];

    UIView*whi_view = [[UIViewalloc]initWithFrame:CGRectMake(0,Screen_Height-300,Screen_Width, 300)];

    whi_view.backgroundColor=white_Color;

    [payAlertaddSubview:whi_view];

    UIButton *close_btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];

    [close_btnsetImage:[UIImage imageNamed:@"SDPay_close"] forState:UIControlStateNormal];

    [whi_viewaddSubview:close_btn];

    [close_btnaddTarget:self action:@selector(close_btn_action) forControlEvents:UIControlEventTouchUpInside];

    UILabel *top_lab = [[UILabel alloc] initWithFrame:CGRectMake(20, CGRectGetMaxY(close_btn.frame), Screen_Width-40, 20)];

    top_lab.text = FGGetStringWithKeyFromTable(@"tpl127", @"Localizable");

    top_lab.font = [UIFont systemFontOfSize:18];

    top_lab.textColor=black_Color;

    [whi_viewaddSubview:top_lab];

    UILabel *bom_lab = [[UILabel alloc] initWithFrame:CGRectMake(20, CGRectGetMaxY(top_lab.frame)+10, Screen_Width-40, 20)];

    bom_lab.text = FGGetStringWithKeyFromTable(@"tpl128", @"Localizable");

    bom_lab.font = [UIFont systemFontOfSize:15];

    bom_lab.textColor = colorWithHexString(@"#666666");

    [whi_viewaddSubview:bom_lab];

    STPPaymentCardTextField *cardTextField = [[STPPaymentCardTextField alloc] initWithFrame:CGRectMake(20, 110, Screen_Width-40, 40)];

    cardTextField.numberPlaceholder = FGGetStringWithKeyFromTable(@"tpl132", @"Localizable");

    cardTextField.expirationPlaceholder = FGGetStringWithKeyFromTable(@"tpl130", @"Localizable");

    cardTextField.postalCodePlaceholder = FGGetStringWithKeyFromTable(@"tpl131", @"Localizable");

    self.cardTextField= cardTextField;

    [whi_viewaddSubview:cardTextField];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];

    button.frame=CGRectMake(20,CGRectGetMaxY(cardTextField.frame)+30,Screen_Width-40, 50);

    button.layer.cornerRadius= 5;

    button.backgroundColor = [UIColor systemBlueColor];

    button.titleLabel.font = [UIFont systemFontOfSize:22];

    [buttonsetTitle:[NSString stringWithFormat:@"%@ %@",FGGetStringWithKeyFromTable(@"tpl129", @"Localizable"),self.money_lab.text] forState:UIControlStateNormal];

    [buttonaddTarget:self action:@selector(pay) forControlEvents:UIControlEventTouchUpInside];

    self.payButton= button;

    [whi_viewaddSubview:button];

    returnpayAlert;

}

- (void)bla_view_tap_action{

    [appDelegate.window endEditing:YES];

}

- (void)close_btn_action{

    [appDelegate.window endEditing:YES];

    if(self.PayAlert) {

        [self.PayAlert.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];

        [self.PayAlert removeFromSuperview];

        self.PayAlert=nil;

    }

}

为了更好的体验,我在这个类里面监听了键盘的弹出事件

- (void)addObserve{

    // 增加监听,当键盘出现或改变时收出消息

    [[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(keyboardWillShow:)

                                                 name:UIKeyboardWillShowNotification

                                               object:nil];

    // 增加监听,当键退出时收出消息

    [[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(keyboardWillHide:)

                                                 name:UIKeyboardWillHideNotification

                                               object:nil];

}

#pragma mark- 监听键盘的高度

// 当键盘出现或改变时调用

- (void)keyboardWillShow:(NSNotification*)aNotification{

    // 获取键盘的高度

    NSDictionary*userInfo = [aNotificationuserInfo];

    NSValue*aValue    = [userInfoobjectForKey:UIKeyboardFrameEndUserInfoKey];

    CGRectkeyboardRect = [aValueCGRectValue];

    CGFloatheight      = keyboardRect.size.height;

    if(self.PayAlert) {

        self.PayAlert.y= -height;

    }

}

// 当键退出时调用

- (void)keyboardWillHide:(NSNotification*)aNotification{

    if(self.PayAlert) {

        self.PayAlert.y= 0;

    }

}

点击支付弹窗上的支付按钮的点击事件实现:

- (void)pay{

    [appDelegate.window endEditing:YES];

    if (!self.paymentIntentClientSecret) {

            NSLog(@"PaymentIntent hasn't been created");

            return;

        }

    [MBProgressHUD showHUDAddedTo:appDelegate.window animated:YES];

    //我这里是直接使用Stripe自带的STPPaymentCardTextField收集的卡参数

    STPPaymentMethodParams *paymentMethodParams = [STPPaymentMethodParams paramsWithCard:self.cardTextField.cardParams billingDetails:nil metadata:nil];

    //服务器传递过来的ClientSecret

    STPPaymentIntentParams *paymentIntentParams = [[STPPaymentIntentParams alloc] initWithClientSecret:self.paymentIntentClientSecret];

    paymentIntentParams.paymentMethodParams= paymentMethodParams;

    // paymentIntentParams.savePaymentMethod = @YES;

    //自己设置的urlScheme: your-app://stripe-redirect

    //paymentIntentParams.returnURL = @"xxx://xxx.stripe.com";

    MJWeakSelf

    // Submit the payment

    STPPaymentHandler *paymentHandler = [STPPaymentHandler sharedHandler];

    // STPAuthenticationContext 需要实现一下<STPAuthenticationContext>

    [paymentHandlerconfirmPayment:paymentIntentParams withAuthenticationContext:self completion:^(STPPaymentHandlerActionStatus status, STPPaymentIntent *paymentIntent, NSError *error) {

        dispatch_async(dispatch_get_main_queue(), ^{

            [MBProgressHUD hideAllHUDsForView:appDelegate.window animated:YES];

            switch(status) {

                case STPPaymentHandlerActionStatusFailed: {// 失败

                    NSLog(@"STPPaymentHandlerActionStatusFailed %@",error.localizedDescription ?: @"");

                    [MBProgressHUD showMessage:FGGetStringWithKeyFromTable(@"tpl88", @"Localizable") toView:appDelegate.window delay:2];

                    break;

                }

                case STPPaymentHandlerActionStatusCanceled: {// 取消

                    NSLog(@"STPPaymentHandlerActionStatusCanceled %@",error.localizedDescription ?: @"");

                    [MBProgressHUD showMessage:FGGetStringWithKeyFromTable(@"tpl89", @"Localizable") toView:appDelegate.window delay:2];

                    break;

                }

                case STPPaymentHandlerActionStatusSucceeded: {// 成功

                    NSLog(@"STPPaymentHandlerActionStatusSucceeded %@",paymentIntent.description ?: @"");

                    [MBProgressHUD showMessage:FGGetStringWithKeyFromTable(@"tpl87", @"Localizable") toView:appDelegate.window delay:2.5];

                    [weakSelfclose_btn_action];

                    // 支付成功后代码业务逻辑可在这里编写

                    // 。。。。。

                    break;

                }

                default:

                    break;

            }

        });

    }];

}

# pragma mark STPAuthenticationContext协议实现

- (UIViewController *)authenticationPresentingViewController {

    return self;

}

到这里简单的oc版本的stripe支付就完成了,希望可以帮助你解惑,程序之路任重道远,疫情后时代,希望山河无恙,每个人都健健康康的。

相关文章

  • iOS 简单接入stripe支付(oc版本)

    首先,先上stripe官方的链接,官方其实写的已经是很细致细致了,对于新手来说也是很友好的。 官方链接[https...

  • IOS接入Stripe支付

    简单写一下,能最快的实现支付。 步骤为:加卡->选择支付方式->发起支付(或使用ApplePay) 1.加卡 加卡...

  • iOS Stripe支付 OC版

    前文 前段时间在空暇时间写了GoogleMaps的使用指南,刚写完的一段时间,发现并没有人阅读,所以不太想写第二篇...

  • iOS oc版Stripe支付

    之前有个项目是要做海外支付业务,最后大家决定用stripe支付,但是iOS Stripe支付中文的资料很少,我看...

  • iOS Stripe支付 OC版

    前文 前段时间在空暇时间写了GoogleMaps的使用指南,刚写完的一段时间,发现并没有人阅读,所以不太想写第二篇...

  • Stripe 支付接入笔记

    后端处理部分 后端向 stripe 服务器发起请求 本文 Postman 请求,来走支付流程 请求头 Author...

  • stripe支付接入步骤

    官网:https://dashboard.stripe.com/test/dashboard[https://da...

  • iOS接入国际支付Stripe和Braintree

    前言 最近在开发国际版APP时需要用到支付,由于资料比较少,所以这里记录一下Braintree和Stripe的使用...

  • iOS Stripe支付升级支持欧洲九月SCA验证(支持信用卡3

    前言 之前写过一篇Stripe的信用卡支付的接入文章,这篇文章是由于前两天突然看到Stripe官网上,有这样的提醒...

  • Stripe集成 iOS 端

    Stripe集成 iOS 端 因为项目中有遇到需要针对海外用户集成银行卡支付功能,经过考虑选择了Stripe。官方...

网友评论

      本文标题:iOS 简单接入stripe支付(oc版本)

      本文链接:https://www.haomeiwen.com/subject/vwudqdtx.html