Wayne Smallman
Wayne Smallman

Reputation: 1720

PayPal: Getting error: "Http response code 400 when accessing https://api.sandbox.paypal.com/v1/payments/payment."

Having followed the code in a GitHub example, and some suggestions here (additional error messages, and an error method), nothing is able to get me south of: $payment->create($this->_api_context); and into the exception handling of the try block, or beyond the generic error message:

Http response code 400 when accessing https://api.sandbox.paypal.com/v1/payments/payment.

Here is the method I'm using:

public function __construct() {

    // PayPal API context.
    $configPayPal = \Config::get('paypal');
    $this->_api_context = new ApiContext(
        new OAuthTokenCredential(
            $configPayPal['client_id'],
            $configPayPal['secret']
        )
    );

    $this->_api_context->setConfig($configPayPal['settings']);

}

public function makePayment(Request $request) {

    $payer = new Payer();

    $payer->setPaymentMethod('paypal');

    $orderForPayment = $request->get('orderForPayment');

    $orderTotal = $request->get('orderTotal');

    $orderTax = $request->get('orderTax');

    $shipping = 0.66;

    $items = [];

    foreach ($orderForPayment as $index => $item):

        $items[$index] = new Item();

        $items[$index]->setName($item['name'])
            ->setCurrency('GBP')
            ->setQuantity($item['qty'])
            ->setPrice($item['subtotal']);

    endforeach;

    $itemsList = new ItemList();

    $itemsList->setItems($items);

    $details = new Details();

    $details->setShipping($shipping)
        ->setTax($orderTax)
        ->setSubtotal($orderTotal);

    $amount = new Amount();

    $amount->setCurrency('GBP')
        ->setTotal($orderTotal + $orderTax + $shipping)
        ->setDetails($details);

    $transaction = new Transaction();

    $transaction->setAmount($amount)
        ->setItemList($itemsList)
        ->setDescription("Your transaction description.");

    $redirect_urls = new RedirectUrls();

    $redirect_urls->setReturnUrl(URL::route('getPaymentStatus'))
        ->setCancelUrl(URL::route('getPaymentStatus'));

    $payment = new Payment();

    $payment->setIntent("Sale")
        ->setPayer($payer)
        ->setRedirectUrls($redirect_urls)
        ->setTransactions(array($transaction));

    //dd($payment->create($this->_api_context)); exit;

    try {

        $payment->create($this->_api_context);

    } catch (PayPal\Exception\PayPalConnectionException $ex) {

        // Prints the Error Code
        echo $ex->getCode();

        // Prints the detailed error message
        echo $ex->getData();

        echo $this->PayPalError($ex);

    } catch (Exception $ex) {

        echo $this->PayPalError($ex);

    }

    foreach ($payment->getLinks() as $link) {

        if ($link->getRel() == 'approval_url') {

            $redirect_url = $link->getHref();

            break;

        }

    }

    // Add payment ID to the session.
    \Session::put('paypal_payment_id', $payment->getId());
    if (isset($redirect_url)) {

        // Redirect to PayPal.
        return Redirect::away($redirect_url);

    }

    \Session::put('error', "Unknown error occurred");

    return Redirect::route('makePayment');

}

I've checked the values down through the method, to make sure they're integers and not strings. I've tried swapping the currencies around between GBP and USD.

I've not used PayPal's API before, so it's possible I've got something wrong, but the generic error is killing the debug process.

While testing, I decided to send to items:

$itemsList->setItems(array());

... and it worked.

So if I send items I get an error, but if I don't I get a success.

I could be wrong, but this appears to be an error with the sandbox itself.

In the "config/paypal.php" file I have:

<?php
return [
    'client_id' => env('PAYPAL_CLIENT_ID'),
    'secret' => env('PAYPAL_SECRET'),
    'settings' => array(
        'mode' => env('PAYPAL_MODE'),
        'http.ConnectionTimeOut' => 3000,
        'log.LogEnabled' => true,
        'log.FileName' => storage_path() . '/logs/paypal.log',
        'log.LogLevel' => 'ERROR'
    ),
];

Upvotes: 0

Views: 2378

Answers (2)

Wayne Smallman
Wayne Smallman

Reputation: 1720

As it turned out — and as I expected — there were a few issues with the calculations due to unexpected typecasting. However, the major problem was in the foreach() function, where the $index variable was the Shopify API ID for the product in question, which is ironic.

So, in the end, the code is:

$x = 0;
foreach ($orderForPayment as $index => $item):

    $items[$x] = new Item();

    $items[$x]->setName($item['name'])
        ->setCurrency('GBP')
        ->setQuantity($item['qty'])
        ->setPrice($item['subtotal']);

    $++;
endforeach;

Upvotes: 2

Code Spirit
Code Spirit

Reputation: 5071

The response code says 400 Bad Request so something with your request is not working.

But I cant see your instantiation of the $_apiContext.
I would guess that you havent configured your context for the sandbox.
Mabye you should take a read on the following Article: PayPal PHP SDK: Making First Call

EDIT:
Try:

$this->_api_context->setConfig(["mode" => "sandbox"]);

PS: Event though youve added the instantiation its not all information needed to solve this problem.

Upvotes: 0

Related Questions