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

WBOY
WBOYOriginal
2016-07-12 09:08:351304browse

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>

  • 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>

    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>
  • 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>}");

    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> '支付成功!感谢支持!';

    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:
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