Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PayPal API with Laravel - Updating of data

I'm trying to implement the API of PayPal payment with Laravel 5.1. But when I log in to PayPal (sandbox), it uses the address I used in my account, and also it uses the name from PayPal account not the data from my website. That's my problem.

I want to use the data from my website because it doesn't make sense if I enter the shipping address (for example) from my website and not using it. Please see my code below for reference (Or comment down below for some details from me).

class PaypalPaymentController extends BaseController
{

    private $_api_context;

    public function __construct(){
        $paypal_conf = \Config::get('paypal');

        $this->_api_context = new ApiContext(new OAuthTokenCredential(
            $paypal_conf['client_id'],
            $paypal_conf['secret']
        ));

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

    public function payWithPaypal(Request $request){
        $payer = new Payer;
        $payer->setPaymentMethod('paypal');

        $price = 0;

        switch($request->get('amount')) {
            case '10 books':
                $price = 6200;
                break;
            case '20 books':
                $price = 12200;
                break;
            case '50 books':
                $price = 25200;
                break;
            default:
                return redirect()
                        ->route('bookstore.shipping')
                        ->with('danger', 'Please select the right amount of book/s.');
                break;
        }

        $item1 = new Item();
        $item1->setName($request->get('amount'))
                ->setCurrency('PHP')
                ->setQuantity(1)
                ->setPrice($price);

        $item_list = new ItemList();
        $item_list->setItems([$item1]);

        $amount = new Amount();
        $amount->setCurrency('PHP')
                ->setTotal($price);

        $transaction = new Transaction();
        $transaction->setAmount($amount)
                    ->setItemList($item_list)
                    ->setDescription('Books transaction');

        $redirect_urls = new RedirectUrls();
        $redirect_urls->setReturnUrl(route('bookstore.payment-status'))
                        ->setCancelUrl(route('bookstore.payment-status'));

        $payment = new Payment();
        $payment->setIntent('Sale')
                ->setPayer($payer)
                ->setRedirectUrls($redirect_urls)
                ->setTransactions([$transaction]);

         $patchReplace = new Patch();
         $patchReplace->setOp('add')
                    ->setPath('/transactions/0/item_list/shipping_address')
                    ->setValue(json_decode('{
                        "line1": "345 Lark Ave",
                        "city": "Montreal",
                        "state": "QC",
                        "postal_code": "H1A4K2",
                        "country_code": "CA"
                    }'));

         $patchRequest = (new PatchRequest())->setPatches([$patchReplace]);


        try{

            $payment->create($this->_api_context);
            $payment->update($patchRequest, $this->_api_context);

        } catch(\Palpal\Exception\PPConnectionException $e){

            if(\Config::get('app.debug')){
                return redirect()
                        ->route('bookstore.shipping')
                        ->with('danger', 'Connection Timeout.');
            }

            return redirect()
                    ->route('bookstore.shipping')
                    ->with('danger', 'Some error occured, sorry for the inconvenience.');
        }

        foreach($payment->getLinks() as $link){
            if($link->getRel() == 'approval_url'){
                $redirect_url = $link->getHref();
                break;
            }
        }

        Session::put('paypal_payment_id', $payment->getId());

        if(isset($redirect_url)){
            return Redirect::away($redirect_url);
        }

        return redirect()
                ->route('bookstore.shipping')
                ->with('danger', 'Unknown error occured.');
    }

    public function getPaymentStatus(){
        $payment_id = Session::get('paypal_payment_id');
        Session::forget('paypal_payment_id');

        if(empty(Input::get('PayerID')) || empty(Input::get('token'))){
            return redirect()
                    ->route('bookstore.shipping')
                    ->with('danger', 'Payment failed.');
        }

        $payment = Payment::get($payment_id, $this->_api_context);
        $execution = new PaymentExecution();
        $execution->setPayerId(Input::get('PayerID'));

        $result = $payment->execute($execution, $this->_api_context);

        if($result->getState() == 'approved'){
            // Send Email
            $email_data = [
                'number_of_books' => $payment->transactions[0]->item_list->items[0]->name,
                'shipping' => [
                    'street' => $payment->payer->payer_info->shipping_address->line1,
                    'city' => $payment->payer->payer_info->shipping_address->city,
                    'state' => $payment->payer->payer_info->shipping_address->state,
                    'country' => $payment->payer->payer_info->shipping_address->country_code,
                ]
            ];

            // Send email function here ...

            return redirect()
                    ->route('bookstore.shipping')
                    ->with('success', 'Transaction payment success!');
        }

        return redirect()
                ->route('bookstore.shipping')
                ->with('danger', 'Payment failed.');
    }

}

I also reviewed this link but it seems like it cannot answer my problem. Also, what if the country has a province? How can we add that?

Update 1

  1. Added new Patch() class.
  2. Edited Code in Try Catch.

Note: The accepted answer will also receive the bounty plus the up.

Update 2 with Tutorial

  1. For PHP/Laravel (I'm currently using v5.1), install this package paypal/rest-api-sdk-php

  2. Create Sandbox account in PayPal. Choose Buy with Paypal.

  3. Continue until you see options, choose Shop the world.

  4. Login to developer.paypal.com.

  5. Click Accounts. Click Create Account.

  6. Choose what country you want. Choose Personal (Buyer Account) in Account Type.

  7. Add email address, avoid to use -. Use _ instead.

  8. Enter how much PayPal Balance you want.

  9. Click Create Account.

Make it live?

https://github.com/paypal/PayPal-PHP-SDK/wiki/Going-Live

like image 975
Jie Avatar asked Jul 02 '18 06:07

Jie


1 Answers

After you have created the payment, try updating the address as shown in this example.

$paymentId = $createdPayment->getId();

$patch = new \PayPal\Api\Patch();
$patch->setOp('add')
    ->setPath('/transactions/0/item_list/shipping_address')
    ->setValue([
        "recipient_name" => "Gruneberg, Anna",
        "line1" => "52 N Main St",
        "city" => "San Jose",
        "state" => "CA",
        "postal_code" => "95112",
        "country_code" => "US"
    ]);

$patchRequest = new \PayPal\Api\PatchRequest();
$patchRequest->setPatches([$patch]);
$result = $createdPayment->update($patchRequest, $apiContext);

I also reviewed this link but it seems like it cannot answer my problem. Also, what if the country has a province? How can we add that?

Use the state codes listed here.

like image 128
Erik Berkun-Drevnig Avatar answered Oct 22 '22 01:10

Erik Berkun-Drevnig