def transactions(): """Display transactions that happened over a billing agreement """ start_date, end_date = "2014-07-01", "2014-07-20" billing_agreement = BillingAgreement.find(request.args.get('id', '')) transactions = billing_agreement.search_transactions(start_date, end_date) return render_template('history.html', transactions=transactions.agreement_transaction_list, description=request.args.get('description', ''))
def free_subscription(uid): """ Function to make free sunscription for user""" user_detail = User.by_id(uid) dash_redirect = url_for('userbp.dashboard') if int(uid) != int(current_user.id): dash_redirect = url_for('userbp.customers') if user_detail.payment_status == 1: configure_paypal() pay_info = Payment.byuser_id(uid) billing_agreement_detail = BillingAgreement.find( pay_info.PaymentDetail.billing_aggrement_id) cancel_note = {"note": "Canceling the agreement"} cancel_states = ['Active', 'Suspended'] if billing_agreement_detail.state in cancel_states: if billing_agreement_detail.cancel(cancel_note): user_detail.payment_status = 2 flash(MAKE_FREE_USER, 'success') flash(CANCEL_PLAN, 'success') else: errorlog.error('Cancel Current Plan Error', details=str(billing_agreement_detail.error)) flash(CANCEL_PLAN_ERROR, 'danger') else: errorlog.error('Cancel Current Plan Error', details=str(billing_agreement_detail.error)) flash(PLAN_NOT_ACTIVE, 'danger') else: user_detail.payment_status = 2 flash(MAKE_FREE_USER, 'success') db.session.commit() return redirect(dash_redirect)
def suspend_billing_agreement(self, billing_agreement): note = {"note": "Suspending the agreement"} if billing_agreement.suspend(note): # Would expect status has changed to Suspended billing_agreement = BillingAgreement.find(billing_agreement.id) print("Billing Agreement suspension successful! {} {}".format(billing_agreement.id, billing_agreement.state)) else: print("Billing Agreement suspension failed! {}".format(billing_agreement.error))
def reactivate_billing_agreement(self, billing_agreement): note = {"note": "Reactivating the agreement"} if billing_agreement.reactivate(note): # Would expect status has changed to Active billing_agreement = BillingAgreement.find(billing_agreement.id) print("Billing Agreement reactivation successful! {} {}".format(billing_agreement.id, billing_agreement.state)) else: print("Billing Agreement reactivation failed! {}".format(billing_agreement.error))
def get(self): payment_token = self.get_argument('payment_token') start_date, end_date = self.get_argument( 'start_date'), self.get_argument('end_date') billing_agreement = BillingAgreement.find(payment_token) transactions = billing_agreement.search_transactions( start_date, end_date) self.write({'response': transactions})
def cancel_billing_agreement(self, billing_agreement): note = {"note": "Canceling the agreement"} if billing_agreement.cancel(note): # Would expect status has changed to Cancelled billing_agreement = BillingAgreement.find(billing_agreement.id) print("Billing Agreement cancellation successful! {} {}".format(billing_agreement.id, billing_agreement.state)) else: print("Billing Agreement cancellation failed! {}".format(billing_agreement.error))
def get_billing_agreement(billing_agreement_id, paypal_mode, paypal_client_id, paypal_client_secret): return BillingAgreement.find(billing_agreement_id, api=Api({ 'mode': paypal_mode, 'client_id': paypal_client_id, 'client_secret': paypal_client_secret }))
def set_and_bill_balance_billing_agreement(self, billing_agreement): outstanding_amount = { "value": "10", "currency": "USD" } if billing_agreement.set_balance(outstanding_amount): billing_agreement = BillingAgreement.find(billing_agreement.id) print("Billing Agreement set_balance successful! {} {}".format(billing_agreement.id, billing_agreement.outstanding_balance.value)) outstanding_amount_note = { "note": "Billing Balance Amount", "amount": outstanding_amount } if billing_agreement.bill_balance(outstanding_amount_note): billing_agreement = BillingAgreement.find(billing_agreement.id) print("Billing Agreement bill_balance successful! {}".format(billing_agreement.outstanding_balance.value)) else: print("Billing Agreement bill_balance failed! {}".format(billing_agreement.error)) else: print("Billing Agreement set_balance failed! {}".format(billing_agreement.error))
def delete(self): data = agreement.parse_args() agr_id = data.get('agreement_id') current_username = get_jwt_identity()['username'] current_user = User.find_by_username(current_username) from paypalrestsdk import BillingAgreement import logging try: billing_agreement = BillingAgreement.find(agr_id) print("Billing Agreement [%s] has state %s" % (billing_agreement.id, billing_agreement.state)) cancel_note = {"note": "Canceling the agreement"} if billing_agreement.cancel(cancel_note): billing_agreement = BillingAgreement.find(agr_id) print("Billing Agreement [%s] has state %s" % (billing_agreement.id, billing_agreement.state)) else: print(billing_agreement.error) except ResourceNotFound as error: print("Billing Agreement Not Found") current_user.agreementId = '' current_user.subType = 'basic' current_user.save_to_db() access_token = create_access_token(identity = {'username': user.username, 'subscription': user.subType}) refresh_token = create_refresh_token(identity = {'username': user.username, 'subscription': user.subType}) return { "access_token": access_token, "refresh_token": refresh_token }
def check_paypal(self): try: subscription = BillingAgreement.find(self.paypal_subscription_id) if subscription.state.lower() != "suspended": end_date = subscription.agreement_details.next_billing_date else: end_date = subscription.agreement_details.last_payment_date # to be sure no errors with strptime method if end_date: end_date = datetime.strptime(end_date, "%Y-%m-%dT%H:%M:%SZ") status = (subscription.state.lower(), end_date) except ResourceNotFound: status = None return status
def cancel_current_plan(): """ Function to cancel the current plan """ try: get_uid = request.args.get('userid', default=None, type=int) uid = current_user.id profile_redirect = url_for('userbp.profile') dashboard_redirect = url_for('userbp.dashboard') if get_uid is not None and current_user.user_type == 'admin': uid = get_uid profile_redirect = url_for('userbp.profile', userid=uid) dashboard_redirect = url_for('userbp.dashboard', userid=uid) userinfo = User.by_id(uid) if userinfo.payment_status != 1: flash(PLAN_SUBSCRIPTION_ERROR, 'danger') return redirect(profile_redirect) configure_paypal() pay_info = Payment.byuser_id(uid) billing_agreement_detail = BillingAgreement.find( pay_info.PaymentDetail.billing_aggrement_id) cancel_note = {"note": "Canceling the agreement"} cancel_states = ['Active', 'Suspended'] if billing_agreement_detail.state in cancel_states: if billing_agreement_detail.cancel(cancel_note): userinfo.payment_status = 0 db.session.commit() flash(CANCEL_PLAN, 'success') return redirect(dashboard_redirect) else: errorlog.error('Cancel Current Plan Error', details=str(billing_agreement_detail.error)) flash(CANCEL_PLAN_ERROR, 'danger') else: flash(PLAN_NOT_ACTIVE, 'danger') except Exception as err: errorlog.error('Cancel Current Plan Error', details=str(err)) flash(CANCEL_PLAN_ERROR, 'danger') return redirect(profile_redirect)
def my_account(): """ Function to view my account having info abount subscription and payment history """ try: get_uid = request.args.get('userid', default=None, type=int) uid = current_user.id if get_uid is not None and current_user.user_type == 'admin': uid = get_uid userinfo = User.by_id(uid) trans_list = None billing_agreement = None account_detail = None if userinfo.payment_status == 1: account_detail = Payment.byuser_id(userinfo.id) get_date = datetime.strptime(str( userinfo.created_at), '%Y-%m-%d %H:%M:%S') - timedelta(days=1) start_date, end_date = get_date.strftime('%Y-%m-%d'), \ datetime.now().strftime("%Y-%m-%d") account_detail = Payment.byuser_id(userinfo.id) configure_paypal() billing_agreement = BillingAgreement.find( account_detail.PaymentDetail.billing_aggrement_id) transactions = billing_agreement.search_transactions( start_date, end_date) trans_list = transactions.agreement_transaction_list if trans_list is None: trans_list = [] credit_card_form = payment_form.credit_card() plan = Subscription.get_all(True) credit_card_form.payment_token.data = plan.subscription_id return render_template('payment/my_account.html', account_detail=account_detail, transactions=trans_list, agreement=billing_agreement, userinfo=userinfo, plan=plan, ccform=credit_card_form) except Exception as err: errorlog.error('My Account Error', details=str(err)) return render_template('error.html', message="Error!")
def put(self): data = json.loads(self.request.body.decode('utf-8')) billing_agreement_id = data['billing_agreement_id'] billing_agreement = BillingAgreement.find(billing_agreement_id) value = { "description": "New Description", "name": "New Name", "shipping_address": { "line1": "StayBr111idge Suites", "line2": "Cro12ok Street", "city": "San Jose", "state": "CA", "postal_code": "95112", "country_code": "US" } } billing_agreement_update_attributes = [{ "op": "replace", "path": "/", "value": value }] self.write({'response': billing_agreement})
def agreement_details(): billing_agreement = BillingAgreement.find(request.args.get('id', '')) return render_template('details.html', agreement=billing_agreement)
from paypalrestsdk import BillingAgreement import logging BILLING_AGREEMENT_ID = "I-HT38K76XPMGJ" try: billing_agreement = BillingAgreement.find(BILLING_AGREEMENT_ID) print("Got Billing Agreement Details for Billing Agreement[%s]" % (billing_agreement.id)) billing_agreement_update_attributes = [ { "op": "replace", "path": "/", "value": { "description": "New Description", "name": "New Name", "shipping_address": { "line1": "StayBr111idge Suites", "line2": "Cro12ok Street", "city": "San Jose", "state": "CA", "postal_code": "95112", "country_code": "US" } } } ] if billing_agreement.replace(billing_agreement_update_attributes): print("Billing Agreement [%s] name changed to [%s]"
from paypalrestsdk import BillingAgreement, ResourceNotFound import logging logging.basicConfig(level=logging.INFO) try: billing_agreement = BillingAgreement.find("I-HT38K76XPMGJ") print("Got Billing Agreement Details for Billing Agreement[%s]" % (billing_agreement.id)) except ResourceNotFound as error: print("Billing Agreement Not Found")
def cancel_subscription(request, membership): subject = "" message = "" reasons = "" if request.method == 'POST': # save reasons of cancellation to the db for reason in request.POST.getlist('reason'): if reason != 'Other': CancellationReasons(reason=reason, membership_type=membership, user=request.user).save() reasons += str(reason) + ", " else: CancellationReasons(reason=request.POST["other-reasons"], membership_type=membership, user=request.user).save() reasons += request.POST["other-reasons"] if membership == 'stripe': # modify used to hit API only once stripe.Subscription.modify( request.user.stripe_subscription_id, cancel_at_period_end=True, ) request.user.cancel_at_period_end = True request.user.save() message = "I've cancelled subscription': " + str(request.user.stripe_subscription_id) + "\n"\ + "\n" + "Reasons: " + reasons subject = "Cancellation of Stripe subscription" messages.success(request, 'Your subscription has been canceled') elif membership == 'paypal': cancel_note = {"note": "Canceling the agreement"} if BillingAgreement.find( request.user.paypal_subscription_id).cancel(cancel_note): messages.success(request, 'Your subscription has been canceled') request.user.cancel_at_period_end = True request.user.save() message = "I've cancelled subscription': " + str(request.user.paypal_subscription_id) + "\n" \ + "\n" + "Reasons: " + reasons subject = "Cancellation of Paypal subscription" # send email with cancel request if automatic cancellation failed else: message = "I would like to cancel my subscription id: " + str(request.user.paypal_subscription_id) + "\n" \ + "Reasons: " + reasons subject = "Cancellation request of paypal subscription" messages.warning( request, 'Something went wrong. Your subscription has been not canceled. ' 'Email with cancellation request has been sent to ZappyCode' ) elif membership == 'apple': messages.success( request, 'Email with cancel request of your subscription ' 'has been successfully sent to ZappyCode. ' 'We cancel your subscription as soon as it\'s possible') message = "I would like to cancel my subscription id: " + str(request.user.apple_product_id) + "\n"\ + "Apple receipt: " + str(request.user.apple_receipt) + "\n" + "Reasons: " + reasons subject = "Cancellation request of Apple subscription" send_mail(subject, request.user.email + ' ' + message, env.str('ADMIN_EMAIL'), [env.str('ADMIN_EMAIL')], fail_silently=False) return redirect('account') return redirect('home')
from paypalrestsdk import BillingAgreement import logging BILLING_AGREEMENT_ID = "I-HT38K76XPMGJ" try: billing_agreement = BillingAgreement.find(BILLING_AGREEMENT_ID) print("Billing Agreement [%s] has state %s" % (billing_agreement.id, billing_agreement.state)) cancel_note = {"note": "Canceling the agreement"} if billing_agreement.cancel(cancel_note): # Would expect status has changed to Cancelled billing_agreement = BillingAgreement.find(BILLING_AGREEMENT_ID) print("Billing Agreement [%s] has state %s" % (billing_agreement.id, billing_agreement.state)) else: print(billing_agreement.error) except ResourceNotFound as error: print("Billing Agreement Not Found")
def get_billing_agreement(self, agreement_id): billing_agreement = BillingAgreement.find(agreement_id) return billing_agreement
def agreement_details(): billing_agreement = BillingAgreement.find(request.args.get('id', '')) return Response(json.dumps(billing_agreement.to_dict()), mimetype='application/json')
def get(self): payment_token = self.get_argument('payment_token') billing_agreement = BillingAgreement.find(payment_token) print('billing_agreement', billing_agreement) self.write({'response': 'billing_agreement'})