Jump to content
Killersites Community
Neo73

Paypal Integration - Php Shopping Cart Tutorial

Recommended Posts

Hey guys,

 

PayPal changed it's APIs and website some time ago, which unfortunately makes the PayPal integration videos (33-39) of your Shopping Cart Tutorial obsolete. I bought your tutorial with the expectation of getting a beginner's explanation how to effectively integrate PayPal.

 

PayPal now seems to differentiate between the new REST API and the old Classic API, which will only be supported until further notice.

Their documentation / website is pretty confusing and not really clear as the information is all over the place.

 

I would appreciate your guidance how to implement PayPal with the working PHP cart I built. 

 

Are you planning to update the videos on PayPal? I assume that would take a Pro only a couple of hours and would surely be appreciated by everyone who bought the tutorial with the expectation of succesfully implementing PayPal.

 

Thanks for your feedback.

Share this post


Link to post
Share on other sites

Hi,

 

You are correct, there has been an update since the video course was produced and it is something we are looking to address. In the meantime, you can still learn a lot from the course using the classic API. 

 

Please message me for details.

 

PS: do you know any PHP?

 

Stefan

Share this post


Link to post
Share on other sites

Hi Stefan,

 

after searching for quiet some time for the relevant links on PayPal's website this morning, I was able to implement your original solution.

They really made a step back in user-friendly design and their documentation is quiet a mess. The older website was much clearer.

Once you find your way through their chaos and you find the original button generator, your video explanations are very straight forward.

 

However, I assume that your original solution addresses the classic API, so if you have an update on the incorporation of the REST API

that would be much appreciated. 

 

Yes, I know basic PHP.

 

Thanks.

Share this post


Link to post
Share on other sites

Cool. We going to create an update for the course. You will have access needless to say ... 

 

BTW, what are the URLs on Paypal's site that helped you out?

 

Thanks,

 

Stefan

Share this post


Link to post
Share on other sites

You go to https://developer.paypal.com/ to create a new developer account.

 

Once you have logged in you go to 'Applications' -> 'Sandbox accounts', where you create new seller- and buyer-test-accounts.

 

After that you select the seller account and click on 'Enter Sandbox Site', where you login with the credentials of your test account.

 

Within the PayPal Sandbox you go to 'Merchant Services' and click on 'Create payment buttons for your website' and then 'Create a button'.

 

That leads you to the original html-form-generator. The rest works as described in the videos. 

 

Hope that helps.

Share this post


Link to post
Share on other sites

Hi, just curious -- is the current incarnation of the Paypal Shopping Cart tutorial up to date and relevant to PayPal's current API setup?  My impression is that the tutorial wasn't made recently (esp seeing as this thread is from 2014...) and just want to double check before I continue investing what has been a lot of time into it, that I will be learning an effective and up to date method of using the PayPal API.  Thank you!

Share this post


Link to post
Share on other sites

Hi,

You are right, there have been some changes to the API, so when you get to that point, you will have to change some of the code. But that accounts for about maybe .... 3-5% of the video content. As I say in the intro video for the projects, the projects are just bridging tutorials, to give you ideas on how to take the foundation code to projects. 

I figure, once you've done 1/2, you will feel comfortable using Paypal's docs on it. They come complete with PHP code samples on implementation. 

Hope that makes sense?

Stef

Share this post


Link to post
Share on other sites

If you were to build a full fledged e-commerce site with PHP, I would suggest doing the crud tutorial, the tag cloud, the simple and MVC login system, then do a Laravel walkthrough video.

Any modern PHP app of any consequence should be using an MVC framework like Laravel.

Stef

Share this post


Link to post
Share on other sites

Thanks for replying Stef.  At the risk of succumbing to what Charlie Munger described as 'Deprival Superreaction Tendency' (basically, refusing to cut your losses and move on),  I am going to continue and complete the course, since I'm almost done and have spent so much time with it already.  It seems like at least some of it is still relevant so far and I should be able to learn a thing or two about PayPal's API yet.  I'll check out the other courses you suggest.  Thanks again.   

Edited by brent

Share this post


Link to post
Share on other sites

Seems like the course is out of date again in December 2018. I've got as far as creating the sandbox accounts. Yet can't find the sample SDK to download as it's not on GitHub as the video shows. So came here looking for answers.

I shall persevere, because I need to get paypal up and running.

I too signed up mainly to learn paypal integration. 

Edited by DavidCampbell
gramar

Share this post


Link to post
Share on other sites

Hi,

Sorry for this particular course is in need of an update. I plan on addressing this in the new year. That said, once you get past the Paypal and PHP SDK, you should be good to go.

Stef

Share this post


Link to post
Share on other sites

No worries Stef, I'm on this vid right now "Steps to Submitting a Payment" and it is hard to find the equivalent area on developer.paypal.com in order to generate the JSON like the vid is doing. Yeah it really needs an update. 😄 I was hoping to wrap this course up. 

