Flutter-使用Laravel API进行条纹付款

时间:2019-12-06 11:37:51

标签: laravel flutter stripe-payments laravel-cashier

因此,基本上我想做的是让客户添加信用卡以备后用,而我所做的是:

StripePayment.setOptions(StripeOptions(
        publishableKey: "MY_KEY_HERE"));

并添加了一个按钮:

onPressed: () async {
                    dynamic value =
                        await StripePayment.paymentRequestWithCardForm(
                      CardFormPaymentRequest(),
                    ).catchError(setError).then(
                      (PaymentMethod paymentMethod) async {
                        try {
                          addCreditCard(paymentMethod);    // post request to laravel cashier api with the payment method
                          print("Payment Method ID: ${paymentMethod.id}");
                        } catch (e) {
                          print(e);
                        }
                      },
                    );
                  },

所以我在这里所做的是,用户可以按一个按钮,然后弹出输入表单,其中包含带有条带验证算法的所有必需的卡详细信息,一旦输入所有内容,我将返回返回的PaymentMethod对象(包含令牌和最后4个数字等。)之后,我将此PaymentMethod对象发送给包含该功能的laravel收银员api:


public function create_card(Request $request)
    {
        $user = $request->user();
        $user->addPaymentMethod($request->method); //Laravel billable cashier function
        return response()->json([
            'message' => 'Successfully updated credit card'
        ], 201);
    }

我收到否这样的付款方式的回复,我不确定如何从这里继续,因为我找不到与此有关的任何文档。 任何帮助都会很棒。

Laravel的收银员可计费的addPaymentMethod函数:

public function addPaymentMethod($paymentMethod)
    {
        $this->assertCustomerExists();

        $stripePaymentMethod = $this->resolveStripePaymentMethod($paymentMethod);

        if ($stripePaymentMethod->customer !== $this->stripe_id) {
            $stripePaymentMethod = $stripePaymentMethod->attach(
                ['customer' => $this->stripe_id], $this->stripeOptions()
            );
        }

        return new PaymentMethod($this, $stripePaymentMethod);
    }

2 个答案:

答案 0 :(得分:0)

尝试删除“异步”并打印PaymentMethod来检查您是否获得付款方式ID:

StripePayment
.paymentRequestWithCardForm(CardFormPaymentRequest())
.then((paymentMethod) {
print(paymentMethod);
}).catchError((error)=>{print(error)});

答案 1 :(得分:0)

对于仍在为这个问题苦苦挣扎的人,我终于找到了添加付款方式的可行解决方案。

我的设置是这样的:

Laravel Framework 8.37.0
    "laravel/cashier": "^12.12",
    "laravel/sanctum": "^2.9",

Flutter (Channel stable, 2.0.5)
    Dart 2.12.3
    stripe_payment: ^1.0.11

颤振侧:

sample_view.dart 是包含调用 Stripe 方法的按钮的屏幕:

import 'package:my_sample_package/services/payment_services.dart';
import 'package:flutter/material.dart';
import 'package:stripe_payment/stripe_payment.dart';


class Subscribe extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Center(
          child: ElevatedButton(
            child: Text("Add new Payment Method"),
            onPressed: () {
              StripeService.addNewPayment();
            },
          )
        )
      ),
    );
  }
}

payment_services.dart 是处理 Stripe 和 Api 调用的文件:

import 'dart:convert';
import 'dart:developer';
import 'package:dio/dio.dart';
import 'package:flutter/services.dart';
import 'package:stripe_payment/stripe_payment.dart';

class StripeService {
  Dio dio = new Dio();
  static Future<dynamic> addNewPayment() async {
    StripePayment.setOptions(
      StripeOptions(
        publishableKey: "your_stripe_publishable_key",
        merchantId: "Test",
        androidPayMode: 'test'
      )
    );

    Dio dio = new Dio(); // I'm using Dio instead of the http package
    String baseUrl = 'http://192.168.1.122:8000/api/'; // Your host, I started mine using ## php artisan serve --host 192.168.1.122 --port 8000 ##
    String token = 'my_laravel_access_token'; // This is the token I get from Laravel Sanctum

    await StripePayment.paymentRequestWithCardForm(
      CardFormPaymentRequest(), // This will show the Native Payment Card form 
    )
    .then(
      (PaymentMethod paymentMethod) async {
        try {
          inspect(paymentMethod);
          final response = await dio.post(
            baseUrl + "user/subscription/payment-method/update", // My Laravel endpoint for updating the payment method
            options: Options(
              headers: { 'Authorization': 'Bearer $token' },
            ),
            data: {
              "payment_method": paymentMethod
            }
          );
          inspect(response);
        } catch (e) {
          inspect(e);
        }
      },
    ).onError((error, stackTrace) {
      inspect(error);
    });
  }
}

Laravel 侧:

routes/api.php 文件来注册我们需要的路由:

...
Route::group(['prefix' => 'user', 'middleware' => ['auth:sanctum']], function () {
    Route::post('subscription/payment-method/update', [UserController::class, 'updatePaymentMethod']);
});
...

Controllers/UserController.php 文件来注册我们的方法:

public function updatePaymentMethod(Request $request): \Illuminate\Http\JsonResponse
    {
        $user = auth()->user();
        $user->updateDefaultPaymentMethod($request->payment_method['id']); // You need to pass just the payment method ID, not the whole object

        return response()->json([
            'message' => 'Payment method saved'
        ], 200);
    }