草庐IT

android - 如何在 Android 应用程序中集成 Paypal?

coder 2023-11-18 原文

我尝试使用沙箱将 paypal 与 Android 应用程序集成。我正在成功地渴望使用 paypal,但是当我进行付款时,如果没有 Response,Screen 将直接变得不可见。
我怎样才能得到上述问题的答复?

这是我的代码。

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);
}

最佳答案

这是我的代码,运行良好。有两个类。

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

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 = "";
    }

主类:

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);
}

关于android - 如何在 Android 应用程序中集成 Paypal?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7631841/

有关android - 如何在 Android 应用程序中集成 Paypal?的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. ruby - 在 Ruby 程序执行时阻止 Windows 7 PC 进入休眠状态 - 2

    我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0

  3. ruby - 将差异补丁应用于字符串/文件 - 2

    对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl

  4. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  5. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  6. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

  7. ruby - 在 Ruby 中编写命令行实用程序 - 2

    我想用ruby​​编写一个小的命令行实用程序并将其作为gem分发。我知道安装后,Guard、Sass和Thor等某些gem可以从命令行自行运行。为了让gem像二进制文件一样可用,我需要在我的gemspec中指定什么。 最佳答案 Gem::Specification.newdo|s|...s.executable='name_of_executable'...endhttp://docs.rubygems.org/read/chapter/20 关于ruby-在Ruby中编写命令行实用程序

  8. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  9. ruby-on-rails - Rails 应用程序之间的通信 - 2

    我构建了两个需要相互通信和发送文件的Rails应用程序。例如,一个Rails应用程序会发送请求以查看其他应用程序数据库中的表。然后另一个应用程序将呈现该表的json并将其发回。我还希望一个应用程序将存储在其公共(public)目录中的文本文件发送到另一个应用程序的公共(public)目录。我从来没有做过这样的事情,所以我什至不知道从哪里开始。任何帮助,将不胜感激。谢谢! 最佳答案 无论Rails是什么,几乎所有Web应用程序都有您的要求,大多数现代Web应用程序都需要相互通信。但是有一个小小的理解需要你坚持下去,网站不应直接访问彼此

  10. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

随机推荐