Multi Items Payment with PayPal REST API (PHP)

    Rating: ★★★★☆
    View: 131
    Download: 88
    Từ khóa:

    Yes PayPal allows people to pay for your products directly using credit cards, which requires absolutely no user sign-in or sign-ups with PayPal.

    Before we begin get your Client Id and Client Secret from developer.paypal.comaccount for sandbox testing. Or to sell your products live, you will need Client Idand Client Secret from Paypal.com

    In my previous post, I had created four files, but here I’ve add two more file calledpayment_option.php and config.php. payment_option.php file allows customer to choose Payment method, which is either PayPal or Credit Card, and you can guess what config.php is all about.

    1. config.php – Stores information needed by the application.
    2. Index.php – (Products page) contains list of products for sale.
    3. Payment_option.php – Allows customer to choose payment method
    4. Order_process.php – Processes PayPal payment.
    5. Functions.inc.php – Helper script, contains functions needed for processing.
    6. Payment_cancel.html – PayPal redirects user to this page in-case of cancellation.

    Products Page

    Let’s talk about product page (Index.php) a bit, as you can see in PHP code below, I have listed the products stored in database, each item contains a quantity field and a checkbox. User selects the item he wants to buy, selects the quantity and these information will be posted to payment_option.php.

    query("SELECT id, product_code, product_name, product_price, image_name FROM my_products");
    
    //wrap with form tag
    print   '
    '; print '
      '; //list products from database while($row = $results->fetch_object()) { print '
    • '; print ''; print '
      ' . $row->product_name . '
      '; print '
      '; print 'Qty:'; print ' '; print ''; print '
      '; print '
    • '; } print '
    '; print '
    '; print ''; print '
    '; print '
    '; ?>

    Payment Method Selection

    When a user is redirected to this page along with item ids and quantity, we need to make sure selected items exist in database, then we can fetch prices and product codes from database and construct a collection of items array in $_SESSION["items"], which we will use in order_process.php.

    query("SELECT product_code, product_name, product_price FROM my_products WHERE id IN (".$item_codes.")");
        if($results->num_rows){
            $item_total = 0;
            while($row = $results->fetch_object()){
                //item quantity
                $item_quantity = ( isset( $_POST[$row->product_code."_qty"] ) && is_numeric( $_POST[$row->product_code."_qty"] ) ) ? $_POST[$row->product_code."_qty"] : 1;
                
                //add item array to $items variable, it will be used in order_process.php
                $items[] = array(
                                'name' => $row->product_name, 
                                'quantity' => $item_quantity, 
                                'price' => $row->product_price, 
                                'sku' => $row->product_code, 
                                'currency' => PP_CURRENCY
                                );
                //calculate total price of all items        
                $item_total = $item_total + ($row->product_price * $item_quantity);
            }
        }else{
            die("Selected item(s) not found in database!");
        }
        
        //Set session variables of items and total price for later use.
        $_SESSION["items"] = $items;
        $_SESSION["items_total"] = $item_total;
                                            
    }else{
        die("Please select atlease 1 product");
    }
    ?>

    If everything looks good, it’s time to display Payment Option page to user. As you can see I have two HTML forms here, first one is for PayPal Payment method, and second HTML form is for credit card Payment method, it contains all the fields required for credit card information.

    Select a Payment Method.

    You may be wondering, why show two forms to customer? he will get confused! Well the solution is pretty simple, we will just use jQuery here, and we hide/show credit card form when customer selects a payment method. You might want to use some credit card validation script here to make things more solid.

     

    Order Processes

    Order process is actually pretty straight forward if you examine the code carefully. I have really tried hard to make it look less complicated, I just hope it doesn’t take you too much time to understand the whole process.
    Here’s the sample flow of order_process.php.

    //we have user payment method and session items
    if(isset($_POST["payment_method"]) && isset($_SESSION["items"])){
        try{ 
            if($_POST["payment_method"] == "paypal"){
                //redirect to paypal with items and prices
            }
            if($_POST["payment_method"] == "credit_card"){
                //pay using credit card, no paypal redirection required
                //set $_SESSION["results"] and redirect user back to this page
            }
        }catch(PPConnectionException $ex){
            //show errors
        }
    }
    
    
    if(isset($_GET["token"]) && isset($_GET["PayerID"]) && isset($_SESSION["payment_id"])){
        //if PayPal payment method was used, paypal redirects back to this page with PayerID and Payment ID
        //execute payment using PayerID and Payment ID
        //set $_SESSION["results"] and redirect user back to this page
    }
    
    if(isset($_SESSION["results"]))
    {
        //If results session was set in actions above, display results set in session.
    }

    And here’s the whole code, just take your time to read each comment line to understand it more clearly.

    state == "created" && $result->payer->payment_method == "paypal"){
                    $_SESSION["payment_id"] = $result->id; //set payment id for later use, we need this to execute payment
                    unset($_SESSION["items"]); //unset item session, not required anymore.
                    unset($_SESSION["items_total"]); //unset items_total session, not required anymore.
                    header("location: ". $result->links[1]->href); //after success redirect user to approval URL 
                    exit();
                }
            
            }
            
            ######## if payment method is Credit Card ##############    
            if($_POST["payment_method"] == "credit_card"){
                $credit_card = array(
                                    'type'=> $cc_card_type, 
                                    'number' => $cc_card_number, 
                                    'expire_month'=>$cc_card_month, 
                                    'expire_year'=>$cc_card_year, 
                                    'cvv2'=>$cc_card_cvv2,
                                    'first_name'=>$cc_first_name,
                                    'last_name'=>$cc_last_name
                                    );
                                        
                //pay directly using credit card information.
                $result = pay_direct_with_credit_card($credit_card, PP_CURRENCY , $total_amount, $items, '') ;      
                    
                    //If credit card payment is succesful, get results
                    if($result->state == "approved" && $result->payer->payment_method == "credit_card"){
                        unset($_SESSION["items"]); //unset item session, not required anymore.
                        unset($_SESSION["items_total"]); //unset items_total session, not required anymore.
            
                        //get transaction details
                        $transaction_id         = $result->transactions[0]->related_resources[0]->sale->id;
                        $transaction_time       = $result->transactions[0]->related_resources[0]->sale->create_time;
                        $transaction_currency   = $result->transactions[0]->related_resources[0]->sale->amount->currency;
                        $transaction_amount     = $result->transactions[0]->related_resources[0]->sale->amount->total;
                        $transaction_method     = $result->payer->payment_method;
                        $transaction_state      = $result->transactions[0]->related_resources[0]->sale->state;
                        
                        //get payer details
                        $payer_first_name       = $result->payer->payer_info->first_name;
                        $payer_last_name        = $result->payer->payer_info->last_name;
                        $payer_email            = $result->payer->payer_info->email;
                        $payer_id               = $result->payer->payer_info->payer_id;
                        
                        //get shipping details 
                        $shipping_recipient     = $result->transactions[0]->item_list->shipping_address->recipient_name;
                        $shipping_line1         = $result->transactions[0]->item_list->shipping_address->line1;
                        $shipping_line2         = $result->transactions[0]->item_list->shipping_address->line2;
                        $shipping_city          = $result->transactions[0]->item_list->shipping_address->city;
                        $shipping_state         = $result->transactions[0]->item_list->shipping_address->state;
                        $shipping_postal_code   = $result->transactions[0]->item_list->shipping_address->postal_code;
                        $shipping_country_code  = $result->transactions[0]->item_list->shipping_address->country_code;
    
                        //insert into database         
                        $insert_row = $mysqli->query("INSERT INTO my_orders (transaction_id, transaction_currency, transaction_amount, transaction_method, transaction_state)
                                VALUES ('$transaction_id', '$transaction_currency', '$transaction_amount', '$transaction_method', '$transaction_state')");
        
                        //set $_SESSION["results"] session, print_r($result); to see what is returned
                        $_SESSION["results"]  = array(
                                'transaction_id' => $transaction_id, 
                                'transaction_time' => $transaction_time,
                                'transaction_currency' => $transaction_currency,
                                'transaction_amount' => $transaction_amount,
                                'transaction_method' => $transaction_method,
                                'transaction_state' => $transaction_state
                                );
                                    
                        header("location: ". RETURN_URL); //$_SESSION["results"] is set, redirect back to order_process.php
                        exit();
                    }
            }
    
        }catch(PPConnectionException $ex) {
            echo parseApiError($ex->getData());
        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
    
    }
    
    
    ### If Payment method was PayPal, user is redirected back to this page with token and Payer ID ###
    if(isset($_GET["token"]) && isset($_GET["PayerID"]) && isset($_SESSION["payment_id"])){
        try{
            $result = execute_payment($_SESSION["payment_id"], $_GET["PayerID"]);  //call execute payment function.
    
            if($result->state == "approved"){ //if state = approved continue..
                //SUCESS
                
                unset($_SESSION["payment_id"]); //unset payment_id, it is no longer needed 
                
                //get transaction details
                $transaction_id         = $result->transactions[0]->related_resources[0]->sale->id;
                $transaction_time       = $result->transactions[0]->related_resources[0]->sale->create_time;
                $transaction_currency   = $result->transactions[0]->related_resources[0]->sale->amount->currency;
                $transaction_amount     = $result->transactions[0]->related_resources[0]->sale->amount->total;
                $transaction_method     = $result->payer->payment_method;
                $transaction_state      = $result->transactions[0]->related_resources[0]->sale->state;
                
                //get payer details
                $payer_first_name       = $result->payer->payer_info->first_name;
                $payer_last_name        = $result->payer->payer_info->last_name;
                $payer_email            = $result->payer->payer_info->email;
                $payer_id               = $result->payer->payer_info->payer_id;
                
                //get shipping details 
                $shipping_recipient     = $result->transactions[0]->item_list->shipping_address->recipient_name;
                $shipping_line1         = $result->transactions[0]->item_list->shipping_address->line1;
                $shipping_line2         = $result->transactions[0]->item_list->shipping_address->line2;
                $shipping_city          = $result->transactions[0]->item_list->shipping_address->city;
                $shipping_state         = $result->transactions[0]->item_list->shipping_address->state;
                $shipping_postal_code   = $result->transactions[0]->item_list->shipping_address->postal_code;
                $shipping_country_code  = $result->transactions[0]->item_list->shipping_address->country_code;
                            
                //insert into database         
                $insert_row = $mysqli->query("INSERT INTO my_orders (transaction_id, transaction_currency, transaction_amount, transaction_method, transaction_state)
                        VALUES ('$transaction_id', '$transaction_currency', '$transaction_amount', '$transaction_method', '$transaction_state')");
                
                            
                //Set session for later use, print_r($result); to see what is returned
                $_SESSION["results"]  = array(
                        'transaction_id' => $transaction_id, 
                        'transaction_time' => $transaction_time,
                        'transaction_currency' => $transaction_currency,
                        'transaction_amount' => $transaction_amount,
                        'transaction_method' => $transaction_method,
                        'transaction_state' => $transaction_state
                        );
                            
                header("location: ". RETURN_URL); //$_SESSION["results"] is set, redirect back to order_process.php
                exit();
            }
            
        }catch(PPConnectionException $ex) {
            $ex->getData();
        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
    
    }
    
    ### Display order confirmation if $_SESSION["results"] is set  ####
    if(isset($_SESSION["results"]))
    {
        $html = '';
        $html .= '';
        
        
        $html .= '';
        $html .= '';
        $html .= 'Order Confirm Details';
        $html .= '';
        $html .= '';
        $html .= '';
    
        $html .='

    Payment Success

    '; $html .='
    Please note down your transaction ID, it will be required for further communication!
    '; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= ''; $html .= '
    Transaction IDDateCurrencyAmountMethodState
    '.$_SESSION["results"]["transaction_id"].''.$_SESSION["results"]["transaction_time"].''.$_SESSION["results"]["transaction_currency"].''.$_SESSION["results"]["transaction_amount"].''.$_SESSION["results"]["transaction_method"].''.$_SESSION["results"]["transaction_state"].'
    '; $html .= ''; $html .= ''; echo $html; unset($_SESSION["results"]); } ?>

     

    loading Đang tải...

    template được ưa chuộng