Search code examples
paypal-sandboxpaypal-ipnpaypal-subscriptions

Smart Payment Buttons passing custom variable for IPN


I have two Smart button on my website for a monthly subscription (working well). I successfully receive the IPN response with the payment information ready to be added to the Database. But I need to get the UserID of my application with the IPN response.

How can I pass custom variable with my Smart payment button so it can be passed to the IPN (for buying transaction and refund/cancellation ones if possible?)

Here is my Smart button code :

<div id="paypal_button"></div>

<script src="https://www.paypal.com/sdk/js?client-id=[ID]...></script>

<script>
paypal.Buttons({
    style:{
        color:"blue",
        shape:"rect",
        label:"paypal",
        tagline:false
    },
    createSubscription: function(data, actions) {
        return actions.subscription.create({'plan_id': 'P-02S33....'});
    },
    onApprove: function(data, actions) {
        alert('You have successfully created subscription ENTERPRISE' + data.subscriptionID);
    }
}).render('#paypal_button');
</script>

Solution

  • From June 2020 you can pass a custom_id with the paypal subscription button like this:

      createSubscription: function(data, actions) {
        return actions.subscription.create({
          plan_id: "P-1234567897897AAA",
          custom_id: "1344", // for example your internal userid
        });
      },
    

    Now with the webhook (if you use PHP):

    // get data from Paypal Webhook POST
    $data = json_decode(file_get_contents("php://input"));
    
    error_log('custom_id: '.$data->resource->custom_id);
    
    // also helpful for debugging
    error_log(print_r($data, true));
    

    Events that have the custom_id included as described above:

    • BILLING.SUBSCRIPTION.CREATED
    • BILLING.SUBSCRIPTION.ACTIVATED

    For event:

    • PAYMENT.SALE.COMPLETED

    You need to use:

    error_log('custom_id: '.$data->resource->custom);
    

    Without the _id in the end.


    Note: I have written a comprehensive tutorial that hopefully will help developers to get things done. Tutorial: How to integrate Paypal Subscription API with PHP and Javascript (2021) - Complete Guide