Table of Contents
The specific implementation of Paypal payment demo developed in PHP language, phppaypal payment demo
If our application is for international applications, we usually consider using paypal when making payments. The following is a PayPal payment example written by an individual, which has been personally tested and is feasible. A very good thing about PayPal is that it provides developers with a sandbox testing function. (That is, it provides developers with a virtual seller account and amount, a virtual buyer account and amount, virtual card number, etc. in the development environment. This allows us to test without using real money.)
1. Preparation before development
2. Enter payment demo development
The demo in this article was tested on 2015-9-2 using the latest paypal php-sdk version 1.5.1. If the SDK versions are far apart, there may be slight differences.
Borrowers can just use it for reference! I hope it can bring some help to those who just want to develop PayPal payment but really have no idea where to start!
Home Backend Development PHP Tutorial Specific implementation of Paypal payment demo developed in PHP language, phppaypal payment demo_PHP tutorial

Specific implementation of Paypal payment demo developed in PHP language, phppaypal payment demo_PHP tutorial

Jul 12, 2016 am 09:08 AM
paypal

The specific implementation of Paypal payment demo developed in PHP language, phppaypal payment demo

If our application is for international applications, we usually consider using paypal when making payments. The following is a PayPal payment example written by an individual, which has been personally tested and is feasible. A very good thing about PayPal is that it provides developers with a sandbox testing function. (That is, it provides developers with a virtual seller account and amount, a virtual buyer account and amount, virtual card number, etc. in the development environment. This allows us to test without using real money.)

1. Preparation before development

  • https://developer.paypal.com/ Go to the official developer website of paypal to register a developer account.
  • After logging in with your account, click dashboard on the navigation to enter the dashboard. As shown in the screenshot below, subsequent operations are performed in this panel.
  • You can see the buyer account and seller account of your sandbox test in Accounts under the menu Sandbox in the screenshot above. Both test accounts have a profile option with changepassword to set the password for the virtual account.
  • Transactions under the menu Sandbox in the screenshot above is your transaction record.
  • Click the Create App button in the upper right corner of the screenshot page. Create an app. After creation, you will be provided with a Client ID and Secret. These two can be configured as PHP constants and will be used in later development.

