Вызов CDVPluginResult из совершенно другого класса? - PullRequest
0 голосов
/ 27 апреля 2020

, поэтому я изо всех сил пытаюсь перезвонить моему классу плагина, чтобы сообщить ему, что метод завершен. По сути, я открываю окно оформления заказа, и как только оплата была произведена, я хотел отозвать ее, чтобы я мог передать ее на JS, чтобы она была завершена. Не уверен, что я что-то упускаю или просто что-то усложняю. На данный момент я попытался сохранить идентификатор CallbackID, используя self.checkout.storedCallbackId для возврата к обратному вызову, но я ничего не вижу. Я не очень знаком с Objective- C, поэтому заранее прошу прощения за все отвратительное.

Код выглядит следующим образом:

Плагин Stripe: Я вызываю StripeActivity, который затем вызывает класс извлечения для открытия.


    - (void)StripeActivity:(CDVInvokedUrlCommand*)command
    {
        NSLog(@"StripeActivity");

        CGRect bounds = [[UIScreen mainScreen] bounds];
        UIWindow *window = [[UIWindow alloc] initWithFrame:bounds];
        self.checkout = [[CheckoutViewController alloc] init];
        UINavigationController *rootViewController = [[UINavigationController alloc] initWithRootViewController:self.checkout];
        rootViewController.navigationBar.translucent = NO;
        window.rootViewController = rootViewController;
        [window makeKeyAndVisible];

        self.checkout.storedCallbackId = command.callbackId;
        self.checkout.backendUrl = backendUrl;
        self.checkout.pushableKey = pushableKey;
        self.checkout.userId = userId;
        self.checkout.token = token;
        self.checkout.planId = planId;
        self.checkout.product = product;
        self.checkout.price = price;


        // Create the web view above our one.
        self.webView.window.windowLevel = UIWindowLevelAlert + 1;
        [self.webView.superview addSubview:window];

        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_NO_RESULT];
        [pluginResult setKeepCallback:[NSNumber numberWithBool:YES]];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:self.checkout.storedCallbackId];

        NSLog(@"Orig");
        NSLog(self.checkout.storedCallbackId);
    }

