I'm trying to implement PayPal subscription functionality into my app and this is where I got so far. I created a function which handles the payment process, and subscribes the user to the selected subscription plan, but I can't figure how can I create similar function for manual subscription canceling? Is that possible? I mean, how can I cancel my subscription as a user?
This is my payment process function.
def process_order(request, plan_slug):
host = request.get_host()
plan = Subscription.objects.get(slug__iexact=plan_slug)
request.session['plan_id'] = plan.pk
order, created = Order.objects.get_or_create(
plan=plan,
user=request.user,
total_cost=plan.sum_price,
)
if created:
request.session['order_id'] = order.pk
elif order:
request.session['order_id'] = order.pk
order.created = timezone.now()
order.save()
if plan.slug == 'some_slug':
user = Customuser.objects.get(email=request.user.email)
user.subscription_plan = plan
user.sub_renewal_date = None
user.save()
messages.success(request, 'You are now some_slug plan!')
return redirect('accounts:profile', user.email)
paypal_dict = {
"cmd": "_xclick-subscriptions",
'business': settings.PAYPAL_RECEIVER_EMAIL,
'a1': 1,
'period1': '1 M',
"a3": plan.sum_price, # monthly price
"p3": plan.plan_duration, # duration of each unit (depends on unit)
"t3": 'M', # duration unit ("M for Month")
"src": "1", # make payments recur
"sra": "1", # reattempt payment on payment error
"no_note": "1",
'item_name': plan_slug,
'item_number': order.pk,
'invoice': str(order.pk),
'custom': {
'order': order.pk,
'user': request.user.email,
},
'currency_code': 'USD',
'notify_url': 'http://{}{}'.format(host,
reverse('billing:paypal-ipn')),
'return_url': 'http://{}{}'.format(host,
reverse('billing:payment_done')),
'cancel_return': 'http://{}{}'.format(host,
reverse('billing:payment_canceled')),
}
form = CustomPayPalForm(initial=paypal_dict)
context = {
'plan': plan,
'form': form,
}
return render(request, 'subscriptions/checkout.html', context)
It can be done by using django-paypal ion signals, which are sent by PayPal API back to the server.