1

I'd like to have a simple solution to get the subscription ID after a payment approval in a Flask app.

Paypal provides this code only for client side:

<div id="paypal-button-container-P-REF"></div>
<script src="https://www.paypal.com/sdk/js?client-id=REF_ID=subscription" data-sdk-integration-source="button-factory"></script>
<script>
  paypal.Buttons({
      style: {
          shape: 'pill',
          color: 'gold',
          layout: 'vertical',
          label: 'subscribe'
      },
      createSubscription: function(data, actions) {
        return actions.subscription.create({
          /* Creates the subscription */
          plan_id: 'P-REF',
          quantity: 1 // The quantity of the product for a subscription
        });
      },
      onApprove: function(data, actions) {
        alert(data.subscriptionID); // You can add optional success message for the subscriber here

        actions.redirect('/thankyou', _external=True);
      }
  }).render('#paypal-button-container-REF'); // Renders the PayPal button
</script>

In server side, it should be something like:

@app.route('/upgrade',methods = ['POST','GET'])
@login_required
def upgrade():
    global user, user_email,user_category
    
    print(request.method )
    if request.method == 'POST':
        subscriptionID = request.args.get('subscriptionID')
        print(subscriptionID)
        
        if subscriptionID == None:
            flash('Payment error, please try again.','error')
        else:
            flash('Payment successful, thanks!','success')
            
            insert_payment(subscriptionID,user.id,'best_plan')#Add payment id to DB
            
            update_user_subscription(user.id,'best_plan')#Update user plan
            
            
    return render_template('upgrade.html', u_email=user_email, u_category = user_category)

But I need to retrieve the subscriptionID with a post method to save it in a database.

The client base method doesn't send back post information.

Any idea to do it easily with flask and JS? I don't understand how any e-market could work only with a client side code.

Note that the code available about server side in Paypal is mainly for classic order payment, not subscriptions.

NicolasSens
  • 117
  • 1
  • 9

1 Answers1

0

Subscribe to a webhook for the PAYMENT.SALE.COMPLETED event. This way you will get notifications for every payment on the subscription, not just the first one.

Preston PHX
  • 27,642
  • 4
  • 24
  • 44
  • Thanks. It is the best solution indeed. One last question: How do I know the user ID from a webhook from Paypal, in order to make the link between the subscription and the user ID in my DB? – NicolasSens May 13 '22 at 14:12
  • It seems the answer is here already: https://stackoverflow.com/questions/68240529/django-paypal-how-to-pass-user-id-with-webhooks-or-in-subscription – NicolasSens May 13 '22 at 14:16