def subscribe(): billing_agreement = BillingAgreement({ "name": "Organization plan name", "description": "Agreement for <Monthly Plan>", "start_date": (datetime.now() + timedelta(hours=1)).strftime('%Y-%m-%dT%H:%M:%SZ'), "plan": { "id": "P-3NF352338H658800LZS4KMVY" }, "payer": { "payment_method": "paypal" }, "shipping_address": { "line1": "StayBr111idge Suites", "line2": "Cro12ok Street", "city": "San Jose", "state": "CA", "postal_code": "95112", "country_code": "US" } }) if billing_agreement.create(): for link in billing_agreement.links: if link.rel == "approval_url": approval_url = link.href return approval_url else: return billing_agreement.error
def post(self): data = json.loads(self.request.body.decode('utf-8')) billing_agreement = BillingAgreement({ "name": "Organization plan name", "description": "Agreement for " + data['name'], "start_date": (datetime.datetime.now() + datetime.timedelta(days=365)).strftime('%Y-%m-%dT%H:%M:%SZ'), "plan": { "id": data['id'] }, "payer": { "payment_method": "paypal" }, "shipping_address": { "line1": "StayBr111idge Suites", "line2": "Cro12ok Street", "city": "San Jose", "state": "CA", "postal_code": "95112", "country_code": "US" } }) if billing_agreement.create(): for link in billing_agreement.links: if link.rel == "approval_url": approval_url = link.href msg = approval_url else: msg = billing_agreement.error print(msg) self.write({'response': msg})
def subscribe(): """Customer subscribes to a billing plan to form a billing agreement """ if session.get('logged_in') and session.get('customer'): billing_agreement = BillingAgreement({ "name": "Organization plan name", "description": "Agreement for " + request.args.get('name', ''), "start_date": "2015-02-19T00:37:04Z", "plan": { "id": request.args.get('id', '') }, "payer": { "payment_method": "paypal" }, "shipping_address": { "line1": "StayBr111idge Suites", "line2": "Cro12ok Street", "city": "San Jose", "state": "CA", "postal_code": "95112", "country_code": "US" } }) if billing_agreement.create(): for link in billing_agreement.links: if link.rel == "approval_url": approval_url = link.href return redirect(approval_url) else: print(billing_agreement.error) return redirect(url_for('subscriptions')) else: return redirect(url_for('login'))
def create_billing_agreement(self, billing_plan_id): delay = timedelta(days=2) #delay = timedelta(hours=1) agreement = { "name": "Agreement for Basic Plan subscription", "description": "Agreement for Basic Plan subscription", "start_date": (datetime.now()+delay).strftime('%Y-%m-%dT%H:%M:%SZ'), "plan": { "id": billing_plan_id }, "payer": { "payment_method": "paypal" }, } billing_agreement = BillingAgreement(agreement) if billing_agreement.create(): print("Billing Agreement creation successful! {}".format(billing_agreement.id)) print(billing_agreement) for link in billing_agreement.links: print(link.rel) print(link.href) if link.rel == "approval_url": approval_url = link.href print(approval_url) else: print("Billing Agreement creation failed! {}".format(billing_agreement.error)) return billing_agreement
def plan_payment_url(value): plan_details = current_app.paypal['plans'][value] billing_agreement = BillingAgreement({ "name": g.user.name, "description": "Agreement for %s" % plan_details['name'], "start_date": (datetime.utcnow() + timedelta(minutes=1)).strftime("%Y-%m-%dT%H:%M:%SZ"), "plan": { "id": plan_details.id }, "payer": { "payment_method": "paypal" }, }) import ipdb ipdb.set_trace() # XXX BREAKPOINT if billing_agreement.create(): for link in billing_agreement.links: if link.rel == "approval_url": approval_url = link.href return approval_url raise RuntimeError('Could not get approval url for plan %s.' % plan_details.name)
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 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 get(self): from flask import request from datetime import datetime from paypalrestsdk import BillingAgreement from app import app from flask import redirect now = datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ') billing_agreement = None if request.args.get('sub') == 'pro': billing_agreement = BillingAgreement({ "name": "Pro Agreement", "description": "- up to 5 updates get saved;\n-Play store researches;\n-News researches;", "start_date": now, "plan": { "id": app.config['PRO'] }, "payer": { "payment_method": "paypal" } }) else: billing_agreement = BillingAgreement({ "name": "Premium Agreement", "description": "- unlimited updates;\n- all the modules;", "start_date": now, "plan": { "id": app.config['PREMIUM'] }, "payer": { "payment_method": "paypal" } }) if billing_agreement.create(): print(billing_agreement.links) for link in billing_agreement.links: if link.method == "REDIRECT": redirect_url = str(link.href) return redirect(redirect_url) else: print(billing_agreement.error)
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 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 execute(): """Customer redirected to this endpoint by PayPal after payment approval """ if session.get('logged_in') and session.get('customer'): payment_token = request.args.get('token', '') billing_agreement_response = BillingAgreement.execute(payment_token) return redirect(url_for('agreement_details', id=billing_agreement_response.id)) else: return redirect(url_for('login'))
def get(self): from flask import request, redirect from paypalrestsdk import BillingAgreement token = request.args.get('token') billing_agreement_response = BillingAgreement.execute(token) print("BillingAgreement[%s] executed successfully" % (billing_agreement_response.id)) return redirect('http://localhost:4200/paypal_redirect?done={}&type={}&id={}'.format( 1, 'premium', billing_agreement_response.id ))
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 _process_agreement(self, agreement: sdk.BillingAgreement): transactions = agreement.search_transactions("2016-01-01", date.today().isoformat()) for transaction in transactions['agreement_transaction_list']: stat = transaction["status"] if stat == 'Created': pass # Might want to do something with this, eventually. elif stat == 'Completed': self._process_recurring_payment(agreement, transaction) elif stat == 'Canceled': pass # Might want to do something with this, eventually. else: print("Unrecognized status: " + stat)
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 plan_payment_url(value): plan_details = current_app.paypal['plans'][value] billing_agreement = BillingAgreement({ "name": g.user.name, "description": "Agreement for %s" % plan_details['name'], "start_date": (datetime.utcnow() + timedelta(minutes=1)).strftime("%Y-%m-%dT%H:%M:%SZ"), "plan": { "id": plan_details.id }, "payer": { "payment_method": "paypal" }, }) import ipdb; ipdb.set_trace() # XXX BREAKPOINT if billing_agreement.create(): for link in billing_agreement.links: if link.rel == "approval_url": approval_url = link.href return approval_url raise RuntimeError('Could not get approval url for plan %s.' % plan_details.name)
def execute(): """ Function to execute plan after redirecting from paypal site after customer agreement """ try: configure_paypal() payment_token = request.args.get('token', '') billing_agreement_response = BillingAgreement.execute(payment_token) plans = Subscription.get_all() action = url_for('userbp.dashboard') billing_action = url_for('paymentbp.billing') if 'id' in billing_agreement_response: pdobj = PaymentDetail( amount=plans.subscription_price, subscription_id=plans.id, payment_status='Success', payment_date=func.now(), billing_aggrement_id=billing_agreement_response.id, payment_token=payment_token, payment_mode='paypal') db.session.add(pdobj) db.session.commit() user_id = current_user.id if 'app_user_id' in session: user_id = session['app_user_id'] session.pop('app_user_id') action = url_for('userbp.dashboard', userid=user_id) billing_action = url_for('paymentbp.billing', userid=user_id) pobj = Payment(user_id=user_id, payment_detail_id=pdobj.id, created_at=func.now(), updated_at=func.now()) db.session.add(pobj) get_user = User.by_id(int(user_id)) get_user.payment_status = True db.session.commit() flash(PLAN_EXECUTED, 'success') return redirect(action) else: flash(PLAN_EXECUTED_ERROR, 'danger') return redirect(billing_action) except Exception as err: errorlog.error('Subscribe Error', details=str(err)) return render_template('error.html', message="Error!")
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 execute_agreement(): payment_token = request.args.get('token', '') billing_agreement_response = BillingAgreement.execute(payment_token) return (url_for('agreement_details', id=billing_agreement_response.id)) return 'execute'
def agreement_details(): billing_agreement = BillingAgreement.find(request.args.get('id', '')) return Response(json.dumps(billing_agreement.to_dict()), mimetype='application/json')
from paypalrestsdk import BillingAgreement import logging logging.basicConfig(level=logging.INFO) billing_agreement = BillingAgreement({ "name": "Fast Speed Agreement", "description": "Agreement for Fast Speed Plan", "start_date": "2015-02-19T00:37:04Z", "plan": { "id": "P-0NJ10521L3680291SOAQIVTQ" }, "payer": { "payment_method": "paypal" }, "shipping_address": { "line1": "StayBr111idge Suites", "line2": "Cro12ok Street", "city": "San Jose", "state": "CA", "postal_code": "95112", "country_code": "US" } }) if billing_agreement.create(): print("Billing Agreement created successfully") else: print((billing_agreement.error))
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")
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")
from paypalrestsdk import BillingAgreement import logging logging.basicConfig(level=logging.INFO) billing_agreement = BillingAgreement({ "name": "Fast Speed Agreement", "description": "Agreement for Fast Speed Plan", "start_date": "2015-02-19T00:37:04Z", "plan": { "id": "P-0NJ10521L3680291SOAQIVTQ" }, "payer": { "payment_method": "paypal" }, "shipping_address": { "line1": "StayBr111idge Suites", "line2": "Cro12ok Street", "city": "San Jose", "state": "CA", "postal_code": "95112", "country_code": "US" } }) if billing_agreement.create(): print("Billing Agreement created successfully") else: print(billing_agreement.error)
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]"
# Use this call to execute (complete) a PayPal BillingAgreement that has # been approved by the payer. from paypalrestsdk import BillingAgreement import logging logging.basicConfig(level=logging.INFO) billing_agreement = BillingAgreement({ "name": "Fast Speed Agreement", "description": "Agreement for Fast Speed Plan", "start_date": "2015-02-19T00:37:04Z", "plan": { "id": "P-0NJ10521L3680291SOAQIVTQ" }, "payer": { "payment_method": "paypal" }, "shipping_address": { "line1": "StayBr111idge Suites", "line2": "Cro12ok Street", "city": "San Jose", "state": "CA", "postal_code": "95112", "country_code": "US" } }) # After creating the agreement, redirect user to the url provided in links array # entry with method field set to REDIRECT if billing_agreement.create(): print("Billing Agreement created successfully") for link in billing_agreement.links:
def get_billing_agreement(self, agreement_id): billing_agreement = BillingAgreement.find(agreement_id) return billing_agreement