2. Enter payment demo development

  • Create a development code root directory locally. First create an index.html and put two simple input items: product name and product price. The code and screenshots are as follows:
  • <span><!</span><span>DOCTYPE html</span><span>></span>
    <span><</span><span>html </span><span>lang</span><span>="en"</span><span>></span>
        <span><</span><span>head</span><span>></span>
            <span><</span><span>meta </span><span>charset</span><span>="utf-8"</span><span>></span>
            <span><</span><span>title</span><span>></span>支付页面<span></</span><span>title</span><span>></span>
        <span></</span><span>head</span><span>></span>
        <span><</span><span>body</span><span>></span>
            <span><</span><span>div</span><span>></span>
                <span><</span><span>form </span><span>action</span><span>="checkout.php"</span><span> method</span><span>="post"</span><span> autocomplete</span><span>="off"</span><span>></span>
                    <span><</span><span>label </span><span>for</span><span>="item"</span><span>></span><span>
                        产品名称
                        </span><span><</span><span>input </span><span>type</span><span>="text"</span><span> name</span><span>="product"</span><span>></span>
                    <span></</span><span>label</span><span>></span>
                    <span><</span><span>br</span><span>></span>
                    <span><</span><span>label </span><span>for</span><span>="amount"</span><span>></span><span>
                        价格
                        </span><span><</span><span>input </span><span>type</span><span>="text"</span><span> name</span><span>="price"</span><span>></span>
                    <span></</span><span>label</span><span>></span>
                    <span><</span><span>br</span><span>></span>
                    <span><</span><span>input </span><span>type</span><span>="submit"</span><span> value</span><span>="去付款"</span><span>></span>
                <span></</span><span>form</span><span>></span>
            <span></</span><span>div</span><span>></span>
        <span></</span><span>body</span><span>></span>
    <span></</span><span>html</span><span>></span>
    Copy after login

  • Enter product name and price. Click to pay and you will go to the paypal payment page. Use your sandbox test buyer account to pay. You will find that the payment is successful. Then log in to your test seller account. You will find that the seller's account has received payment. Of course, the handling fee charged by Paypal will be deducted here. The handling fee is charged by the seller.
  • Let’s take a closer look at how php is implemented. First, you need to get the php-sdk provided by paypal into your code directory. Here we introduce how to use PHP's package manager composer to obtain the latest SDK. Of course, you can obtain the latest paypal PHP-SDK from other channels such as github.
  • Composer is already installed on your computer by default. If you don’t have it, go to Du Niang or google to install it with composer.
  • Then write a composer.json file in your code root directory to get the package content. The json file code is as follows:
    <span>{
        </span>"require" :<span> {
            </span>"paypal/rest-api-sdk-php" : "1.5.1"<span>
        }
    }</span>
    Copy after login

    If this is a linux/unix system, just execute composer install directly in the root directory to obtain the package content.

  • After installation. A vendor directory will be generated under the root directory. There are two subdirectories: composer and paypal. Composer implements automatic loading, and paypal is your sdk content.
  • Next, let’s write a public file (app/start.php is used by default here, you can customize it in your project). In fact, it just implements the autoload.php of sdk to automatically load and create the client mentioned above. Paypal payment object instance generated by id and secret. The start.php code is as follows:
  • <?<span>php
    </span><span>require</span> "vendor/autoload.php"; <span>//</span><span>载入sdk的自动加载文件</span>
    <span>define</span>('SITE_URL', 'http://www.paydemo.com'); <span>//</span><span>网站url自行定义
    //创建支付对象实例</span>
    <span>$paypal</span> = <span>new</span><span> \PayPal\Rest\ApiContext(
        </span><span>new</span><span> \PayPal\Auth\OAuthTokenCredential(
            </span>'你的Client ID'
            '你的secret'<span>
        )
    );</span>
    Copy after login
  • The next step is to implement the processing file checkout.php submitted in the form. The code content is as follows:
  • <?<span>php
    </span><span>/*</span><span>*
     * @author xxxxxxxx
     * @brief 简介:
     * @date 15/9/2
     * @time 下午5:00
     </span><span>*/</span>
    <span>use</span><span> \PayPal\Api\Payer;
    </span><span>use</span><span> \PayPal\Api\Item;
    </span><span>use</span><span> \PayPal\Api\ItemList;
    </span><span>use</span><span> \PayPal\Api\Details;
    </span><span>use</span><span> \PayPal\Api\Amount;
    </span><span>use</span><span> \PayPal\Api\Transaction;
    </span><span>use</span><span> \PayPal\Api\RedirectUrls;
    </span><span>use</span><span> \PayPal\Api\Payment;
    </span><span>use</span> \PayPal\<span>Exception</span><span>\PayPalConnectionException;
    
    </span><span>require</span> "app/start.php"<span>;
    </span><span>if</span> (!<span>isset</span>(<span>$_POST</span>['product'], <span>$_POST</span>['price'<span>])) {
        </span><span>die</span>("lose some params"<span>);
    }
    </span><span>$product</span> = <span>$_POST</span>['product'<span>];
    </span><span>$price</span> = <span>$_POST</span>['price'<span>];
    </span><span>$shipping</span> = 2.00; <span>//</span><span>运费</span>
    
    <span>$total</span> = <span>$price</span> + <span>$shipping</span><span>;
    
    </span><span>$payer</span> = <span>new</span><span> Payer();
    </span><span>$payer</span>->setPaymentMethod('paypal'<span>);
    
    </span><span>$item</span> = <span>new</span><span> Item();
    </span><span>$item</span>->setName(<span>$product</span><span>)
        </span>->setCurrency('USD'<span>)
        </span>->setQuantity(1<span>)
        </span>->setPrice(<span>$price</span><span>);
    
    </span><span>$itemList</span> = <span>new</span><span> ItemList();
    </span><span>$itemList</span>->setItems([<span>$item</span><span>]);
    
    </span><span>$details</span> = <span>new</span><span> Details();
    </span><span>$details</span>->setShipping(<span>$shipping</span><span>)
        </span>->setSubtotal(<span>$price</span><span>);
    
    </span><span>$amount</span> = <span>new</span><span> Amount();
    </span><span>$amount</span>->setCurrency('USD'<span>)
        </span>->setTotal(<span>$total</span><span>)
        </span>->setDetails(<span>$details</span><span>);
    
    </span><span>$transaction</span> = <span>new</span><span> Transaction();
    </span><span>$transaction</span>->setAmount(<span>$amount</span><span>)
        </span>->setItemList(<span>$itemList</span><span>)
        </span>->setDescription("支付描述内容"<span>)
        </span>->setInvoiceNumber(<span>uniqid</span><span>());
    
    </span><span>$redirectUrls</span> = <span>new</span><span> RedirectUrls();
    </span><span>$redirectUrls</span>->setReturnUrl(SITE_URL . '/pay.php?success=true'<span>)
        </span>->setCancelUrl(SITE_URL . '/pay.php?success=false'<span>);
    
    </span><span>$payment</span> = <span>new</span><span> Payment();
    </span><span>$payment</span>->setIntent('sale'<span>)
        </span>->setPayer(<span>$payer</span><span>)
        </span>->setRedirectUrls(<span>$redirectUrls</span><span>)
        </span>->setTransactions([<span>$transaction</span><span>]);
    
    </span><span>try</span><span> {
        </span><span>$payment</span>->create(<span>$paypal</span><span>);
    } </span><span>catch</span> (PayPalConnectionException <span>$e</span><span>) {
        </span><span>echo</span> <span>$e</span>-><span>getData();
        </span><span>die</span><span>();
    }
    
    </span><span>$approvalUrl</span> = <span>$payment</span>-><span>getApprovalLink();
    </span><span>header</span>("Location: {<span>$approvalUrl</span>}");
    Copy after login

    checkout.php initializes and sets the specific payment details and parameters through the parameters submitted through the form. Only the commonly used parts are listed here. PayPal provides many parameter settings. For more details, you can refer to Paypal's official developer documentation.

  • After checkout.php sets the parameters. A payment link will be generated. Use the header to jump to the payment link (that is, the payment page of Paypal). When you go to the payment page, you can use the buyer account provided by your sandbox to pay. The screenshot is as follows:
  • After the payment is completed using the buyer account. Go check the merchant account balance of your sandbox. You will find that you have received the money minus the handling fee.
  • There is a callback processing after the payment is successful or failed. The php file for callback processing is set at setReturnUrl in checkout.php above. What is set here is /pay.php?success=true
  • Next let’s take a look at how pay.php simply handles callbacks. First paste the pay.php code:
  • <?<span>php
    
    </span><span>require</span> 'app/start.php'<span>;
    
    </span><span>use</span><span> PayPal\Api\Payment;
    </span><span>use</span><span> PayPal\Api\PaymentExecution;
    
    </span><span>if</span>(!<span>isset</span>(<span>$_GET</span>['success'], <span>$_GET</span>['paymentId'], <span>$_GET</span>['PayerID'<span>])){
        </span><span>die</span><span>();
    }
    
    </span><span>if</span>((bool)<span>$_GET</span>['success']=== 'false'<span>){
    
        </span><span>echo</span> 'Transaction cancelled!'<span>;
        </span><span>die</span><span>();
    }
    
    </span><span>$paymentID</span> = <span>$_GET</span>['paymentId'<span>];
    </span><span>$payerId</span> = <span>$_GET</span>['PayerID'<span>];
    
    </span><span>$payment</span> = Payment::get(<span>$paymentID</span>, <span>$paypal</span><span>);
    
    </span><span>$execute</span> = <span>new</span><span> PaymentExecution();
    </span><span>$execute</span>->setPayerId(<span>$payerId</span><span>);
    
    </span><span>try</span><span>{
        </span><span>$result</span> = <span>$payment</span>->execute(<span>$execute</span>, <span>$paypal</span><span>);
    }</span><span>catch</span>(<span>Exception</span> <span>$e</span><span>){
        </span><span>die</span>(<span>$e</span><span>);
    }
    </span><span>echo</span> '支付成功!感谢支持!';
    Copy after login

    Okay. At this point, a simple PayPal payment demo has actually worked. After understanding the payment principle, if you want to make richer extensions in your own project, go to Paypal's official documentation to view more specific development project settings. Including the acquisition of transaction details, etc. are all achievable. I won’t go into details here.

