如何在 Android 应用程序中集成 Paypal? [英] How integrate Paypal in android Application?

查看:21
本文介绍了如何在 Android 应用程序中集成 Paypal?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用沙盒将 paypal 与 Android 应用程序集成.我已经成功地渴望使用 paypal,但是当我付款时,屏幕将直接隐形,无需响应.
我怎样才能得到上述问题的答复?

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 without Response.
How can I get the response for the above question?

这是我的代码.

private void invokeSimplePayment()
{
    try
    {
        PayPalPayment payment = new PayPalPayment();
        payment.setSubtotal(new BigDecimal(Amt));
        payment.setCurrencyType(Currency_code[code]);
        payment.setRecipient("Rec_Email");
        payment.setPaymentType(PayPal.PAYMENT_TYPE_GOODS);
        Intent checkoutIntent = PayPal.getInstance().checkout(payment, this);
        startActivityForResult(checkoutIntent, request);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

public void onActivityResults(int requestCode, int resultCode, Intent data)
{
    switch(resultCode) 
    {
        case Activity.RESULT_OK:
            resultTitle = "SUCCESS";                
            resultInfo = "You have successfully completed this " ;
            //resultExtra = "Transaction ID: " + data.getStringExtra(PayPalActivity.EXTRA_PAY_KEY);
            break;
        case Activity.RESULT_CANCELED:
            resultTitle = "CANCELED";
            resultInfo = "The transaction has been cancelled.";
            resultExtra = "";
            break;
        case PayPalActivity.RESULT_FAILURE:
            resultTitle = "FAILURE";
            resultInfo = data.getStringExtra(PayPalActivity.EXTRA_ERROR_MESSAGE);
            resultExtra = "Error ID: " + data.getStringExtra(PayPalActivity.EXTRA_ERROR_ID);
    }
    System.out.println("Result=============="+resultTitle);
    System.out.println("ResultInfo=============="+resultInfo);
}

推荐答案

这是我的代码,运行良好.有两个班级.

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

对于从沙盒到实时环境的 PayPal,您必须做两件事:将实际帐户持有人置于设置的收件人中,并通过将您的应用提交到 PayPal 来获取实时 ID

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 + "
Correlation ID: "
           + correlationID + "
Pay Key: " + payKey;
    }


    public void onPaymentCanceled(String paymentStatus) {
        main.resultTitle = "CANCELED";
        main.resultInfo = "The transaction has been cancelled.";
        main.resultExtra = "";
    }

主类:

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("

Simple Demo Build " + build + "
MPL 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);
}

这篇关于如何在 Android 应用程序中集成 Paypal?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