Tag Archives: Code

Creating a PayPal / Credit Card Payment within an Android Application

By and

In this tutorial we’re going to learn how to set up the PayPal Android SDK to process a simple payment via either a PayPal payment or a credit card purchase. At the end of this example, you should have a simple button in an application that, when clicked, will forward the user to PayPal to confirm a set payment, then return the user back to the application and log the confirmation of payment.

The complete application code for this example is available in the PayPal Developer Github Repository.

Let’s get started.

The first step is to obtain and add the SDK to your project. We add the reference to our build.gradle dependancies like so:

dependencies {
    compile 'com.paypal.sdk:paypal-android-sdk:2.14.1'
    ...
}

Now we head over to our MainActivity.java file (or wherever you’d like to add the PayPal button integration), and add in a config object for our client ID and the environment (sandbox) that we will be using.

private static PayPalConfiguration config = new PayPalConfiguration()
    .environment(PayPalConfiguration.ENVIRONMENT_SANDBOX)
    .clientId("YOUR CLIENT ID");

Now we’re going to create a button in our onCreate(...) method, which will enable us to process a payment via PayPal once clicked.

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final Button button = (Button) findViewById(R.id.paypal_button);
}

We now need to define the functionality for that button. In your res > layout > main XML file you can add the following definition for the button, which will define the text and onClick handler for the button with the paypal_button ID.

<Button android:id="@+id/paypal_button"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:text="@string/paypal_button"
    android:onClick="beginPayment" />

When clicked, the button will call the beginPayment(...) method. We can then add the text for the button to our strings.xml file, like so:

<string name="paypal_button">Pay with PayPal</string>

With the button in place, we now have to handle the button click in order to begin payment processing. Add in the following beginPayment(...) method below our previous onCreate(...) method.

public void beginPayment(View view){
    Intent serviceConfig = new Intent(this, PayPalService.class);
    serviceConfig.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
    startService(serviceConfig);

    PayPalPayment payment = new PayPalPayment(new BigDecimal("5.65"), 
        "USD", "My Awesome Item", PayPalPayment.PAYMENT_INTENT_SALE);

    Intent paymentConfig = new Intent(this, PaymentActivity.class);
    paymentConfig.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);
    paymentConfig.putExtra(PaymentActivity.EXTRA_PAYMENT, payment);
    startActivityForResult(paymentConfig, 0);
}

What we are doing here is first setting up the service intent (serviceConfig), using the config that we had defined previously for our client ID and the sandbox environment. We then specify the payment object that we want to process. For the sake of this example, we are setting a static price, currency, and description. In your final application, these values should be obtained from what the user is trying to buy in the application. Lastly, we set up the paymentConfig, adding in both the config and payment objects that we had previously defined, and start the activity.

At this point the user will be presented with the PayPal login and payment screens, allowing them to select whether to pay with PayPal or a credit card (via manual entry or card.io if the camera is available). That screen will look something like this:

PayPal payment confirmation screen

Once done, we need to have a handler ready for when PayPal forwards the user back to the application after confirmation of payment or cancellation. Let’s override onActivityResult(...) for that purpose.

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

                // TODO: send 'confirm' to your server for verification

            } catch (JSONException e) {
                Log.e("sampleapp", "no confirmation data: ", e);
            }
        }
    } else if (resultCode == Activity.RESULT_CANCELED) {
        Log.i("sampleapp", "The user canceled.");
    } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
        Log.i("sampleapp", "Invalid payment / config set");
    }
}

Within the onActivityResult(...) method, we are checking to see if the resultCode that comes back is RESULT_OK (user confirmed payment), RESULT_CANCELED (user cancelled payment), or RESULT_EXTRAS_INVALID (there was a configuration issue). In the case of a valid confirmation, we get the object that is returned from the payment and, in this sample, log it. What will be returned to us should look something like the following:

{
    "client": {
        "environment": "sandbox",
        "paypal_sdk_version": "2.14.1",
        "platform": "Android",
        "product_name": "PayPal-Android-SDK"
    },
    "response": {
        "create_time": "2016-05-02T15:33:43Z",
        "id": "PAY-0PG63447RB821630KK1TXGTY",
        "intent": "sale",
        "state": "approved"
    },
    "response_type": "payment"
}

If we look under the response object, we can see that we have a state of approved, meaning that the payment was confirmed. At this point, that object should be sent to your server to confirm that a payment actually went through. For more information on those steps, see these docs.

Our last step is to cleanup in our onDestroy(...).

@Override
public void onDestroy(){
    stopService(new Intent(this, PayPalService.class));
    super.onDestroy();
}

