laravel POST работает в почтальоне, а не в экземпляре axios в реагирующем - PullRequest
0 голосов
/ 24 сентября 2019

Я пытаюсь создать объект PaymentIntent, созданный на сервере, используя stripe-php и laravel 5.8 со следующим кодом:

в routs / api.php:

Route::post('/create-payment-intent', 'Api\v1\PaymentController@createPaymentIntent');

в файле PaymentController.php:

public function createPaymentIntent(Request $request) {
    $validator = Validator::make($request->all(), [
      'amount' => 'required',
      'currency' => 'required',
      'voucherId' => 'required',
    ]);

    $user = Auth::user();
    $voucher = AppVoucher::where('id', $request->input('voucherId'))->first();
    $voucherOwner = User::where('id', $voucher['business_id'])->first();

    try {
      $paymentIntent = \Stripe\PaymentIntent::create([
        'amount' => $request->input('amount') * 100 ,
        'currency' => $request->input('currency'),
        'customer' => $user->client_stripe_id,
        'description' => $voucher->description,
        'on_behalf_of' => $voucherOwner->stripe_account_id,
        'payment_method_types' => ['card'],
        'receipt_email' => $user->email,
        'transfer_data' => ['destination' => $voucherOwner->stripe_account_id],
      ]);

      return response()->json(['paymentIntent' => $paymentIntent], 200);
    }

    catch (\CardErrorException $e) {
      return response()->json([
        'information' => 'Error. Something went wrong. Please try again',
        'error_on' => 'creating a Payment Intent object in Stripe',
      ], 400);
    }
  }

на моем клиенте (приложение React-Native) я создал экземпляр axios и вспомогательную функцию apiCall для выполнения всех запросов к моему api следующим образом:

Вспомогательная функция axiosInstance и apiCall:

const axiosInstance = axios.create({
  baseURL: config.apiUrl.local, // LOCAL ENV
  // baseURL: config.apiUrl.staging, // STAGING ENV
  cancelToken: source.token,
});

const apiCall = async ({ url, method, data, options, onSuccess, onError }) => {
  const token = await getToken();
  const headers = {
    'Access-Control-Allow-Origin': '*',
    'Content-Type': 'application/json',
  };

  if (options.withPhoto) {
    headers['Content-Type'] = 'multipart/form-data';
  }

  if (options.withToken) {
    headers.Authorization = `Bearer ${token}`;
  }

  axiosInstance({ url, method, data, headers })
    .then((res) => {
      if (res.status >= 200 || res.status < 300) {
        onSuccess(res.data);
      }
    })
    .catch(err => onError(err));
};

export default apiCall;

в componentDidMount из CheckoutContainer:

componentDidMount() {
    const { navigation, onPaymentIntentStart, onPaymentIntentFail } = this.props;
    const voucher = navigation.getParam('voucher');
    onPaymentIntentStart();

    apiCall({
      url: 'create-payment-intent',
      data: {
        amount: Number(voucher.amount),
        currency: 'gbp',
        voucherId: voucher.id,
      },
      method: 'post',
      options: { withToken: true, withPhoto: false },
      onSuccess: res => console.log('onSuccess res: ', res),
      // onSuccess: res => this.onPaymentIntentSuccess(res),
      onError: err => console.log('onError err: ', err),
      // onError: err => onPaymentIntentFail(err.message),
    });
  }

Эта настройка работает для каждого отдельного apiCall, который я создаю в приложении, за исключением соответствующего метода, который работаетс почтальоном, но не с axios в реакции-родной.Я также попытался увеличить время ожидания в axiosInstance, добавив ключ времени ожидания, но все равно выдает код ошибки 500.

Если я удаляю код на сервере, связанный с $paymentIntent, и просто возвращаю $user,$voucher и $voucherOwner используя axios, я получаю ответ.

Я застрял на несколько дней.Чего мне здесь не хватает?

...