The demo in this article was tested on 2015-9-2 using the latest paypal php-sdk version 1.5.1. If the SDK versions are far apart, there may be slight differences.

Borrowers can just use it for reference! I hope it can bring some help to those who just want to develop PayPal payment but really have no idea where to start!

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1054178.htmlTechArticleThe specific implementation of Paypal payment demo developed in PHP language, phppaypal payment demo If our application is for international, then payment I usually consider using paypal. The following is written by an individual...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Online payments using PHP and PayPal Online payments using PHP and PayPal May 11, 2023 pm 03:37 PM

With the rapid development of the Internet, more and more companies choose to sell products and services online, which makes online payment a major need for companies. As the world's leading online payment platform, PayPal has also become the first choice for many companies. This article will introduce how to use PHP and PayPal to implement online payments. We will divide it into the following steps: Create a PayPal account and application Integrate PayPalSDK Obtain payment Token Processing Payment processing Payment confirmation Create a PayPal account and application To use P

What is the reason why paypal cannot pay? What is the reason why paypal cannot pay? Sep 01, 2023 pm 05:00 PM

The reasons why PayPal cannot pay are due to insufficient account balance, payment method restrictions, transactions intercepted by the risk control system, payee account problems, network connection problems, and user account abnormalities, etc. Detailed introduction: 1. If the account balance is insufficient, you can increase the account balance through bank transfer or credit card recharge; 2. The payment method is restricted, check the payment settings and ensure that the selected payment method is not restricted; 3. The transaction is intercepted by the risk control system , contact PayPal customer service, provide relevant information to prove the legitimacy of the transaction, and request to lift payment restrictions, etc.

