PHP Language Development PayPal Payment demo specific implementation

Source: Internet
Author: User
Tags php language paypal php composer install

If our application is international-oriented, then we usually consider using PayPal when paying. The following is an example of a PayPal payment written by a person, which has been pro-tested. PayPal has a very good place to provide a sandbox (sandbox) testing capabilities for developers. (that is, for developers to provide a virtual seller account and amount in the development environment, as well as a virtual buyer account and amount, virtual card number, etc.) Allows us to not use real money for testing. ) I. Preparation BEFORE development
    • https://developer.paypal.com/to PayPal's developer website to register the developer account.
    • After logging in with your account, click on the dashboard above and enter the dashboard panel. The following operations are done in this panel.
    • In the above menu sandbox below the accounts inside can see your sandbox test buyer account and seller account. 2 test accounts have the profile option inside the ChangePassword can set the virtual account password.
    • The transactions in the top menu sandbox is your transaction history.
    • Click the Create app button in the top right corner of the page. Create an app. Once created, you will be provided with a client ID and Secret. Both of these can be configured as PHP constants that are used later in development.
Second, enter the payment demo development
  • Create a local code root directory, create a index.html inside to put a simple product name and product price two input items can, code and the following:
  • <!DOCTYPE HTML><HTMLLang= "en">    <Head>        <MetaCharSet= "Utf-8">        <title>Payment Page</title>    </Head>    <Body>        <Div>            <formAction= "checkout.php"Method= "POST"AutoComplete= "Off">                <label for= "Item">Product Name<inputtype= "text"name= "Product">                </label>                <BR>                <label for= "Amount">Price<inputtype= "text"name= "Price">                </label>                <BR>                <inputtype= "Submit"value= "Go to pay">            </form>        </Div>    </Body></HTML>

  • Enter the product name and price. Click to pay will go to PayPal's payment page. Use your sandbox to test your buyer's account to pay. You will find that the payment was successful. Then log in to your test seller account. will find the seller account has received payment. Of course, this will deduct the fees charged by PayPal. The charges are for the sellers.
  • Here's a look at how PHP is implemented. First of all, the PayPal provided by the PHP-SDK to get your code directory. Here you will find the latest SDK using PHP's Package Manager composer, and of course you can get the latest PayPal php-sdk from other sources such as GitHub.
  • By default, your computer has composer installed. If you do not go to the Niang or Google under composer installation.
  • Then write a Composer.json file in your code root directory to get the package contents. The JSON file code is as follows:
    {    "require": {        "paypal/rest-api-sdk-php": "1.5.1"    }}

    If this is the Linux/unix system, execute the composer install directly from the root directory to get the package contents.

  • After the installation is done. A vendor directory will be generated under the root directory. There are two sub-directories of composer and PayPal. Composer inside the automatic loading, PayPal is your SDK content.
  • Next we write a public file (here by default with app/start.php, your project can be customized), in fact, just implement the SDK autoload.php automatically loaded and created just above the client ID and Secret the generated PayPal payment object instance. The start.php code is as follows:
  • <? PHP require // loading the SDK's auto-load file Define // site URL self-defined//Create a Payment object instance $paypal New \paypal\rest\apicontext (    new  \paypal\auth\oauthtokencredential (        ' Your client ID '        your secret ')    ;
  • The next step is to implement the processing file checkout.php submitted in the form. The code reads as follows:
  • <?PHP/** * @author xxxxxxxx * @brief profile: * @date 15/9/2 * @time afternoon 5:00pm*/ Use\paypal\api\payer; Use\paypal\api\item; Use\paypal\api\itemlist; Use\paypal\api\details; Use\paypal\api\amount; Use\paypal\api\transaction; Use\paypal\api\redirecturls; Use\paypal\api\payment; Use\paypal\Exception\paypalconnectionexception;require"App/start.php";if(!isset($_post[' Product '],$_post[' Price '])) {     die("Lose Some params");}$product=$_post[' Product '];$price=$_post[' Price '];$shipping= 2.00;//Shipping$total=$price+$shipping;$payer=Newpayer ();$payer->setpaymentmethod (' PayPal ');$item=NewItem ();$item->setname ($product)    ->setcurrency (' USD ')    ->setquantity (1)    ->setprice ($price);$itemList=NewItemList ();$itemList->setitems ([$item]);$details=NewDetails ();$details->setshipping ($shipping)    ->setsubtotal ($price);$amount=NewAmount ();$amount->setcurrency (' USD ')    ->settotal ($total)    ->setdetails ($details);$transaction=NewTransaction ();$transaction->setamount ($amount)    ->setitemlist ($itemList)    ->setdescription ("Payment description")    ->setinvoicenumber (uniqid());$redirectUrls=Newredirecturls ();$redirectUrls->setreturnurl (Site_url. '/pay.php?success=true ')    ->setcancelurl (Site_url. '/pay.php?success=false ');$payment=NewPayment ();$payment->setintent (' Sale ')    ->setpayer ($payer)    ->setredirecturls ($redirectUrls)    ->settransactions ([$transaction]);Try {    $payment->create ($paypal);} Catch(paypalconnectionexception$e) {    Echo $e-GetData ();  die();}$APPROVALURL=$payment-Getapprovallink ();Header("Location: {$APPROVALURL}");

    Checkout.php the payment details and parameters are initialized and set by the parameters of the form submission. Only the usual sections are listed here. PayPal offers a number of parameter settings. More specific, you can refer to the official PayPal developer documentation.

  • checkout.php after the parameters have been set. A payment link is generated. Use the header to jump to this payment link (that is, PayPal's payment page) to this payment page can be used in your sandbox to provide the buyer account to pay. As follows:
  • After payment with buyer account is completed. Check out the merchant account balance in your sandbox. You will find that you have received the money deducted from the handling fee.
  • There is a callback after the payment succeeds or fails. The callback processing PHP file is then set up in the checkout.php inside the Setreturnurl. The/pay.php?success=true is set here.
  • Let's take a look at how pay.php handles callbacks simply. Put the pay.php code first:
  • <?PHPrequire' App/start.php '; Usepaypal\api\payment; Usepaypal\api\paymentexecution;if(!isset($_get[' Success '],$_get[' Paymentid '],$_get[' Payerid '])){     die();}if((BOOL)$_get[' Success ']=== ' false '){    Echo' Transaction cancelled! ';  die();}$paymentID=$_get[' Paymentid '];$payerId=$_get[' Payerid '];$payment= Payment::get ($paymentID,$paypal);$execute=Newpaymentexecution ();$execute->setpayerid ($payerId);Try{    $result=$payment->execute ($execute,$paypal);}Catch(Exception $e){     die($e);}Echo' Payment is successful! Thanks for the support! ';

    All right. Here a simple PayPal payment demo has actually gone through. After you know the payment principle and want to enrich your own project, go to PayPal's official documentation to see more specific development settings. Including the transaction details of the acquisition, etc. are achievable. It's not going to be any more specific here.

The demo in this article was passed in 2015-9-2 using the latest PayPal PHP-SDK version 1.5.1 test. It may be slightly different if the SDK versions are far apart. The borrower's own reference can be! I hope to have just wanted to develop PayPal payment, do not have to start the people to bring a little help!

PHP Language Development PayPal Payment demo specific implementation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.