javascriptpaypalpaypal-sandboxpaypal-rest-sdk

PayPal: Handling and Testing Declined Cards with Javascript SDK+REST


I need to handle declined cards in my implementation, and test that it works.

  1. For testing, I see some stuff about using REST headers, but don't see how that can be used from the Javascript SDK. It seems there aren't test card #'s? They make testing quick, simple, and reliable; I'm shocked if there aren't any: Braintree's don't seem to work.
  2. If a card is declined, what comes back from actions.order.capture()?
  3. If onError gets called, what is it's argument: an error message string, an error object as a JSON string, or a decoded error object? Ideally I'd like to call actions.restart(). As a fallback my server-side will route to an order-declined page, and the user can click through to edit the payment.

My current client code (based on various samples) looks like this:

BuildNewPayPalButtons = function(val)
{
    paypal.Buttons({
    createOrder: function(data, actions) {
// Set up the transaction
        return actions.order.create({
        application_context: {
            shipping_preference: 'NO_SHIPPING' // NOT an enum
        },
        purchase_units: [{
            amount: {
            value: '$amt'
            },
            description: 'my favorite product',
            invoice_id: '$sessid'
        }]
        });
    },
    onApprove: function(data, actions) {
        return actions.order.capture().then(function(orderData) {
        var trns = orderData.purchase_units[0].payments.captures[0];

        console.error('OK: Whole JSON ', JSON.stringify(orderData));

        // Send the transaction id to the server for verification
        window.location.href = "$payurl&paymID=" + trns.id;
        });
    },
    onCancel: function(data) {
        window.location.href = "$cancelurl";
    },
    onError: function(err) {
        console.error('error from the onError callback', err);
        window.location.href = "/unimplemented_error.html";
    }
    }).render('#paypal-button-container');
}

It would be nice if the "Complete Javascript SDK" documentation could be expanded to live up to its name.


Solution

  • 2024 edit: actions.order.capture() is deprecated, do not use in any new integration


    When using a client-side actions.order.capture(), declines are handled automatically. See the note here.

    Handling of declines is only necessary for a server-side API capture, as in this example.


    Optionally, you can implement onError to show a generic failure message if some random uncaught 500 error situation arises, but those are a separate matter from declines, and rarely encountered.