2

I am trying to integrate the PayPal payflow to my Android app, using the latest implementation issued by PayPal late last year. But unfortunately I can't get it to work. Any idea on what I am doing wrong? Any help you could give me would be greatly appreciated.

This is my code:

public class PM_Fragment extends Fragment {
    private static final String CONFIG_ENVIRONMENT = //Enter the correct environment here;
    private static final String CONFIG_CLIENT_ID = //you need to register with PayPal and enter your client_ID here;

    private static final int REQUEST_CODE_PAYMENT = 1;
    private static final int REQUEST_CODE_FUTURE_PAYMENT = 2;

    private static PayPalConfiguration config = new PayPalConfiguration()
        .environment(CONFIG_ENVIRONMENT)
        .clientId(CONFIG_CLIENT_ID)
        .acceptCreditCards(true)
        .languageOrLocale("EN")
        .rememberUser(true)
        .merchantName("Company name");

    EditText Name, Age;
    Spinner amount;
    Button Donate;

    @Override
    public View onCreateView(LayoutInflater inflater,
        ViewGroup container, Bundle savedInstanceState) {
        /**
        * Inflate the layout for this fragment
        */
        View rootView= inflater.inflate(
            R.layout.pm_fragment, container, false);

        Name = (EditText) rootView.findViewById(R.id.editText1);
        Age = (EditText) rootView.findViewById(R.id.editText2);
        amount = (Spinner) rootView.findViewById(R.id.spinner1);
        Donate = (Button) rootView.findViewById(R.id.button1);

        Donate.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onBuyPressed(v);
            }
        });

        initPaymentService();

        return rootView;
    }

    public void initPaymentService() {
        try {
            Intent intent = new Intent(getActivity(), PayPalService.class);
            intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);

            getActivity().startService(intent);
        } catch (Exception e) {
            Log.i("PayPal Exception", e.getMessage());
        }
    }

    public double onChoiceMade() {
        int pos = amount.getSelectedItemPosition();
        double payment;

        if (pos == 0) {
            payment = 5.00;
        } else if (pos == 1) {
            payment = 10.00;
        } else if (pos == 2) {
            payment = 20.00;
        } else {
            payment = 50.00;
        }
        return payment;
    }

    public void onBuyPressed(View pressed) {
        try{
            int age = Integer.parseInt(Age.getText().toString());
            if (age >= 18 && age < 99) {
                PayPalPayment thingToBuy = new PayPalPayment(new BigDecimal(onChoiceMade()), "EUR", "Rockestra Donation", PayPalPayment.PAYMENT_INTENT_SALE);

                Intent intent = new Intent(getActivity(), PaymentActivity.class);
                intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
                startActivityForResult(intent, REQUEST_CODE_PAYMENT);
            } else {
                Toast.makeText(getActivity(), "You must be 18 years of age to Process a payment. Please enter a correct age.", Toast.LENGTH_LONG).show();
                Age.setText("");
            }
        } catch (NumberFormatException e){
            Toast.makeText(getActivity(), "Age value cannot be empty. \n Please enter a valid age.", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                PaymentConfirmation confirm = data
                    .getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
                if (confirm != null) {
                    try {
                        Log.i("paymentExample", confirm.toJSONObject().toString(4));

                        Toast.makeText(getActivity().getApplicationContext(), "PaymentConfirmation info received from PayPal",
                            Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        Log.e("paymentExample", "an extremely unlikely failure occurred: ", e);
                    }
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Log.i("paymentExample", "The user canceled.");
            } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
                Log.i("paymentExample", "An invalid Payment was submitted. Please see the docs.");
            }
        } else if (requestCode == REQUEST_CODE_FUTURE_PAYMENT) {
            if (resultCode == Activity.RESULT_OK) {
                PayPalAuthorization auth = data
                    .getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
                if (auth != null) {
                    try {
                        Log.i("FuturePaymentExample", auth.toJSONObject().toString(4));

                        String authorization_code = auth.getAuthorizationCode();
                        Log.i("FuturePaymentExample", authorization_code);

                        sendAuthorizationToServer(auth);
                        Toast.makeText(getActivity().getApplicationContext(), "Future Payment code received from PayPal",
                            Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        Log.e("FuturePaymentExample", "an extremely unlikely failure occurred: ", e);
                    }
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Log.i("FuturePaymentExample", "The user canceled.");
            } else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
                Log.i("FuturePaymentExample",
                      "Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
            }
        }
    }

    private void sendAuthorizationToServer(PayPalAuthorization authorization) {
    }

    @Override
    public void onDestroy() {
        // Stop service when done
        getActivity().stopService(new Intent(getActivity(), PayPalService.class));
        super.onDestroy();
    }
}
Michele La Ferla
  • 6,775
  • 11
  • 53
  • 79
shailesh
  • 449
  • 5
  • 11

1 Answers1

2

I have the following code implemented in a fragment. Please take a look at the below. Note that you need to make some changes, so I take a look at the PayPal documentation too.

Class code:

public class DonationFragment extends Fragment {
     private static final String CONFIG_ENVIRONMENT = //Enter the correct environment here;
     private static final String CONFIG_CLIENT_ID = //you need to register with PayPal and enter your client_ID here;

        private static final int REQUEST_CODE_PAYMENT = 1;
        private static final int REQUEST_CODE_FUTURE_PAYMENT = 2;

        private static PayPalConfiguration config = new PayPalConfiguration()
                .environment(CONFIG_ENVIRONMENT)
                .clientId(CONFIG_CLIENT_ID)
                .acceptCreditCards(true)
                .languageOrLocale("EN")
                .rememberUser(true)
                .merchantName("Company name");

        EditText Name, Age;
        Spinner amount;
        Button Donate;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_donations, container, false);

            Name = (EditText) rootView.findViewById(R.id.editText1);
            Age = (EditText) rootView.findViewById(R.id.editText2);
            amount = (Spinner) rootView.findViewById(R.id.spinner1);
            Donate = (Button) rootView.findViewById(R.id.button1);

            Donate.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    onBuyPressed(v);
                }

            });

            initPaymentService();

            return rootView;
        }

        public void initPaymentService() {
            try {
                Intent intent = new Intent(getActivity(), PayPalService.class);
                 intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);

             getActivity().startService(intent);
            } catch (Exception e) {
                Log.i("PayPal Exception", e.getMessage());
            }
        }

        public double onChoiceMade() {
            int pos = amount.getSelectedItemPosition();
            double payment;

            if (pos == 0) {
                payment = 5.00;
            }else if (pos == 1) {
                payment = 10.00;
            }else if (pos == 2) {
                payment = 20.00;
            }else {
                payment = 50.00;
            }
        return payment;
        }

        public void onBuyPressed(View pressed) {

            try{
                int age = Integer.parseInt(Age.getText().toString());
                if (age >= 18 && age < 99) {
                    PayPalPayment thingToBuy = new PayPalPayment(new BigDecimal(onChoiceMade()), "EUR", "Rockestra Donation", PayPalPayment.PAYMENT_INTENT_SALE);

                    Intent intent = new Intent(getActivity(), PaymentActivity.class);
                    intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
                    startActivityForResult(intent, REQUEST_CODE_PAYMENT);
                }
                else  {
                    Toast.makeText(getActivity(), "You must be 18 years of age to Process a payment. Please enter a correct age.", Toast.LENGTH_LONG).show();
                    Age.setText("");
                }
            }catch (NumberFormatException e){
                Toast.makeText(getActivity(), "Age value cannot be empty. \n Please enter a valid age.", Toast.LENGTH_LONG).show();
                }
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if (requestCode == REQUEST_CODE_PAYMENT) {
                if (resultCode == Activity.RESULT_OK) {
                    PaymentConfirmation confirm = data
                            .getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
                    if (confirm != null) {
                        try {
                            Log.i("paymentExample", confirm.toJSONObject().toString(4));

                            Toast.makeText(getActivity().getApplicationContext(), "PaymentConfirmation info received from PayPal",
                                    Toast.LENGTH_LONG).show();

                        } catch (JSONException e) {
                            Log.e("paymentExample", "an extremely unlikely failure occurred: ", e);
                        }
                    }
                } else if (resultCode == Activity.RESULT_CANCELED) {
                    Log.i("paymentExample", "The user canceled.");
                } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
                    Log.i("paymentExample", "An invalid Payment was submitted. Please see the docs.");
                }
            } else if (requestCode == REQUEST_CODE_FUTURE_PAYMENT) {
                if (resultCode == Activity.RESULT_OK) {
                    PayPalAuthorization auth = data
                            .getParcelableExtra(PayPalFuturePaymentActivity.EXTRA_RESULT_AUTHORIZATION);
                    if (auth != null) {
                        try {
                            Log.i("FuturePaymentExample", auth.toJSONObject().toString(4));

                            String authorization_code = auth.getAuthorizationCode();
                            Log.i("FuturePaymentExample", authorization_code);

                            sendAuthorizationToServer(auth);
                            Toast.makeText(getActivity().getApplicationContext(), "Future Payment code received from PayPal",
                                    Toast.LENGTH_LONG).show();

                        } catch (JSONException e) {
                            Log.e("FuturePaymentExample", "an extremely unlikely failure occurred: ", e);
                        }
                    }
                } else if (resultCode == Activity.RESULT_CANCELED) {
                    Log.i("FuturePaymentExample", "The user canceled.");
                } else if (resultCode == PayPalFuturePaymentActivity.RESULT_EXTRAS_INVALID) {
                    Log.i("FuturePaymentExample",
                            "Probably the attempt to previously start the PayPalService had an invalid PayPalConfiguration. Please see the docs.");
                }
            }
        }

        private void sendAuthorizationToServer(PayPalAuthorization authorization) {

        }

        @Override
        public void onDestroy() {
            // Stop service when done
            getActivity().stopService(new Intent(getActivity(), PayPalService.class));
            super.onDestroy();
        }
}