Anyway it's been good so far getting my head into this whole MVC with PHP. Up to now I've only used PHP procedurally.

I'll keep poking around and see if I can get this paypal sorted.
 

  • Like 1

Share this post


Link to post
Share on other sites

Actually this link here seems to be the most relevant so far: https://paypal.github.io/PayPal-PHP-SDK/sample/doc/payments/CreatePaymentUsingPayPal.html

Which is the top link on this page: https://paypal.github.io/PayPal-PHP-SDK/sample/

Seems to be an online version of the locally installed PayPal sample used in the tutorial.

https://github.com/paypal/PayPal-PHP-SDK/tree/master/sample

Edited by DavidCampbell
spelling and grammar

Share this post


Link to post
Share on other sites

 

Well I've kinda got it working, only it doesnt like me buying 10 TV's LOL. I can buy 2 headphones though, so not sure whats going with the quantity bug. 

This is the error I get:

Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Total is not a valid numeric value' in /Volumes/5TB_Seagate/htdocs/phpCart/app/vendor/paypal/rest-api-sdk-php/lib/PayPal/Validation/NumericValidator.php:23 Stack trace: #0 /Volumes/5TB_Seagate/htdocs/phpCart/app/vendor/paypal/rest-api-sdk-php/lib/PayPal/Api/Amount.php(54): PayPal\Validation\NumericValidator::validate('3,302.39', 'Total') #1 /Volumes/5TB_Seagate/htdocs/phpCart/app/models/m_payments.php(132): PayPal\Api\Amount->setTotal('3,302.39') #2 /Volumes/5TB_Seagate/htdocs/phpCart/checkout.php(31): Payments->create_payment(Array, Array) #3 {main} thrown in /Volumes/5TB_Seagate/htdocs/phpCart/app/vendor/paypal/rest-api-sdk-php/lib/PayPal/Validation/NumericValidator.php on line 23

 

Edited by DavidCampbell

Share this post


Link to post
Share on other sites

bug fixed:

here is my new checkout.php

 

<?php

include('app/init.php');


if(isset($_POST))
	{
	// create Payment Object
	include('app/models/m_payments.php');
	$Payments = new Payments();

	// get item data
	$items = $Cart->get();

	// get details
	$details['subtotal'] = $Cart->get_total_cost();
	$details['shipping'] = 0;

	foreach ($items as $item) 
		{
		$details['shipping'] += $Cart->get_shipping_cost($item['price']);
		}
	$details['shipping'] = number_format($details['shipping'], 2, '.', '');
	$details['tax'] = number_format($details['subtotal'] * SHOP_TAX, 2, '.', '');
	$details['total'] = number_format(
		$details['subtotal'] + 
		$details['shipping'] + 
		$details['tax'], 2, '.', '');

	// send to PayPal
	$error = $Payments->create_payment($items, $details);
	if ($error != NULL)
		{
		$Template->set_alert($error, 'error');
		$Template->redirect('cart.php');
		}

	}
else
	{
	$Template->redirect('cart.php');
	}

note the changes to number_format() where appropriate. 

  • Like 1

Share this post


Link to post
Share on other sites

Videos:

Composer Introduction & SDK Setup
PayPal Settings & Minor Changes
Steps to Submitting a Payment
Integrating PayPal Part 1
Integrating PayPal Part 2
Integrating PayPal Part 3
Integrating PayPal Part 4

On the whole the videos can be followed, but there are few red herrings on the way. And unnecessary distractions.

Composer Introduction & SDK Setup
Forget Composer, this is an unnecessary distraction and just confuses things, maybe mention Composer at the end of the tutorial as an alternative method for installing the SDK.

Get the SDK hosted on Github from here: https://github.com/paypal/PayPal-PHP-SDK/releases
I used the 1.13.0 zip (latest version) from this page and it works fine. To follow the videos you would rename the uncompressed SDK folder to 'vendor' and place it in the /app directory.

The 'samples' are slightly different. They are now hosted online here" https://paypal.github.io/PayPal-PHP-SDK/sample/

Only one sample is actually used in the tutorial, this one: https://paypal.github.io/PayPal-PHP-SDK/sample/doc/payments/CreatePaymentUsingPayPal.html
as you can see it looks virtually the same.

If you want to host the samples locally, you can still do that. Go to the main SDK repository on Github https://github.com/paypal/PayPal-PHP-SDK
you can see the samples directory is there. I did however have trouble downloading directly from here. For some reason when you hit the clone/download button and download from here the zip is missing files and directories you'd expect to be there, including the samples directory. I have no clue why this is. I managed to work around this problem by forking the repository and using the GitHub desktop app to clone my fork to my local drive. It was then fairly simple to drag the 'samples' directory out and host that with my MAMP/LAMP.