GCash launches PayPal's stable coin, allowing Filipinos to trade cryptocurrency protected from price volatility GCash launches PayPal's stable coin, allowing Filipinos to trade cryptocurrency protected from price volatility Jul 31, 2024 am 06:36 AM

GCash on Tuesday said PayPal USD (PYUSD) tokens could now be traded via GCrypto, an in-app feature powered by the Philippine Digital Asset Exchange, at “low transaction fees.”

What is the reason why paypal cannot pay? What is the reason why paypal cannot pay? Oct 16, 2023 pm 03:23 PM

The inability to pay with Paypal is caused by problems with payment methods, account balances, Paypal balances, payment information, network problems, Paypal systems, merchants, and browsers. Detailed introduction: 1. Payment method, please make sure that the payment method used has been added to the Paypal account; 2. Account balance, ensure that the Paypal account balance is sufficient to pay the order amount; 3. Paypal balance, check the account status to see if there are any abnormalities; 4. Payment information, make sure the payment information entered is correct, such as credit card number, expiration date, etc.

Do Europeans use paypal? Do Europeans use paypal? Nov 10, 2022 am 10:52 AM

Europeans use PayPal, but it is not universal and can only be used in areas where it is opened; PayPal is an online payment service provider headquartered in San Jose, California, USA; PayPal account is a secure online electronic account launched by PayPal. Use It can effectively reduce the occurrence of online fraud; the advanced management functions integrated into the PayPal account can control the details of every transaction.

paypal official app download paypal official app download Apr 23, 2024 am 10:00 AM

To download the PayPal official app, please visit the PayPal official website: https://www.paypal.com/ Click "Download", select the appropriate app store according to your device, search for "PayPal", download and install, and finally log in Your PayPal account. The app allows you to easily manage your account, stay secure, track spending, make payments seamlessly, and is available for iOS and Android devices.

Paypal's PYUSD Nears $1B Milestone Paypal's PYUSD Nears $1B Milestone Aug 17, 2024 am 06:10 AM

The stablecoin asset issued by Paypal is now the sixth largest stablecoin asset today after growing significantly over the past ten days.

PayPal joins forces with Apple's Tap to Pay to enable contact-free iPhone payments for millions of U.S. small businesses PayPal joins forces with Apple's Tap to Pay to enable contact-free iPhone payments for millions of U.S. small businesses Apr 10, 2024 pm 12:10 PM

According to news on March 8, PayPal Holdings Inc. recently issued an announcement announcing that millions of U.S. small businesses, all of which are users of Venmo and PayPal Zettle, now do not require any additional hardware such as expansion accessories or Bluetooth card readers. By supporting Apple's TaptoPay function, you can achieve contact-free payment with just an iPhone. Apple's TaptoPay feature, launched in May 2022, allows U.S. merchants to accept ApplePay and other contactless payment methods using iPhones and merchant-supported iOS apps. Through this service, users with compatible iPhone devices are able to securely process contactless payments as well as those with enabled

See all articles