How integrate Paypal in android Application?

前端 未结 3 1519
广开言路
广开言路 2020-12-13 02:53

I try to integrate paypal with Android app using sandbox. I\'m getting successfully longing with paypal but when I am doing payment then Screen will get invisible directly w

相关标签:
3条回答
  • 2020-12-13 03:33
    package com.paypal;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;
    
    import com.paypal.android.sdk.payments.PayPalConfiguration;
    import com.paypal.android.sdk.payments.PayPalPayment;
    import com.paypal.android.sdk.payments.PayPalService;
    import com.paypal.android.sdk.payments.PaymentActivity;
    import com.paypal.android.sdk.payments.PaymentConfirmation;
    
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import java.math.BigDecimal;
    
    public class MainActivity extends AppCompatActivity {
    
        public static  String CONFIG_ENVIRONMENT = PayPalConfiguration.ENVIRONMENT_SANDBOX;
        // note that these credentials will differ between live & sandbox environments.
    
        public static  String CONFIG_CLIENT_ID = "Add your Client ID";      /// add your paypal client id 
    
       private static  int REQUEST_CODE_PAYMENT = 1;
        public static PayPalConfiguration config = new PayPalConfiguration()
                .environment(CONFIG_ENVIRONMENT)
                .clientId(CONFIG_CLIENT_ID);
    
        Button btn_payment;
        String paypal_id,paypal_state,paypal_amount,paypal_currency_code;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            btn_payment = (Button)findViewById(R.id.btn_payment);
    
            btn_payment.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBuyPressed();
                }
            });
    
        }
    
        public void onBuyPressed() {
            PayPalPayment thingToBuy = getThingToBuy(PayPalPayment.PAYMENT_INTENT_SALE);
            Intent intent = new Intent(MainActivity.this, PaymentActivity.class);
            intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
            intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
            startActivityForResult(intent, REQUEST_CODE_PAYMENT);
        }
    
        private PayPalPayment getThingToBuy(String paymentIntent) {
            return new PayPalPayment(new BigDecimal("1"), "USD", "sample item  ",
                    paymentIntent);
        }
    
        @Override
        protected 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.e("Show", confirm.toJSONObject().toString(4));
                            Log.e("Show", confirm.getPayment().toJSONObject().toString(4));
    
                            JSONObject json=confirm.toJSONObject();
                            JSONObject responce = json.getJSONObject("response");
                            paypal_id = responce.getString("id");
                            paypal_state = responce.getString("state");
                            JSONObject payment=confirm.getPayment().toJSONObject();
                            paypal_amount=payment.getString("amount");
                            paypal_currency_code=payment.getString("currency_code");
    
                            Toast.makeText(getApplicationContext(), "PaymentConfirmation info received" + " from PayPal", Toast.LENGTH_LONG).show();
                        } catch (JSONException e) {
                            Toast.makeText(getApplicationContext(), "an extremely unlikely failure" +
                                    " occurred:", Toast.LENGTH_LONG).show();
                        }
                    }
                } else if (resultCode == Activity.RESULT_CANCELED) {
    
                } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
                    Toast.makeText(getApplicationContext(), "An invalid Payment or PayPalConfiguration" +
                            " was submitted. Please see the docs.", Toast.LENGTH_LONG).show();
                }
            }
        }
    
        @Override
        public void onDestroy() {
            // Stop service when done
            stopService(new Intent(this, PayPalService.class));
            super.onDestroy();
        }
    
    }
    
    
    ///////////////// decler paypal activity in manifest ///////////////////////////
    
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.paypal">
    
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        <!-- for card.io card scanning -->
        <uses-permission android:name="android.permission.CAMERA" />
        <uses-permission android:name="android.permission.VIBRATE" />
    
        <uses-feature
            android:name="android.hardware.camera"
            android:required="false" />
        <uses-feature
            android:name="android.hardware.camera.autofocus"
            android:required="false" />
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
    
            <!-- pay pal server decler -->
            <service
                android:name="com.paypal.android.sdk.payments.PayPalService"
                android:exported="false" />
    
            <activity android:name="com.paypal.android.sdk.payments.PaymentActivity" />
            <activity android:name="com.paypal.android.sdk.payments.LoginActivity" />
            <activity android:name="com.paypal.android.sdk.payments.PaymentMethodActivity" />
            <activity android:name="com.paypal.android.sdk.payments.PaymentConfirmActivity" />
            <activity
                android:name="io.card.payment.CardIOActivity"
                android:configChanges="keyboardHidden|orientation" />
            <activity android:name="io.card.payment.DataEntryActivity" />
            <!-- end -->
    
        </application>
    
    </manifest>
    
    
    
    
    
    
    //////////////////// gradel ///////////////////
    
    apply plugin: 'com.android.application'
    
    android {
        compileSdkVersion 23
        buildToolsVersion "23.0.1"
    
        defaultConfig {
            applicationId "com.paypal"
            minSdkVersion 16
            targetSdkVersion 23
            versionCode 1
            versionName "1.0"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }
    
    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        testCompile 'junit:junit:4.12'
        compile 'com.android.support:appcompat-v7:23.0.1'
        compile 'com.paypal.sdk:paypal-android-sdk:2.14.2'
    }
    
    0 讨论(0)
  • 2020-12-13 03:34

    This is my code and it works fine. There are two classes.

    For PayPal from sandbox to live environment you have to do 2 things: put the actual account holder in set recipient and get a live ID by submitting your app to PayPal

    public class ResultDelegate implements PayPalResultDelegate, Serializable {
         private static final long serialVersionUID = 10001L;
    
    
        public void onPaymentSucceeded(String payKey, String paymentStatus) {
    
            main.resultTitle = "SUCCESS";
            main.resultInfo = "You have successfully completed your transaction.";
            main.resultExtra = "Key: " + payKey;
        }
    
    
        public void onPaymentFailed(String paymentStatus, String correlationID,
                      String payKey, String errorID, String errorMessage) {
            main.resultTitle = "FAILURE";
            main.resultInfo = errorMessage;
            main.resultExtra = "Error ID: " + errorID + "\nCorrelation ID: "
               + correlationID + "\nPay Key: " + payKey;
        }
    
    
        public void onPaymentCanceled(String paymentStatus) {
            main.resultTitle = "CANCELED";
            main.resultInfo = "The transaction has been cancelled.";
            main.resultExtra = "";
        }
    

    The main class :

    public class main extends Activity implements OnClickListener {
    
    // The PayPal server to be used - can also be ENV_NONE and ENV_LIVE
    private static final int server = PayPal.ENV_LIVE;
    // The ID of your application that you received from PayPal
    private static final String appID = "APP-0N8000046V443613X";
    // This is passed in for the startActivityForResult() android function, the value used is up to you
    private static final int request = 1;
    
    public static final String build = "10.12.09.8053";
    
    protected static final int INITIALIZE_SUCCESS = 0;
    protected static final int INITIALIZE_FAILURE = 1;
    
    TextView labelSimplePayment;
    LinearLayout layoutSimplePayment;
    CheckoutButton launchSimplePayment;
    Button exitApp;
    TextView title;
    TextView info;
    TextView extra;
    TextView labelKey;
    TextView appVersion;
    EditText enterPreapprovalKey;
    
    public static String resultTitle;
    public static String resultInfo;
    public static String resultExtra;
    private String isuename;
    private String isueprice;
    
    Handler hRefresh = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what){
    
            case INITIALIZE_SUCCESS:
                setupButtons();
                break;
            case INITIALIZE_FAILURE:
                showFailure();
                break;
            }
        }
    };
    
    
    
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        Thread libraryInitializationThread = new Thread() {
            @Override
            public void run() {
                initLibrary();
    
                // The library is initialized so let's create our CheckoutButton and update the UI.
                if (PayPal.getInstance().isLibraryInitialized()) {
                    hRefresh.sendEmptyMessage(INITIALIZE_SUCCESS);
                }
                else {
                    hRefresh.sendEmptyMessage(INITIALIZE_FAILURE);
                }
            }
        };
        libraryInitializationThread.start();
    
    
         isuename=getIntent().getStringExtra("name").trim();
         isueprice=getIntent().getStringExtra("price").replace("$", "").trim();
    
         Log.v("isuename ",""+isuename);
         Log.v("isueprice ",""+isueprice);
    
        LinearLayout content = new LinearLayout(this);
        content.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.FILL_PARENT));
        content.setGravity(Gravity.CENTER_HORIZONTAL);
        content.setOrientation(LinearLayout.VERTICAL);
        content.setPadding(10, 10, 10, 10);
        content.setBackgroundColor(Color.WHITE);
    
        layoutSimplePayment = new LinearLayout(this);
        layoutSimplePayment.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
        layoutSimplePayment.setGravity(Gravity.CENTER_HORIZONTAL);
        layoutSimplePayment.setOrientation(LinearLayout.VERTICAL);
        layoutSimplePayment.setPadding(0, 5, 0, 5);
    
        labelSimplePayment = new TextView(this);
        labelSimplePayment.setGravity(Gravity.CENTER_HORIZONTAL);
        labelSimplePayment.setText("C&EN");
        labelSimplePayment.setTextColor(Color.RED);
        labelSimplePayment.setTextSize(45.0f);
    
        layoutSimplePayment.addView(labelSimplePayment);
              //        labelSimplePayment.setVisibility(View.GONE);
    
        content.addView(layoutSimplePayment);
    
        LinearLayout layoutKey = new LinearLayout(this);
        layoutKey.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
        layoutKey.setGravity(Gravity.CENTER_HORIZONTAL);
        layoutKey.setOrientation(LinearLayout.VERTICAL);
        layoutKey.setPadding(0, 1, 0, 5);
    
        enterPreapprovalKey = new EditText(this);
        enterPreapprovalKey.setLayoutParams(new LayoutParams(200, 45));
        enterPreapprovalKey.setGravity(Gravity.CENTER);
        enterPreapprovalKey.setSingleLine(true);
        enterPreapprovalKey.setHint("Enter PA Key");
        layoutKey.addView(enterPreapprovalKey);
        enterPreapprovalKey.setVisibility(View.GONE);
        labelKey = new TextView(this);
        labelKey.setGravity(Gravity.CENTER_HORIZONTAL);
        labelKey.setPadding(0, -5, 0, 0);
        labelKey.setText("(Required for Preapproval)");
        layoutKey.addView(labelKey);
        labelKey.setVisibility(View.GONE);
        content.addView(layoutKey);
    
        title = new TextView(this);
        title.setLayoutParams(new LinearLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
        title.setPadding(0, 5, 0, 5);
        title.setGravity(Gravity.CENTER_HORIZONTAL);
        title.setTextSize(30.0f);
        title.setVisibility(View.GONE);
        content.addView(title);
    
        info = new TextView(this);
        info.setLayoutParams(new LinearLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
        info.setPadding(0, 5, 0, 5);
        info.setGravity(Gravity.CENTER_HORIZONTAL);
        info.setTextSize(20.0f);
        info.setVisibility(View.VISIBLE);
        info.setText("Please Wait! Initializing Paypal...");
        info.setTextColor(Color.BLACK);
        content.addView(info);
    
        extra = new TextView(this);
        extra.setLayoutParams(new LinearLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
        extra.setPadding(0, 5, 0, 5);
        extra.setGravity(Gravity.CENTER_HORIZONTAL);
        extra.setTextSize(12.0f);
        extra.setVisibility(View.GONE);
        content.addView(extra);
    
        LinearLayout layoutExit = new LinearLayout(this);
        layoutExit.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
        layoutExit.setGravity(Gravity.CENTER_HORIZONTAL);
        layoutExit.setOrientation(LinearLayout.VERTICAL);
        layoutExit.setPadding(0, 15, 0, 5);
    
        exitApp = new Button(this);
        exitApp.setLayoutParams(new LayoutParams(200, android.view.ViewGroup.LayoutParams.WRAP_CONTENT)); //Semi mimic PP button sizes
        exitApp.setOnClickListener(this);
        exitApp.setText("Exit");
        layoutExit.addView(exitApp);
        content.addView(layoutExit);
    
        appVersion = new TextView(this);
        appVersion.setGravity(Gravity.CENTER_HORIZONTAL);
        appVersion.setPadding(0, -5, 0, 0);
        appVersion.setText("\n\nSimple Demo Build " + build + "\nMPL Library Build " + PayPal.getBuild());
        content.addView(appVersion);
        appVersion.setVisibility(View.GONE);
    
        setContentView(content);
    }
    public void setupButtons() {
        PayPal pp = PayPal.getInstance();
        // Get the CheckoutButton. There are five different sizes. The text on the button can either be of type TEXT_PAY or TEXT_DONATE.
        launchSimplePayment = pp.getCheckoutButton(this, PayPal.BUTTON_194x37, CheckoutButton.TEXT_PAY);
        // You'll need to have an OnClickListener for the CheckoutButton. For this application, MPL_Example implements OnClickListener and we
        // have the onClick() method below.
        launchSimplePayment.setOnClickListener(this);
        // The CheckoutButton is an android LinearLayout so we can add it to our display like any other View.
        layoutSimplePayment.addView(launchSimplePayment);
    
        // Get the CheckoutButton. There are five different sizes. The text on the button can either be of type TEXT_PAY or TEXT_DONATE.
    
        // Show our labels and the preapproval EditText.
        labelSimplePayment.setVisibility(View.VISIBLE);
    
    
        info.setText("");
        info.setVisibility(View.GONE);
    }
    public void showFailure() {
        title.setText("FAILURE");
        info.setText("Could not initialize the PayPal library.");
        title.setVisibility(View.VISIBLE);
        info.setVisibility(View.VISIBLE);
    }
    private void initLibrary() {
        PayPal pp = PayPal.getInstance();
    
        if(pp == null) {
    
            pp = PayPal.initWithAppID(this, appID, server);
            pp.setLanguage("en_US"); // Sets the language for the library.
            pp.setFeesPayer(PayPal.FEEPAYER_EACHRECEIVER); 
            // Set to true if the transaction will require shipping.
            pp.setShippingEnabled(true);
            // Dynamic Amount Calculation allows you to set tax and shipping amounts based on the user's shipping address. Shipping must be
            // enabled for Dynamic Amount Calculation. This also requires you to create a class that implements PaymentAdjuster and Serializable.
            pp.setDynamicAmountCalculationEnabled(false);
            // --
        }
    }
    
    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("harshd_1312435282_per@gmail.com");
    
    
        // Sets the amount of the payment, not including tax and shipping amounts.
    
        payment.setSubtotal(new BigDecimal(isueprice));
        // 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("0"));
        // Sets the shipping amount.
        invoice.setShipping(new BigDecimal("0"));
    
        // 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(isuename);
        // 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("2.99"));
        // 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("C&EN");
        // Sets the description of the payment.
        payment.setDescription("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 payment.");
    
        return payment;
    }
    @Override
    public void onClick(View v) {
    
        if(v == launchSimplePayment) {
            // Use our helper function to create the simple payment.
            PayPalPayment payment = exampleSimplePayment(); 
            // Use checkout to create our Intent.
            Intent checkoutIntent = PayPal.getInstance().checkout(payment, this, new ResultDelegate());
            // Use the android's startActivityForResult() and pass in our Intent. This will start the library.
            startActivityForResult(checkoutIntent, request);
        } else if(v == exitApp) {
    
            Intent in = new Intent();
            in.putExtra("payment", "unpaid");
            /*in.putExtra("condition", "false");*/
            setResult(1,in);//Here I am Setting the Requestcode 1, you can put according to your requirement
            finish();
        }
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode != request)
            return;
    
        if(main.resultTitle=="SUCCESS"){
            Intent in = new Intent();
            in.putExtra("payment", "paid");
            setResult(22,in);
    
        }else if(main.resultTitle=="FAILURE"){
            Intent in = new Intent();
            in.putExtra("payment", "unpaid");
            setResult(22,in);
                     //         finish();
        }else if(main.resultTitle=="CANCELED"){
            Intent in = new Intent();
            in.putExtra("payment", "unpaid");
            setResult(22,in);
                      //            finish();
        }
    
    
        launchSimplePayment.updateButton();
    
        title.setText(resultTitle);
        title.setVisibility(View.VISIBLE);
        info.setText(resultInfo);
        info.setVisibility(View.VISIBLE);
        extra.setText(resultExtra);
        extra.setVisibility(View.VISIBLE);
        finish();
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent in = new Intent();
            in.putExtra("payment", "unpaid");
            setResult(1,in);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
    0 讨论(0)
  • 2020-12-13 03:35

    PayPal Launches Android SDK for Developers

    https://www.paypal-forward.com/innovation/paypal-launches-android-sdk-for-developers/

    The documentation Here:

    https://developer.paypal.com/webapps/developer/docs/integration/mobile/android-integration-guide/

    0 讨论(0)
提交回复
热议问题