May 25, 2012

PayPal intigration in Android


    If our app has payment option then only one thing can help us and that is paypal .Actually working with payment system is like nightmare but paypal library handles most of things ,which makes developer's life easy .
      
        For developer , we have to test our app in paypal environment but we cant use real money to test our
     app so paypal has given Testing Server which is called 'Sand Box' in which virtual money is used and other is
      
        Live server [For real money]
      
        so in our app we have three option for testing:
        =>SandBox [for testing purpose actually it is exact copy of live paypal but here you can use virtual money ]        =>Live server [it is live]  =>Library itself ,it works as server internally [not recommended for testing better use sandbox]     so Lets explore paypal library in sand box environment       (1) create account in sandbox environment      (2) download paypal library for android and add it to project        (3) test code with some modification             done!!                  Lest start.... 
        (1) Create account :-- 
    
        For  create account in sanbox  ,go to this link


 1 of 10  


      and make account .For verification ,paypal send you mail after verify it will be activated in sanbox environment        note that this sandbox user name and pwd will not work for live paypal and it is recommended that you should not use any real info in sanbox environment .                in website go to in test account tab and create your desired account     

    here three types of account is available  

       (1)Personal   [For individuals who shop online]     

   (2)Business    [For merchants who use a company or group name]    

    (3)Premier     [For individuals who buy and sell online ]         

       create one personal and one Business account for testing transaction                 after creating two account, it will show both account's information            

     for personal account id is something like this ==>> helloxyz_1300948766_per@gmail.com    

    for business account id is something like this ==>> helloxyz22_1300937866_biz@gmail.com        

        here '_per' means personal account and '_biz' means business account        

        now i hope you have created two account ....lets move to second task         

                        (2) Download Library               

   you can download paypal library from here...       

  This zip folder contains demo and jar file for developer.       

           also  you can download paypal tutorials for android here...        

                   (3) Now import project 'sample demo'[which is already in zip folder :)] to your workspace...and run it ..        

 but here we will do some modification in code ...like we will add receipt name .
                

          so first understand how this library works ........
       
       
          initWithAppID Method
The initWithAppID method creates and returns the PayPal object. You must pass in the context and the unique application ID (appID) that PayPal has provided. You can choose whether to use the live or sandbox server, or use non-networked (Demo) mode (see below).
static public PayPal initWithAppID(Context context, String appID, int server)
An example of initializing the Library with this method is:


PayPal ppObj = PayPal.initWithAppID(this.getBaseContext(), "APP-80W284485P519543T", PayPal.ENV_SANDBOX);          

        here appID is   APP-80W284485P519543T which is fix for sandbox environment but for live server it will be diffrent .here PayPal.ENV_SANDBOX ==> means we want to use sandbox server[testing server]        PayPal.ENV_LIVE  ==>> live server      

   PayPal.ENV_NONE  ==> Do not use any PayPal servers.

 Operate in demonstration mode, instead. Demonstration mode lets you view various payment flows without requiring production or test accounts on PayPal servers. Network calls within the library are simulated by using demonstration data held within the library.        

                  getCheckoutButton Method        You must get the Pay with PayPal payment button from the Mobile Payments Library. Use this method, which returns a CheckoutButton (a subclass of LinearLayout), which you can place in your application.
     

   public CheckoutButton getCheckoutButton(Context context, int style, int textType);      
  
      Example code of getting the Payment button from the Library is:CheckoutButton launchPayPalButton = ppObj.getCheckoutButton(this, PayPal.BUTTON_278x43, CheckoutButton.TEXT_PAY); 

//button size 278x43 and text on it is 'PAY'

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);


launchPayPalButton.setLayoutParams(params);

launchPayPalButton.setOnClickListener(this);

((RelativeLayout)findViewById(R.id.RelativeLayout01)).addView(launchPayPalButton);  

     we can customize button like


PayPal.BUTTON_152x33
PayPal.BUTTON_194x37
PayPal.BUTTON_278x43
PayPal.BUTTON_294x45
and we can change text using
CheckoutButton.TEXT_PAY
CheckoutButton.TEXT_DONATE
         
               There are three types of payments in Paypal..               Simple payments have a single recipient. Parallel and Chained payments have multiple recipients and differ in the how the payments are split.Simple Payments


Simple payments use the PayPalPayment object which only supports a payment to a single recipient.

