DevOverlord
DevOverlord

Reputation: 446

Paypal PHP SDK HTTP Error during a transaction update

I am developing a ecommerce site for a friend and in the process of updating Paypal with the shipping amount prior to executing the payment, and I get the following error. This error is occuring when I call on Patch, PatchRequest, and then try executing the payment. Here is all of the code:

if (Input::get('action', 'get') === "getDetails") { //Check to see if the action parameter is set to getDetails

      $payment = \PayPal\Api\Payment::get(Input::get('paymentId', 'get'), $paypalAPI);

      $payerInfo = $payment->getPayer()->payer_info;
      if (!empty($payment)){
        $quantity = 0;
        foreach ($payment->transactions[0]->item_list->items as $item) {
          $quantity += $item->quantity;
        }
        if ($quantity <= 20) {
          $parcelType = "MediumFlatRateBox";
        } else if ($quantity > 20) {
          $parcelType = "LargeFlatRateBox";
        }
        $shipment = \EasyPost\Shipment::create([
          'from_address' => \EasyPost\Address::retrieve(Config::get('easypost/addressObjectID')),
          'to_address' => [
            'name' => $payerInfo->shipping_address->recipient_name,
            'street1'=> $payerInfo->shipping_address->line1,
            'street2' => (isset($payerInfo->shipping_address->line2)) ? $payerInfo->shipping_address->line2 : null,
            'city' =>$payerInfo->shipping_address->city,
            'state' => $payerInfo->shipping_address->state,
            'country' => $payerInfo->shipping_address->country_code,
            'zip' => $payerInfo->shipping_address->postal_code,
            'email' => $payerInfo->email
          ],
          'parcel' => [
            'predefined_package' => $parcelType,
            'weight' => 520
          ]
        ]);
        //Grab the lowest shipping rate
        $shippingRate = $shipment->lowest_rate()->rate;
        //Make a call to PayPal updating our transaction with the tax and shipping rate
        $amount = $payment->transactions[0]->amount;
        $transactionUpdate = new \PayPal\Api\Patch();
        $transactionUpdate    ->setOp('replace')
                              ->setPath('transactions/0/amount')
                              ->setValue(json_decode('{
                                "total": "'.$amount->total.'",
                                "currency":"USD",
                                "detail": {
                                  "subtotal": "'.$amount->details->subtotal.'",
                                  "shipping":"'.$shippingRate.'"
                                }
                              }'));


        //Instantiate a new instance of PayPal's Patch Request Class and Update the Transaction with the tax and shipping rate
        $updateRequest = new \PayPal\Api\PatchRequest();
        $updateRequest->setPatches(
          [$transactionUpdate]
        );
        //Attempt Update

        $result = $payment->update($updateRequest, $paypalAPI);

        if ($result) {
          $transID = generateTransactionID();
          $fields = [
            'dateCreated' => strtotime($payment->create_time),
            'transID' => $transID,
            'paymentID' => $payment->id,
            'shipmentID' => $shipment->id
          ];
          $db->insert('transactionLog', $fields);
          Redirect::to('shoppingCartFinalize.php?transID='.$transID);
          exit();
        } else {
          Alert::set([
            'header' => "Uh Oh....Something Went Wrong",
            'message' => "Unable to update transaction. Transaction Cancelled. Please try again.",
            'type' => 'danger',
            'close' => 1
          ]);
          Redirect::to('shoppingCartView.php');
          exit();
        }
      }

THe following is the error i get during the call:

Fatal error: Uncaught exception 'PayPal\Exception\PayPalConnectionException' with message 'Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/payments/payment/PAY-77N347011V970714EKU2D24Q.' in /var/www/html/myla-dev/vendor/paypal/rest-api-sdk-php/lib/PayPal/Core/PayPalHttpConnection.php:177 Stack trace: #0 /var/www/html/myla-dev/vendor/paypal/rest-api-sdk-php/lib/PayPal/Transport/PayPalRestCall.php(74): PayPal\Core\PayPalHttpConnection->execute('[{"op":"replace...') #1 /var/www/html/myla-dev/vendor/paypal/rest-api-sdk-php/lib/PayPal/Common/PayPalResourceModel.php(103): PayPal\Transport\PayPalRestCall->execute(Array, '/v1/payments/pa...', 'PATCH', '[{"op":"replace...', NULL) #2 /var/www/html/myla-dev/vendor/paypal/rest-api-sdk-php/lib/PayPal/Api/Payment.php(474): PayPal\Common\PayPalResourceModel::executeCall('/v1/payments/pa...', 'PATCH', '[{"op":"replace...', NULL, Object(PayPal\Rest\ApiContext), NULL) #3 /var/www/html/myla-dev/apiProcessing.php(146): PayPal\Api\Payment->update(Object(PayPal\Api\ in /var/www/html/myla-dev/vendor/paypal/rest-api-sdk-php/lib/PayPal/Core/PayPalHttpConnection.php on line 177

UPDATE: Thank you for the assistance Thaer. It helped. Now I am getting a separate error. When I attempt to update the payment it is now saying the following:

Array ( [name] => PAYMENT_STATE_INVALID [message] => This request is invalid due to the current state of the payment [information_link] => https://developer.paypal.com/webapps/developer/docs/api/#PAYMENT_STATE_INVALID [debug_id] => 1b1b9b71e91d8 )

If you know how to fix this please. I don't know how to change the state so that the payment can be updated.

If you find an error please let me know. I am so stuck it is not funny.

Dave Douglas

Upvotes: 0

Views: 760

Answers (2)

Jay Patel - PayPal
Jay Patel - PayPal

Reputation: 1489

First, can you confirm if the payment is already executed or not ?

Note that it can only be updated before the execute is done. Once, the payment is executed it is not possible to udpate that. Docs: https://developer.paypal.com/webapps/developer/docs/api/#update-a-payment-resource

And I think your payment has already been executed, and so the state would be complete and not created, which is causing that 400 Exception of invalid state.

Let me know if that makes sense.

To make a change in the payment, you might be able to create a refund, to return the remaining amount.

Alternatively, you could also use authorize or order, to hold the funds first, and then actually charge them later. Kind of how you see it in restaurants, etc, where they hold the fund of your total, but eventually add the tip later, and complete the transaction later.

For more information read here: https://developer.paypal.com/webapps/developer/docs/integration/direct/create-process-order/

Upvotes: 1

Thaer Zaghal
Thaer Zaghal

Reputation: 44

Please refer to this Answer I think you must try - catch your code to determine error ,regards.

Upvotes: 1

Related Questions