Please note that I have implemented a spinner to select the amount to donate in this program. Also, I have included a check which makes sure that the age of the user is more than 18 and less than 100.

XML layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/bg_black"
    android:gravity="center_horizontal|center_vertical"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:text="Name (optional):"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="262dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:gravity="center_vertical"
        android:inputType="textPersonName" >

        <requestFocus />
    </EditText>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:gravity="center"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:text="Age:"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/editText2"
            android:layout_width="79dp"
            android:layout_height="wrap_content"
            android:ems="10"
            android:gravity="center_vertical"
            android:inputType="number" />
    </LinearLayout>

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:text="Amount to donate:"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="276dp"
        android:layout_height="wrap_content"
        android:entries="@array/donations"
        android:gravity="center_vertical" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="141dp"
        android:gravity="center"
        android:orientation="vertical" >

        <Button
            android:id="@+id/button1"
            android:layout_width="180dp"
            android:layout_height="49dp"
            android:background="@drawable/checkout"
            android:text="Donate"
            android:textColor="#000000" />

    </LinearLayout>

</LinearLayout>

Hope this helps :)

Michele La Ferla
  • 6,775
  • 11
  • 53
  • 79
  • will you give sample app for this? please.. – shailesh Jun 18 '14 at 13:14
  • hello frnds.. i try your code but got error on this line. PayPalConfiguration config = new PayPalConfiguration(). so which library use ? – shailesh Jun 18 '14 at 13:19
  • you obviously need to download the PayPal files from GitHub: `https://github.com/paypal/PayPal-Android-SDK` You would then need to import this as a library into Eclipse then. This would require some research if you are still new to Eclipse, but this is the correct way to implement it. – Michele La Ferla Jun 18 '14 at 13:55
  • hi frnd.. I add PayPalAndroidSDK.jar file in my project library but error i still come.... have you any sample app for this integration ?. please give me. – shailesh Jun 19 '14 at 05:35
  • Could you pelase send us the logcat you are receiving, as this absolutely works for me? Have you imported it as a library in the Java Build Path? – Michele La Ferla Jun 19 '14 at 07:42
  • first of fall i create app and then add your code in MainActivity. and after then i download PayPal-Android-SDK-master.zip from link you give me. this zip file add in my project libs folder and imort using Java Buid Path – shailesh Jun 19 '14 at 08:27
  • The code I use is for Fragments not Activities. You would need to make some research to find the difference between the two. – Michele La Ferla Jun 19 '14 at 08:29
  • hi frnd i add my code please show that.. – shailesh Jun 19 '14 at 11:03
  • It has not been added as the question has been set as too broad. I would take a look at the following link at this point: `https://github.com/paypal/PayPal-Android-SDK` It may help you. – Michele La Ferla Jun 19 '14 at 11:46
  • download sample app and run in my eclipse.and also create personal and business account in sandbox. but in personal account has not CVV number. also i don't able to pay money from sandbox account. i add CLIENT_ID of business account but not working – shailesh Jun 19 '14 at 13:23
  • You need to create a developer account on Paypal to get a client_ID. This is a unique generated id for each user. – Michele La Ferla Jun 19 '14 at 13:37
  • ya bro.. i create developer account on paypal and get client_id, and add in sample app which download from (https://github.com/paypal/PayPal-Android-SDK) but when i run app, it not work. and credit card has not CVV number. – shailesh Jun 20 '14 at 07:11
  • @MicheleLaFerla register with paypal and get client_id, its tend to single payment,is there anyway to make payment to multiple people? like have a list of users and I can select from the list in order to do payment. – RobinHood May 29 '15 at 13:07
  • By changing some parameters, you can make this possible. Please take a look at the documentation of PayPal. – Michele La Ferla May 29 '15 at 23:58
  • Great and simple implementation +1 – RonEskinder Sep 09 '16 at 19:54