Parallel Payments :Parallel Payments allow you to make payments for any amount to any number of recipients. A parallel payment is created by making a payment with multiple recipients with no primary recipient. From the end-user's standpoint, a parallel payment will affect the UI by showing the details for each recipient. Contrary to chained payments, the recipients of a parallel payment are not linked together in terms of amount.  Chained PaymentsA chained payment is a payment from a sender that is indirectly parallel among multiple receivers. It is an extension of a typical payment from a sender to a receiver; however, a receiver, known as the primary receiver, passes part of the payment to other receivers, who are called secondary receivers.            Start the Library ActivityThe Library uses the native Android Activity mechanism to start the checkout flow, and to communicate completion back to you. In addition to the onActivityResult callback, you can implement PayPalResultDelegate to be informed immediately upon successful completion of a payment.


To start the PayPal payment, you must start the Library activity, using the Android method startActivityForResult. Do this when buyers touch the Pay with PayPal button (which you placed on your page with the getCheckoutButton method)


You must first create the PayPal intent and give it the Payment object. There are two types of payment objects. PayPalPayment handles simple payments, which support single receivers of payments with one transaction and a few details. PayPalAdvancedPayment handles parallel and chained payments, which support multiple receivers of payment with one transaction and with additional details, such as invoice data.In the following example, the buyer checks out with a simple payment for a single recipient:


below code is already given in sample demo provided by paypalhere you can modify setRecipient() method and put mail id  of seller's account .also you can modify whether you want shipping or not ,modify tax related calculation ,add invoice data ,,it is pretty easy ...better refer Paypal reference guide for more detail


/**
     * Create a PayPalPayment which is used for simple payments.
     * 
     * @return Returns a PayPalPayment. 
     */
    private PayPalPayment exampleSimplePayment() {
        // Create a basic PayPalPayment.
        PayPalPayment payment = new PayPalPayment();
        // Sets the currency type for this payment.
        payment.setCurrencyType("USD");
        // Sets the recipient for the payment. This can also be a phone number.
        payment.setRecipient("helloxyz22_1300937866_biz@gmail.com");
        // Sets the amount of the payment, not including tax and shipping amounts.
        payment.setSubtotal(new BigDecimal("8.25"));
        // Sets the payment type. This can be PAYMENT_TYPE_GOODS, PAYMENT_TYPE_SERVICE, PAYMENT_TYPE_PERSONAL, or PAYMENT_TYPE_NONE.
        payment.setPaymentType(PayPal.PAYMENT_TYPE_GOODS);
        
        // PayPalInvoiceData can contain tax and shipping amounts. It also contains an ArrayList of PayPalInvoiceItem which can
        // be filled out. These are not required for any transaction.
        PayPalInvoiceData invoice = new PayPalInvoiceData();
        // Sets the tax amount.
        invoice.setTax(new BigDecimal("10.25"));
        // Sets the shipping amount.
        invoice.setShipping(new BigDecimal("4.50"));
        
        // PayPalInvoiceItem has several parameters available to it. None of these parameters is required.
        PayPalInvoiceItem item1 = new PayPalInvoiceItem();
        // Sets the name of the item.
        item1.setName("Pink Stuffed Bunny");
        // Sets the ID. This is any ID that you would like to have associated with the item.
        item1.setID("87239");
        // Sets the total price which should be (quantity * unit price). The total prices of all PayPalInvoiceItem should add up
        // to less than or equal the subtotal of the payment.
        item1.setTotalPrice(new BigDecimal("6.00"));
        // Sets the unit price.
        item1.setUnitPrice(new BigDecimal("2.00"));
        // Sets the quantity.
        item1.setQuantity(3);
        // Add the PayPalInvoiceItem to the PayPalInvoiceData. Alternatively, you can create an ArrayList<PayPalInvoiceItem>
        // and pass it to the PayPalInvoiceData function setInvoiceItems().
        invoice.getInvoiceItems().add(item1);
        
        // Create and add another PayPalInvoiceItem to add to the PayPalInvoiceData.
        PayPalInvoiceItem item2 = new PayPalInvoiceItem();
        item2.setName("Well Wishes");
        item2.setID("56691");
        item2.setTotalPrice(new BigDecimal("2.25"));
        item2.setUnitPrice(new BigDecimal("0.25"));
        item2.setQuantity(9);
        invoice.getInvoiceItems().add(item2);
        
        // Sets the PayPalPayment invoice data.
        payment.setInvoiceData(invoice);
        // Sets the merchant name. This is the name of your Application or Company.
        payment.setMerchantName("The Gift Store");
        // Sets the description of the payment.
        payment.setDescription("Quite a simple payment");
        // Sets the Custom ID. This is any ID that you would like to have associated with the payment.
        payment.setCustomID("8873482296");
        // Sets the Instant Payment Notification url. This url will be hit by the PayPal server upon completion of the payment.
        payment.setIpnUrl("http://www.exampleapp.com/ipn");
        // Sets the memo. This memo will be part of the notification sent by PayPal to the necessary parties.
        payment.setMemo("Hi! I'm making a memo for a simple payment.");
        
        return payment;
    }



After Payment you will get Transcation Id in  ResultDelegate class through PayPalResultDelegate interface 
    
        PayPalResultDelegate interface having three methods:- 
        
        /**
     * Notification that the payment has been completed successfully.
     * 
     * @param payKey            the pay key for the payment
     * @param paymentStatus        the status of the transaction
     */
    public void onPaymentSucceeded(String payKey, String paymentStatus) {
        //after successfull trancation it will give pay key through which we can retrive transcation detail in future using API call 
    }
    /**
     * Notification that the payment has failed.
     * 
     * @param paymentStatus        the status of the transaction
     * @param correlationID        the correlationID for the transaction failure
     * @param payKey            the pay key for the payment
     * @param errorID            the ID of the error that occurred
     * @param errorMessage        the error message for the error that occurred
     */
    public void onPaymentFailed(String paymentStatus, String correlationID,
        
    }
    /**
     * Notification that the payment was canceled.
     * 
     * @param paymentStatus        the status of the transaction
     */
    public void onPaymentCanceled(String paymentStatus) {
        
    }
        
        
    this is end of paypal integration in android , i hope you feel very easy to grasp all those things but i recommend to go through reference given by paypal for android OS    
    
    ######## How to retrieve Transaction detail by using Pay key...######
    
    
    Lets see....
    
    For that we use paypal api call and we need belows details :-]
    
    only business and premier account user can retrieve payment details ,bcoz for that you need Api user name ,pwd and signature .those things will be provided to only   business and premier account user .
    
    
    Now put in headers below things in name
    
    
    
    HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = null;
        httppost = new HttpPost("https://svcs.sandbox.paypal.com/AdaptivePayments/PaymentDetails");
        httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
    
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("X-PAYPAL-SECURITY-USERID", "id here"));
            nameValuePairs.add(new BasicNameValuePair("X-PAYPAL-SECURITY-PASSWORD", "pwd");
            nameValuePairs.add(new BasicNameValuePair("X-PAYPAL-SECURITY-SIGNATURE", "A.ir6-ZUHAj9O5Wgkpf6YhhFFiUUKhjhK3lIEMcukxNT7zOO-fr1l")); 
            nameValuePairs.add(new BasicNameValuePair("X-PAYPAL-APPLICATION-ID", "APP-80W284485P519543T"));
            nameValuePairs.add(new BasicNameValuePair("X-PAYPAL-REQUEST-DATA-FORMAT", "nv"));
            nameValuePairs.add(new BasicNameValuePair("X-PAYPAL-RESPONSE-DATA-FORMAT", "nv"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            and in body content write data :--
            
            
            "payKey=AP-3TY0117788428730   { This is test key for All sandbox applications ) 
&requestEnvelope.errorLanguage=en_US"
        
        
        That is it ...you will get payment details in nv [name vale pair format].....
     I also have attached some screen shots ..for reference ..




        Some Useful Links :
-------------------------
https://www.x.com/developers/paypal/documentation-tools/paypal-sandbox-getting-started-guide


https://developer.paypal.com/us/cgi-bin/devscr?cmd=_logout


http://www.happygeek.in/paypal-integration-in-android-app#!/


https://cms.paypal.com/cms_content/US/en_US/files/developer/PP_MPL_Developer_Guide_and_Reference_Android.pdf


http://androidsnips.blogspot.in/2011/06/paypal-integration-in-android.html


https://www.x.com/developers/paypal/sandbox       
        happy coding... :)


For Sample Source



No comments:

Post a Comment