paypalpaypal-buttons

PayPal Checkout / Smart Buttons - Error with createOrder & empty fields which are optional


With the createOrder function I am passing some of the customer information, mainly to pre-populate the credit / debit card fields.

Something like phone number optional at checkout. With the following code if the order_phone field has a phone number, it works. If it is empty it returns an error and stops. Is there any way around this or let PayPal know it is optional? This happens with other variables too which may be optional for the customer.

    createOrder: function(data, actions) {
      return actions.order.create({
        purchase_units: [{
            amount: {
                value: $("#grand_total").val(),
                currency_code: ("#grand_total").val()
            }
        }],
        "application_context" : { 
             "shipping_preference":"NO_SHIPPING"
        },
        payer: {
            name: {
                given_name: $("#first_name").val(),
                surname: $("#last_name").val()
            },
            email_address: $("#email_address").val(),
                phone: {
                phone_number: {
                    national_number: $("#order_phone").val()
                }
            }
        },
    });
},

Solution

  • Try something like

        createOrder: function(data, actions) {
          var myOrder = {
            purchase_units: [{
                amount: {
                    value: $("#grand_total").val(),
                    currency_code: "USD"
                }
            }],
            "application_context" : { 
                 "shipping_preference":"NO_SHIPPING"
            },
            payer: {
                name: {
                    given_name: $("#first_name").val(),
                    surname: $("#last_name").val()
                },
                email_address: $("#email_address").val(),
            },
          };
        
          var phone = $("#order_phone").val();
          if(phone) myOrder.payer.phone = {
                      phone_number: {
                        national_number: phone
                      }
                    };
          return actions.order.create(myOrder);
        },