admin管理员组

文章数量:1291102

I have this error:

Request is not well-formed, syntactically incorrect, or violates schema.

This is my request:

I was looking to make payments with Credit or Debit Cards with Paypal (not with any other), but without having to log in and use the function to make the payment.

if ($transaction['payment_provider'] == 'card') {    
    // Validar que los datos de la tarjeta están presentes
    $cardName = $request->get('card-name');
    $cardNumber = $request->get('card-number');
    $cardExpiry = $request->get('card-expiry');
    $cardCVV = $request->get('card-cvv');

    if (!$cardName || !$cardNumber || !$cardExpiry || !$cardCVV) {
        return $this->paymentHandler->redirectByTransaction($transaction, __('Missing card details'));
    }

    // Formatear fecha de vencimiento para pasarela de pago (ejemplo: MM/AA → MMYY)
    $cardExpiryFormatted = str_replace('/', '', $cardExpiry);

    // Simulación de procesamiento de pago con tarjeta (AQUÍ IRÍA LA INTEGRACIÓN REAL)
    $paymentResponse = $this->processCardPayment([
        'amount' => $transaction['amount'],
        'currency' => $transaction['currency'],
        'card_name' => $cardName,
        'card_number' => $cardNumber,
        'card_expiry' => $cardExpiryFormatted,
        'card_cvv' => $cardCVV
    ]);

    if ($paymentResponse['status'] == 'success') {
        $transaction['status'] = Transaction::APPROVED_STATUS;
    } else {
        $transaction['status'] = Transaction::DECLINED_STATUS;
        return $this->paymentHandler->redirectByTransaction($transaction, __('Payment declined: ') . $paymentResponse['message']);
    }

    // $transaction->save();
    // return Redirect::route('feed')->with('success', __('Payment successful!'));
}
private function processCardPayment($cardData)
{
    // Configurar credenciales desde config/paypal.php
    $clientId = config('paypal.client_id');
    $clientSecret = config('paypal.secret');
    $paypalUrl = config('paypal.test_mode') 
        ? '' 
        : '';

    Log::info("aaaa");
    try {
        // 1️⃣ Obtener el token de acceso de PayPal
        $client = new \GuzzleHttp\Client();
        $authResponse = $client->request('POST', "$paypalUrl/v1/oauth2/token", [
            'auth' => [$clientId, $clientSecret],
            'form_params' => [
                'grant_type' => 'client_credentials'
            ]
        ]);
        Log::info("bbbb");


        $authData = json_decode($authResponse->getBody(), true);
        $accessToken = $authData['access_token'];
        Log::info("cccc");

        // 2️⃣ Crear una orden en PayPal con pago con tarjeta
        $response = $client->request('POST', "$paypalUrl/v2/checkout/orders", [
            'headers' => [
                'Authorization'     => "Bearer $accessToken",
                'Content-Type'      => 'application/json',
                'PayPal-Request-Id' => (string) \Illuminate\Support\Str::uuid() // ID único
            ],
            'json' => [
                'intent'          => 'CAPTURE',
                'purchase_units'  => [[
                    'amount' => [
                        'currency_code' => $cardData['currency'],
                        'value'         => $cardData['amount']
                    ]
                ]],
                'payment_source' => [
                    'card' => [
                        'number'        => $cardData['card_number'],
                        'expiry'        => $cardData['card_expiry'],
                        'security_code' => $cardData['card_cvv'],
                        'name'          => $cardData['card_name'],
                        'billing_address' => [
                            'address_line_1' => '123 Fake Street',
                            'admin_area_2'   => 'Fake City',
                            'admin_area_1'   => 'Fake State',
                            'postal_code'    => '12345',
                            'country_code'   => 'US'
                        ]
                    ]
                ]
            ]
        ]);

        Log::info("eeeee");


        $order = json_decode($response->getBody(), true);
        Log::info("ffff");


        if (!isset($order['id'])) {
            return [
                'status'  => 'failed',
                'message' => 'Error al crear la orden en PayPal'
            ];
        }

        // 3️⃣ Capturar el pago con tarjeta
        $orderId = $order['id'];
        $captureResponse = $client->request('POST', "$paypalUrl/v2/checkout/orders/$orderId/capture", [
            'headers' => [
                'Authorization' => "Bearer $accessToken",
                'Content-Type'  => 'application/json'
            ]
        ]);

        $captureData = json_decode($captureResponse->getBody(), true);

        if (isset($captureData['status']) && $captureData['status'] === 'COMPLETED') {
            return [
                'status'          => 'success',
                'transaction_id'  => $captureData['id'],
                'message'         => 'Pago aprobado'
            ];
        }

        return [
            'status'  => 'failed',
            'message' => 'Pago no completado'
        ];

    } catch (\Exception $e) {
        return [
            'status'  => 'failed',
            'message' => $e->getMessage()
        ];
    }
}

The blogs are because I was checking, how should it be structured to be able to work?

How to structure the json to send a request to Paypal?

本文标签: