简体   繁体   中英

PayPal Express Checkout Integration with JS: Production ID

I just implemented PayPal Express Checkout Integration in our CMS. With our Sandbox-ID it is all working fine, but for our live-environment, our customers have to put their paypal API credential into our system. In the paypal developer docs I can not find any solution, how I can integrate these customer credentials into the Express Checkout Integration code.

Can somebody please help me?

                    <div id='paypal-button'></div>                          
                        <script>
                            paypal.Button.render({

                                env: 'production', // Specify 'sandbox' for the test environment, 'production'

                            style: {
                                        size: 'medium',
                                        color: 'silver',
                                        shape: 'rect'
                                    },                                  

                            client: {
                                    sandbox:    'ASoNxxxxxxxxxxxxxxxxxxx',
                                    production: '$customer_api'
                                },

                                payment: function(resolve, reject) {
                                    // Set up the payment here, when the buyer clicks on the button
                                    var env    = this.props.env;
                                    var client = this.props.client;

                                    return paypal.rest.payment.create(env, client, {
                                        'intent': 'sale',
                                        'payer':{
                                            'payer_info': {
                                                'email': '$email',
                                                'first_name': '$vorname',
                                                'last_name': '$nachname',
                                                'shipping_address': {
                                                    'line1': '$strasse',
                                                    'city': '$ort',                                                     
                                                    'postal_code': '$plz',
                                                    'country_code': '$land',
                                                    'recipient_name': '$firma'
                                                }
                                            }
                                        },
                                        transactions: [
                                            {
                                                amount: {
                                                    'total': '$total',
                                                    'currency': '$currency',
                                                    'details':{
                                                      'subtotal':'$total_netto',
                                                      'tax':'$tax',
                                                      'shipping':'$shipping',                                                         
                                                      }                                                     
                                            },  
                                            },
                                        ],
                                    });
                                },

                            commit: true,

                                onAuthorize: function(data, actions) {                                     
                                return actions.payment.execute().then(function() {
                                            location.href = '/shop/checkout/mode/4'
                                        });
                                },

                            onCancel: function(data, actions) {
                                    return actions.redirect();
                                },

                            onError: function(err) {
                                    location.href = '/shop/checkout/mode/4'
                                }


                            }, '#paypal-button');
                        </script>

I found a solution and wrote a php-script to realize a quick paypal-express-checkout-button: (by using this sdk: https://github.com/paypal/PayPal-PHP-SDK/releases )

<?php
use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payee;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;

class Application_Model_Paypal{

public function checkout(
            $total          = 0,        //Cost incl. tax
            $subtotal       = 0,        //Cost without tax
            $shipping       = 0,        //Cost for Shipping inkl. tax
            $tax            = 0,        //Tax
            $currency       = 'EUR',    //EUR, USD, ...
            $address        = array(),  //Array() of addressdata
            $items          = array(),  //Array() of Items, [name, amount, tax, price(without. tax), number, description]
            $clientid       = '',       //REST-API-ClientID
            $clientsecret   = '',       //REST-API-Secret
            $payee_email    = '',       //Emailadresse des PayPal-Accounts
            $url_success    = '',       //URL in case of payment success 
            $url_error      = ''        //URL in case of payment error
            ){

    /****
     * 
     * ATTENTION:
     * total =!= subtotal + shipping + tax
     * 
     * ITEMS:
     * subtotal = SUM_OF_ITEMS( price * amount )
     * 
     * ***/


    //Clientaddress data
    $email = $address['email'];
    $firma = $address['firma'];
    $vorname = $address['vorname'];
    $nachname = $address['nachname'];
    $strasse = $address['strasse'];
    $plz = $address['plz'];
    $ort = $address['ort'];
    $land = $address['land'];       


    //PayPalData
    $payer = new Payer();
    $payer->setPaymentMethod("paypal");

    $_itemlist = array();
    foreach($items as $it){
        $i = new Item();
        $i->setName($it['name'])
            ->setCurrency($currency)
            ->setDescription($it['description'])
            ->setQuantity($it['amount'])
            ->setTax($it['tax'])
            ->setSku($it['number']) // Similar to "item_number"
            ->setPrice($it['price']);

        //Item back array
        array_push($_itemlist, $i);
    }



    //Paypal itemlist
    $itemList = new ItemList();
    $itemList->setItems($_itemlist);        

    $details = new Details();
    $details->setShipping($shipping)
        ->setTax($tax)
        ->setSubtotal($subtotal);

    $amount = new Amount();
    $amount->setCurrency($currency)
        ->setTotal($total)
        ->setDetails($details);

    $payee = new Payee();
    $payee->setEmail($payee_email);

    $transaction = new Transaction();
    $transaction->setAmount($amount)
        ->setItemList($itemList)
        ->setDescription("Payment description")
        ->setPayee($payee)
        ->setInvoiceNumber(uniqid());       

    $redirectUrls = new RedirectUrls();
    $redirectUrls->setReturnUrl("$url_success")
        ->setCancelUrl("$url_error");               


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

    $request = clone $payment;

    try {
        $clientid = $clientid;
        $clientsecret = $clientsecret;

        $apiContext = new ApiContext(new OAuthTokenCredential($clientid, $clientsecret));
        $apiContext->setConfig(
            array(
            'mode' => 'live',
        ));             
        $payment->create($apiContext);

    } catch (Exception $e) {
        /*
         *  print_r($_itemlist);
            echo "<div class='alert alert-danger'>".
                    $e->getMEssage()."<br>".
                    "<pre>".$e->getData()."</pre><br>".
                    "Total: $total <br> Subtotal: $subtotal <br> Shipping: $shipping <br> Tax: $tax <br>".
                    "<pre>$payment</pre>".
                "</div>";
         */         
    }


    $res = "        
    <script src='https://www.paypalobjects.com/api/checkout.js'></script>       
    <div id='checkout_button'></div>        
    <script>

        // Render the PayPal button

        paypal.Button.render({

            // Set your environment

            env: 'production', // sandbox | production

            // PayPal Client IDs - replace with your own
            // Create a PayPal app: https://developer.paypal.com/developer/applications/create

            style: {
                size:  'medium',
                color: 'silver',
                shape: 'rect'
            },   

            client: {
                production: '$clientid'
            },

            // Wait for the PayPal button to be clicked

            payment: function() {

                // Make a client-side call to the REST api to create the payment

                return paypal.rest.payment.create(this.props.env, this.props.client, 
                     ".$payment."
                );
            },

            // Wait for the payment to be authorized by the customer

            onAuthorize: function(data, actions) {

                // Execute the payment

                return actions.payment.execute().then(function() {
                    location.href='$url_success';
                });
            },

            // Wait for the payment to be authorized by the customer

            onError: function(err) {
                // Show an error page here, when an error occurs
                location.href = '$url_error';
            },

            onCancel: function(data, actions) {
                return actions.redirect();
            },

        }, '#checkout_button');

    </script>


    ";

    return $res;
}
}

Each merchant has to create a new app in developer REST-API-Tool and has to use a paypal-business-account. After creating these app-credentials, you have to switch to live-environment. Login to your business-account and follow this link to "REST-API apps": https://developer.paypal.com/developer/applications/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM