'Get Paypal server side subscription with Flask

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.



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Preston PHX