Search code examples
paypalpaypal-sandboxpaypal-rest-sdk

Paypal Smart Button Check Postal Code onApprove


The problem: I am trying to figure out how to check the if postal code (entered during the paypal smart button check-out) meets specific requirements. I have the createOrder, and onApprove object attributes I would like to check the postal code before i capture the payment so i can reject it, and cancel the order.

paypal.Buttons(
    {
        createOrder: function(data, actions) {

        // This function sets up the details of the transaction, including the amount and line item details.
            return actions.order.create({
                purchase_units: 
                [
                    {
                        description: "Raffle Tickets",
                        custom_id: $('#cartID').val(),
                        soft_descriptor: "soft_descriptor",
                        amount: {
                            currency_code: "CAD",
                            value: cartVal,
                            breakdown: {
                                item_total: {
                                    currency_code: "CAD",
                                    value: cartVal
                                }
                            }
                        },
                        items: itemList

                    }
                ]
            });
        },
        onApprove: function(data, actions) {

            //id like to check the postal code here, or maybe do an ajax call then on success, call the
            //capture function below to finalize the payment.

            // This function captures the funds from the transaction.
            return actions.order.capture().then(function(details) {
            // This function shows a transaction success message to your buyer.

                $('#details').val(JSON.stringify(details));
                $('#frmConfirm').submit();
            });
        }

    }).render('#paypal-button-container');

Solution

  • return actions.order.get().then(function(data,actions) {
    
        console.log(data);
        /* if logic on data.payer.address.postal_code goes here */
    
        actions.order.capture().then(function(details) { 
            $('#details').val(JSON.stringify(details));
            $('#frmConfirm').submit();
        }
    });
    

    You mentioned AJAX; there are server-side equivalent APIs, if you want to switch from this client-side implementation to one that uses code on the server to validate. In that case the front-end would look more like this: https://developer.paypal.com/demo/checkout/#/pattern/server , and there is a v2/orders API call to get the details of the approved order before capturing it.