Код проверки: По сути, просто хотите перезвонить с успехом и c после успешного платежа.


    @interface CheckoutViewController ()  
    @property (weak) StripeIntent *plugin;
    @property (weak) STPPaymentCardTextField *cardTextField;
    @property (weak) UIButton *payButton;
    @end
    @implementation CheckoutViewController
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.view.backgroundColor = [UIColor whiteColor];

        STPPaymentCardTextField *cardTextField = [[STPPaymentCardTextField alloc] init];
        self.cardTextField = cardTextField;
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.layer.cornerRadius = 5;
        button.backgroundColor = [UIColor systemOrangeColor];
        button.titleLabel.font = [UIFont systemFontOfSize:22];
        [button setTitle:@"Submit Payment" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(pay) forControlEvents:UIControlEventTouchUpInside];
        self.payButton = button;

        UIStackView *stackView = [[UIStackView alloc] initWithArrangedSubviews:@[cardTextField, button]];
        stackView.axis = UILayoutConstraintAxisVertical;
        stackView.translatesAutoresizingMaskIntoConstraints = NO;
        stackView.spacing = 20;
        [self.view addSubview:stackView];

        [NSLayoutConstraint activateConstraints:@[
            [stackView.leftAnchor constraintEqualToSystemSpacingAfterAnchor:self.view.leftAnchor multiplier:2],
            [self.view.rightAnchor constraintEqualToSystemSpacingAfterAnchor:stackView.rightAnchor multiplier:2],
            [stackView.topAnchor constraintEqualToSystemSpacingBelowAnchor:self.view.topAnchor multiplier:2],
        ]];

        [self startCheckout];

    }

    - (void)displayAlertWithTitle:(NSString *)title message:(NSString *)message restartDemo:(BOOL)restartDemo {
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
            if (restartDemo) {
                [alert addAction:[UIAlertAction actionWithTitle:@"Restart demo" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [self.cardTextField clear];
                    [self startCheckout];
                }]];
            }
            else {
                [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil]];
            }
            [self presentViewController:alert animated:YES completion:nil];
        });
    }

    - (void)startCheckout {
                NSLog(@"Loaded Stripe key");
                // Configure the SDK with your Stripe publishable key so that it can make requests to the Stripe API
                [Stripe setDefaultPublishableKey:_pushableKey];
            }

    - (void)pay {
        // Collect card details on the client
        STPPaymentMethodCardParams *cardParams = self.cardTextField.cardParams;
        STPPaymentMethodParams *paymentMethodParams = [STPPaymentMethodParams paramsWithCard:cardParams billingDetails:nil metadata:nil];
        [[STPAPIClient sharedClient] createPaymentMethodWithParams:paymentMethodParams completion:^(STPPaymentMethod *paymentMethod, NSError *createError) {
            // Create PaymentMethod failed
            if (createError != nil) {
                [self displayAlertWithTitle:@"Payment failed" message:createError.localizedDescription ?: @"" restartDemo:NO];
            }
            else if (paymentMethod != nil) {
                // Create a PaymentIntent on the server with a PaymentMethod
                NSLog(@"Created PaymentMethod");
                [self payWithPaymentMethod:paymentMethod.stripeId orPaymentIntent:nil];
            }
        }];
    }

    // Create or confirm a PaymentIntent on the server
    - (void)payWithPaymentMethod:(NSString *)paymentMethodId orPaymentIntent:(NSString *)paymentIntentId {
        NSDictionary *json = @{};
        if (paymentMethodId != nil) {
            if(_planId == nil){
                json = @{
                        @"useStripeSdk": @YES,
                        @"paymentMethodId": paymentMethodId,
                        @"currency": @"gbp",
                        @"token": _token,
                        @"user_id": _userId,
                        @"plan_id": [NSNull null],
                        @"items": @[
                                @{@"id": @"photo_subscription"}
                        ]
                    };
            }else{
                json = @{
                        @"useStripeSdk": @YES,
                        @"paymentMethodId": paymentMethodId,
                        @"currency": @"gbp",
                        @"token": _token,
                        @"user_id": _userId,
                        @"plan_id": _planId,
                        @"items": @[
                                @{@"id": @"photo_subscription"}
                        ]
                    };
            }

        }
        else {
            json = @{
                @"paymentIntentId": paymentIntentId,
                @"token": _token,
                @"user_id": _userId,

            };
        }
        NSURL *url = [NSURL URLWithString:_backendUrl];
        NSData *body = [NSJSONSerialization dataWithJSONObject:json options:0 error:nil];
        NSMutableURLRequest *request = [[NSURLRequest requestWithURL:url] mutableCopy];
        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:body];
        NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *requestError) {
            NSError *error = requestError;
            NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
            // Request failed
            if (error != nil || httpResponse.statusCode != 200) {
                [self displayAlertWithTitle:@"Payment failed" message:error.localizedDescription ?: @"" restartDemo:NO];
            }
            else {
                NSNumber *requiresAction = json[@"requiresAction"];
                NSString *clientSecret = json[@"clientSecret"];
                NSString *payError = json[@"error"];
                // Payment failed
                if (payError != nil) {
                    [self displayAlertWithTitle:@"Payment failed" message:payError restartDemo:NO];
                }
                // Payment succeeded
                else if (clientSecret != nil && (requiresAction == nil || [requiresAction isEqualToNumber:@NO])) {
                    [self displayAlertWithTitle:@"Payment succeeded" message:clientSecret restartDemo:NO];
                CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"Hello"];
                    [pluginResult setKeepCallback:[NSNumber numberWithBool:YES]];
                    [self.plugin.commandDelegate sendPluginResult:pluginResult callbackId:self.storedCallbackId];

                }
                // Payment requires additional actions
                else if (clientSecret != nil && [requiresAction isEqualToNumber:@YES]) {
                    STPPaymentHandler *paymentHandler = [STPPaymentHandler sharedHandler];
                    [paymentHandler handleNextActionForPayment:clientSecret withAuthenticationContext:self returnURL:nil completion:^(STPPaymentHandlerActionStatus status, STPPaymentIntent *paymentIntent, NSError *handleActionError) {
                            switch (status) {
                                case STPPaymentHandlerActionStatusFailed: {
                                    [self displayAlertWithTitle:@"Payment failed" message:handleActionError.localizedDescription ?: @"" restartDemo:NO];
                                    break;
                                }
                                case STPPaymentHandlerActionStatusCanceled: {
                                    [self displayAlertWithTitle:@"Payment canceled" message:handleActionError.localizedDescription ?: @"" restartDemo:NO];
                                    break;
                                }
                                case STPPaymentHandlerActionStatusSucceeded: {
                                    // After handling a required action on the client, the status of the PaymentIntent is
                                    // requires_confirmation. You must send the PaymentIntent ID to your backend
                                    // and confirm it to finalize the payment. This step enables your integration to
                                    // synchronously fulfill the order on your backend and return the fulfillment result
                                    // to your client.
                                    if (paymentIntent.status == STPPaymentIntentStatusRequiresConfirmation) {
                                        NSLog(@"Re-confirming PaymentIntent after handling action");
                                        [self payWithPaymentMethod:nil orPaymentIntent:paymentIntent.stripeId];
                                    }
                                    else {
                                        [self displayAlertWithTitle:@"Payment succeeded" message:paymentIntent.description restartDemo:NO];
                                        self->_paymentintentId = paymentIntent.description;
                                        NSLog(self->_paymentintentId);
                                        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"Hello"];
                                        [pluginResult setKeepCallback:[NSNumber numberWithBool:YES]];
                                        [self.plugin.commandDelegate sendPluginResult:pluginResult callbackId:self.storedCallbackId];


                                    }
                                    break;
                                }
                                default:
                                    break;
                            }
                    }];
                }
            }
        }];
        [task resume];
    }

    # pragma mark STPAuthenticationContext
    - (UIViewController *)authenticationPresentingViewController {
        return self;
    }
    @end

Я думал, что после успеха будет достаточно, но я ничего не вижу в JS. Полагаю, я делаю что-то глупое и обдумываю что-то, что должно быть легко?:


  CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"Hello"];
                [pluginResult setKeepCallback:[NSNumber numberWithBool:YES]];
                [self.plugin.commandDelegate sendPluginResult:pluginResult callbackId:self.storedCallbackId];

Заранее благодарен за любые советы / советы.

...