That’s all there is to it. In this example we’ve created a simple button to process a payment with either PayPal or a credit card. From this point, there are a few next steps for you to expand upon this sample:

  • Pulling in payment information dynamically based on user product selection in the beginPayment(...) method.
  • Sending the payment confirmation to your server and verifying that the payment actually went through.
  • Handling the error and cancellation user cases within the app.

Building the Next Step in Payment Tutorials with Stack Overflow Docs

By and

At PayPal Developer, we are constantly looking at new ways to expand our outreach into the community to provide the solutions that developers need, where they choose to be. This is why we work within different external communities, such as Stack Overflow to help with technical integrations, and Github for much of our external developer code offerings and open source projects.

We’re happy to announce that we have partnered with Stack Overflow for the launch of a new project called Stack Overflow Documentation. The aim of the Stack Overflow documentation project is to build a community around the process of creating great documentation, not by simply copying our documentation to another place, but by working with the community to build the documentation, examples, and integrations that developers want and care about. We’ve started by adding some examples based off of common questions that we receive frequently.

Come take a look at the initial documentation and examples we have on Stack Overflow Docs and make suggestions for integrations that you want to see. We’re going to be working hard to help deliver the content that you want to see, and we would love for you to be a part of this with us by contributing examples and topics for things that you built out, by requesting new topics for us to write about, or by improving the samples that we already have up on the site if something just doesn’t make sense or should be revised.

We look forward to working with everyone in our community to build the examples that you all care about.

Processing a Credit Card Payment with a Vaulted Card

By and

In this tutorial, we’ll be looking at a Node example to show how to store a credit card using the PayPal vault, then reference that stored credit card to process a credit card transaction for a user.

The reason why we would want to use the vault is so that we don’t have to store sensitive credit card information on our own servers. We simply reference the payment method via a provided vault ID, meaning that we don’t have to deal with many PCI compliance regulations with storing the credit cards ourselves.

For the full example code used in the below tutorial, go to the PayPal Developer Github account.

Our first step is to require the packages that we need, and configure our environment.

var paypal = require('paypal-rest-sdk'),
    uuid = require('node-uuid');

var client_id = 'YOUR CLIENT ID';
var secret = 'YOUR SECRET';

paypal.configure({
  'mode': 'sandbox', //sandbox or live
  'client_id': client_id,
  'client_secret': secret
});

We add the requirement for the PayPal SDK & a uuid package (more on that in a moment), then set up variables for the client ID and secret that were obtained when creating an application. We then configure our application using these details, and specify the environment that we are working in (live or sandbox). We are using the node-uuid package in order to be able to generate unique UUID’s for the payers when storing the card. An alternative for this is to use your unique customer IDs in place of this functionality. You can install that package via:

npm install node-uuid

Next, we define the credit card JSON object that will be sent to the PayPal vault for storage. It contains information from the card, as well as a unique payer ID that we generate using node-uuid. You should store this unique payer_id in your own database as it will be used when creating a payment with the vaulted card.

var create_card_details = {
    "type": "visa",
    "number": "4417119669820331",
    "expire_month": "11",
    "expire_year": "2018",
    "first_name": "John",
    "last_name": "Doe",
    "payer_id": uuid.v4()
};

Lastly, we need to store the credit card and process the payment using that card. To vault a credit card, we call credit_card.create(...), passing in the credit_card_details object that we just created. If all goes well, we should have an object returned to us with details about the vaulted card. For the sake of a payment with that card, we only really need two pieces of information: the payer_id that we already stored, and the vault ID, that should also be stored as a reference in our own database.

paypal.credit_card.create(create_card_details, function(error, credit_card){
    if(error){
        console.error(error);
    } else {
        var card_data = {
            "intent": "sale",
            "payer": {
                "payment_method": "credit_card",
                "funding_instruments": [{
                    "credit_card_token": {
                        "credit_card_id": credit_card.id,
                        "payer_id": credit_card.payer_id
                    }
                }]
            },
            "transactions": [{
                "amount": {
                    "total": "7.47",
                    "currency": "USD",
                    "details": {
                        "subtotal": "7.41",
                        "tax": "0.03",
                        "shipping": "0.03"
                    }
                },
                "description": "This is the payment transaction description." 
            }]
        };

        paypal.payment.create(card_data, function(error, payment){
            if(error){
                console.error(error);
            } else {
                console.log(JSON.stringify(payment));
            }
        });
    }
});

In the section following the successful vaulting of the credit card, we then define our card_data object in order to process the payment. The main difference between a regular card payment (where you add in the card details) and processing via a vaulted payment in the structure of the card_data object, is the funding_instruments section, that we define under payer. Instead of defining the credit card information, we instead use the following object that contains the vault ID reference, and the payer ID:

"credit_card_token": {
    "credit_card_id": credit_card.id,
    "payer_id": credit_card.payer_id
}

Other than that, we simply set an intent of sale and define our transactions object, which details the payment to be made.

Lastly, we make a request to payment.create(...), passing in the card_data object that we just defined. If all is successful, we have now just vaulted a card and immediately processed a payment with it.

Recycle, Reuse, Reharm: How hackers use variants of known malware to victimize companies and what PayPal is doing to eradicate that capability

By and

“No need to reinvent the wheel.” We’ve heard it. We’ve used it. Is it a mark of laziness or leaving something as is because it’s effective? In the case of malware, it’s most certainly the latter. Several high profile hacks have received extensive news coverage in recent years. Seeing these attacks happen repeatedly leads cybersecurity experts to look for common threads in attack vectors and execution modes. Through years of data analysis, one trend is clear- while attacks vary many elements of the malware source codes are identical and are successfully reused. Below are some examples of attacks you may recognize but were unaware were related to previously known attack vectors that are still actively exploited:

  • 2011: Cyber espionage attacks that were launched on RSA and Lockheed-Martin, resulting in grave financial and operational damage used a variant of Poison Ivy, a well-known malware in use since 2006. To date, the cyber security community is still fighting derivatives.
  • 2013 and 2014: The infamous Target and Home Depot hacks were both carried out using variants of BlackPoS, a malware installed on point of sale systems designed to glean data from cards when swiped at the register.
  • 2014: The Sony hack was executed using Destrover, malware heavily reliant on code taken from Shamoon (used in the 2012 attack on Saudi Aramco) and DarkSeoul (used in the 2013 attack on South Korean banks and TV broadcasters).

How does it work?

There are three aspects of malware reuse that we’ve identified as particularly dangerous:

  • Code Reuse: Incorporate code from one malware into another
  • Semantic Equivalence: Make changes to the code but preserve the functions
  • Different Path, Same Target: Change/add functions to evade heuristics

To demonstrate a process malware developers use, we’ll pull an example from BlackPoS. Using code from a January 2015 blog post by Nick Hoffman, we can figuratively explain how reuse of existing techniques enabled the developers of BlackPoS to create a new variant and continue attacking a few months after the malware was discovered attacking Target. The process consists of at least three steps:

  • Once it is downloaded, it runs the CreateToolhelp32Snapshot API call, followed by Process32First in order to discover all the running processes on the computer. This is the exact process used by the Zeus “SpyEye” variant, PoS malware Alina, and PoS malware Backoff. The original BlackPoS variant used a different API call – EnumProcesses, yet the variant of BlackPoS discovered in August 2014 did change to this one. It is quite possible it copied this from Alina or Backoff.
  • Using the OpenProcess and ReadProcessMemory calls, the malware then reads processes that do not appear on its whitelist searching for credit card track data. This technique appeared in the original BlackPoS variant, as well as in Zeus “SpyEye” and Alina. Again, it is likely that this technique was copied from one of them.
  • The last step searches for certain identifiers of track 1 and track 2 data in the data of the processes read with ReadProcessMemory. The same step is seen in all PoS RAM scraping malware, such as Backoff.

Malware.Nov 2015.fw

It’s that easy. This malware does not include C&C communication, stealth, or persistence capabilities. All it needs in order to create these capabilities is copy code and techniques from similar malware that’s already out there. This process is a the base of all malware families, from PoS to ICS.

Cool story. What is PayPal doing about it?

At PayPal’s Center of Excellence in Bee’rsheva, Israel, we approach malware detection with the mentality that by identifying similar elements embedded in the code of existing malware like those illustrated above; we can predict attributes of future bugs and thwart them before they make it into the wild. Our goal is to render the reuse of existing malware ineffective and minimize scalable attacks. By forcing the total recreation of malware each time an attack is launched, we’re lengthening the time between attacks and dramatically increasing the cost of creating a vector.

Our predictive engine creates variants from existing malicious binary samples via an evolutionary algorithm. The results are tested in simulated environments and evaluated, thus supporting a machine learning training process for malware detectors, enabling them to locate hundreds of thousands of future malware variants in the wild, and head off future attacks.

While integrating the existing PayPal infrastructure  into the CyActive predictive detection model, PayPal’s Shlomi Boutnaru and Liran Tancman have been researching this method since 2012. It became a reality in 2013 when they launched CyActive, the cybersecurity company that PayPal acquired in 2015. The product integration is currently in progress and is expected to be a game changer in the risk management arena.  Shlomi’s January 2015 article on Techcrunch highlighted the dangers of malware reuse coupled with human error as key tactics expected to be used by hackers in 2015. We’re doing everything we can to ensure this prediction is eradicated in the foreseeable future.