PayPal Settings & Minor Changes
Do the changes to init.php etc
Then the first step really is to goto https://developer.paypal.com/ log in and go to the dashboard (it all looks very different, but it's essentially doing the same job as before). Scroll down to REST API apps and create a new App. A client ID, secret and two test accounts (buyer and facilitator) are created automatically. Continue and make the changes to init.php, v_public_cart.php, success.php, v_public_success.php and m_payments.php etc. 

Steps to Submitting a Payment
This video is a bit confusing now, as the interactive guide is not the same. The vid really needs to be just a simple explanation of the steps used with paypal.

Integrating PayPal Part 1
Integrating PayPal Part 2
Integrating PayPal Part 3
Integrating PayPal Part 4
Once all the above is sorted you can follow these video's pretty much verbatim, only there are some subtle differences with the bootstrap.php file that you'll be copying from. It's easier to just look at my m_payments.php file:

<?php


/*
    Payments Class
    Handle all tasks related to payments
*/

require ('app/vendor/autoload.php');

use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;

use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
use PayPal\Api\PaymentExecution;

class Payments
    {
    private $api_context;

    function __construct() 
        {
        $this->api_context = $this->get_api_context();

        // echo '<pre>';
        // print_r($this->api_context);
        // echo '</pre>';
        // exit;
        }

    /*

        Getters and Setters

    */
    
    public function get_api_context()
        {

        if (PAYPAL_MODE == "sandbox")
            {
            $apiContext = new ApiContext(
                new OAuthTokenCredential
                    (
                    PAYPAL_DEVID,
                    PAYPAL_DEVSECRET
                    )
                );  
            }
        else
            {
            $apiContext = new ApiContext(
                new OAuthTokenCredential
                    (
                    PAYPAL_LIVEID,
                    PAYPAL_LIVESECRET
                    )
                );  
            }

        $apiContext->setConfig(array
            (
            'mode' => PAYPAL_MODE,
            'http.ConnectionTimeOut' => 30,
            'log.LogEnabled' => true,
            'log.FileName' => 'app/PayPal.log',
            'log.LogLevel' => 'FINE'
            ));

        return $apiContext;
        }

    /**
     * Creates PayPal payment:
     *
     * @access public
     * @param 
     * @return error string
     **/
    public function create_payment($items_array, $details_array)
        {
        $payer = new Payer();
        $payer->setPaymentMethod("paypal");

        // set items
        $i = 0;
        foreach ($items_array as $item) 
            {   
            $items[$i] = new Item();
            $items[$i]
                ->setName($item['name'])
                ->setCurrency(PAYPAL_CURRENCY)
                ->setQuantity($item['quantity'])
                ->setSku("123123" . $i)
                ->setPrice($item['price']);

            $i++;
            }

        $itemList = new ItemList();
        $itemList->setItems($items);

        // set details
        $details = new Details();
        $details
            ->setShipping($details_array['shipping'])
            ->setTax($details_array['tax'])
            ->setSubtotal($details_array['subtotal']);

        // set amount
        $amount = new Amount();
        $amount
            ->setCurrency(PAYPAL_CURRENCY)
            ->setTotal($details_array['total'])
            ->setDetails($details);

        // set transaction
        $transaction = new Transaction();
        $transaction
            ->setAmount($amount)
            ->setItemList($itemList)
            ->setDescription("")
            ->setInvoiceNumber(uniqid());
          
        // create urls
        $redirectUrls = new RedirectUrls();
        $redirectUrls
            ->setReturnUrl(SITE_PATH . "success.php")
            ->setCancelUrl(SITE_PATH . "cart.php");

        // create payment
        $payment = new Payment();
        $payment
            ->setIntent("sale")
            ->setPayer($payer)
            ->setRedirectUrls($redirectUrls)
            ->setTransactions(array($transaction));

        try 
            {
            $payment->create($this->api_context);
            } 
        catch (Exception $ex) 
            {   
            // echo '<pre>';
            // print_r($ex->getData());
            // echo '</pre>';
            // exit;

            return $ex->getMessage();
            }

        // get redirect url
        $approvalUrl = $payment->getApprovalLink();

        $_SESSION['payment_id'] = $payment->getId();
        if (isset($approvalUrl))
            {
            header("Location: $approvalUrl");
            exit;
            }
        }

    /**
     * Executes PayPal payment:
     *
     * @access public
     * @param string, string
     * @return result object
     **/
    public function execute_payment($payer_id, $payment_id)
        {
        $payment = Payment::get($payment_id, $this->api_context);

        $execution = new PaymentExecution();
        $execution->setPayerId($payer_id);
        $result = $payment->execute($execution, $this->api_context);

        return $result;
        }
    }

As you can see it's almost the same, just some subtle difference at the bottom with the re-directs and the try/catch.

I did have to fix that bug that was a result of a comma being in the amount (see earlier post for the fix).

Anyway I think that was everything. 

 

Dave
 

Edited by DavidCampbell

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×