def populate_by_name():
    web.template.create('Maidstone Hackspace')
    header('Maidstone Hackspace Donations')

    pledge = donate.get_pledge({'name': '#lair'}).get()

    import gocardless
    gocardless.environment = gocardless_environment
    gocardless.set_details(**gocardless_credentials)
    merchant = gocardless.client.merchant()

    web.template.body.append('Adding Badges')
    badges.create_badge().execute({'name': 'member'})
    badges.create_badge().execute({'name': 'backer'})
    badges.create_badge().execute({'name': 'teacher'})
    badges.create_badge().execute({'name': 'chairman'})
    badges.create_badge().execute({'name': 'treasurer'})
    badges.create_badge().execute({'name': 'secretary'})

    web.template.body.append('Populating users')
    user_list = {}
    #make sure we have all users in the system
    #~ users_emails = []
    for user in merchant.users():
        user_list[user.id] = user.email
        #~ users_emails.append(user.email)
        site_user.create_basic_user().execute({
            'email': user.email,
            'first_name': user.first_name,
            'last_name': user.last_name
        })

    #get the users ids and emails 
    #~ users = {}
    #~ for member in members.get_members():
        #~ for key, value in user_list.items():
            #~ if value == member.get('email'):
                #~ user_list[key] = member.get('user_id')

    badge_lookup = {badge.get('name'):badge.get('id') for badge in badges.fetch_badges()}

    web.template.body.append('Setting Donation Badges')
    environment = int(gocardless_environment=='production')
    for bill in merchant.bills():
        web.template.body.append(str(bill))

        matched_user = None
        for user_id, user_email in user_list.items():
            if user_email == user.email:
                matched_user = user_id

        donate.add_payment().execute({'user_id': matched_user,'pledge_id': pledge.get('id') , 'reference': bill.id, 'amount': bill.amount_minus_fees, 'environment': environment})

        if matched_user:
            badges.assign_badge().execute({'badge_id': badge_lookup.get('backer'), 'user_id': matched_user})

    return web.render()
def populate_by_name():
    pledge = donate.get_pledge({'name': '#lair'}).get()
    import gocardless
    gocardless.environment = gocardless_environment
    gocardless.set_details(**gocardless_credentials)
    merchant = gocardless.client.merchant()
    for bill in merchant.bills():
        environment = int(gocardless_environment=='production')
        donate.add_payment().execute({'pledge_id':pledge.get('id','') , 'reference': bill.id, 'amount': bill.amount_minus_fees, 'environment': environment})
    return abort()
def submit_donation():
    import gocardless
    gocardless.environment = gocardless_environment
    print app_domain
    gocardless.set_details(**gocardless_credentials)
    url = gocardless.client.new_bill_url(request.form.get('amount'),
                                         name=request.form.get('reference'),
                                         redirect_uri='%s/donate/success' %
                                         app_domain)
    #~ redirect_uri='%s/donate/success' % gocardless_redirect_uri if gocardless_redirect_uri else app_domain)
    return redirect(url)
 def test_set_details_valueerror_raised_when_details_not_present(self):
     details = mock_account_details.copy()
     details["access_token"] = details["token"]
     details.pop("token")
     for key in details.keys():
         #make sure that every key is required by passing in a hash with
         #all but one key missing
         invalid_details = details.copy()
         invalid_details.pop(key)
         with self.assertRaises(ValueError):
             gocardless.set_details(**invalid_details)
def pay_membership():
    import gocardless
    
    gocardless.environment = gocardless_enviroment
    gocardless.set_details(**gocardless_credentials)
    url = gocardless.client.new_subscription_url(
        amount=request.form.get('amount'), 
        interval_length=1, 
        interval_unit="month",
        name="Membership Subscription for MH0001")
    return redirect(url)
Exemple #6
0
def pay_membership():
    import gocardless

    gocardless.environment = gocardless_enviroment
    gocardless.set_details(**gocardless_credentials)
    url = gocardless.client.new_subscription_url(
        amount=request.form.get('amount'),
        interval_length=1,
        interval_unit="month",
        name="Membership Subscription for MH0001")
    return redirect(url)
 def test_set_details_valueerror_raised_when_details_not_present(self):
     details = mock_account_details.copy()
     details["access_token"] = details["token"]
     details.pop("token")
     for key in details.keys():
         #make sure that every key is required by passing in a hash with
         #all but one key missing
         invalid_details = details.copy()
         invalid_details.pop(key)
         with self.assertRaises(ValueError):
             gocardless.set_details(**invalid_details)
def submit_donation():
    import gocardless
    gocardless.environment = gocardless_environment
    print app_domain
    gocardless.set_details(**gocardless_credentials)
    url = gocardless.client.new_bill_url(
        request.form.get('amount'),
        name=request.form.get('reference'),
        redirect_uri='%s/donate/success' % app_domain)
        #~ redirect_uri='%s/donate/success' % gocardless_redirect_uri if gocardless_redirect_uri else app_domain)
    return redirect(url)
Exemple #9
0
    def __init__(self, config):
        self.config = config
        with open(config.get('xero', 'private_key_file')) as keyfile:
            rsa_key = keyfile.read()

        credentials = PrivateCredentials(config.get('xero', 'consumer_key'), rsa_key)
        self.xero = Xero(credentials)
        gocardless.environment = config.get('gocardless', 'environment')
        gocardless.set_details(app_id=config.get('gocardless', 'app_id'),
                               app_secret=config.get('gocardless', 'app_secret'),
                               access_token=config.get('gocardless', 'access_token'),
                               merchant_id=config.get('gocardless', 'merchant_id'))
        self.gc_client = gocardless.client
    def __init__(self, provider='gocardless', style='payment', mode='sandbox'):
        self.provider = provider
        self.environment = int(mode=='production')
        self.provider_id = PROVIDER_ID.get(provider)

        if provider == 'paypal':
            paypal.configure(**settings.payment_providers[provider]['credentials'])
            print(settings.payment_providers[provider]['credentials'])
            return

        #~ environment = int('production' = settings.payment_providers[provider]['environment'])
        gocardless.environment = settings.payment_providers[provider]['environment']
        gocardless.set_details(**settings.payment_providers[provider]['credentials'])
        merchant = gocardless.client.merchant()
Exemple #11
0
    def __init__(self, config):
        self.config = config
        with open(config.get("xero", "private_key_file")) as keyfile:
            rsa_key = keyfile.read()

        credentials = PrivateCredentials(config.get("xero", "consumer_key"), rsa_key)
        self.xero = Xero(credentials)
        gocardless.environment = config.get("gocardless", "environment")
        gocardless.set_details(
            app_id=config.get("gocardless", "app_id"),
            app_secret=config.get("gocardless", "app_secret"),
            access_token=config.get("gocardless", "access_token"),
            merchant_id=config.get("gocardless", "merchant_id"),
        )
        self.gc_client = gocardless.client
def populate_by_name():
    pledge = donate.get_pledge({'name': '#lair'}).get()
    import gocardless
    gocardless.environment = gocardless_environment
    gocardless.set_details(**gocardless_credentials)
    merchant = gocardless.client.merchant()
    for bill in merchant.bills():
        environment = int(gocardless_environment == 'production')
        donate.add_payment().execute({
            'pledge_id': pledge.get('id', ''),
            'reference': bill.id,
            'amount': bill.amount_minus_fees,
            'environment': environment
        })
    return abort()
def success_donation():
    # confirm the payment

    bill_id = request.args.get('resource_id')
    try:
        import gocardless
        gocardless.environment = gocardless_environment
        gocardless.set_details(**gocardless_credentials)
        gocardless.client.confirm_resource(request.args)
        web.page.create('Thanks for your donation')
        web.paragraph.create("""Thanks your payment has been recieved.""")
    except:
        # TODO log what actually has gone wrong
        web.page.create('Something went wrong')
        web.paragraph.create(
            """We could not confirm the payment something may have gone terribly wrong."""
        )

    if bill_id:
        bill = gocardless.client.bill(bill_id)
        pledge = donate.get_pledge({'name': bill.name}).get()

        #~ print dir(bill)

        print bill.amount
        print bill.amount_minus_fees
        print bill.charge_customer_at
        print bill.created_at
        print bill.name
        print bill.payout
        print bill.status
        print bill.user
        environment = int(gocardless_environment == 'production')
        donate.add_payment().execute({
            'pledge_id': pledge.get('name', ''),
            'reference': bill_id,
            'amount': bill.amount_minus_fees,
            'environment': environment
        })

    web.template.create('Maidstone Hackspace')
    header('Maidstone Hackspace Donations')
    web.page.create('Thanks for your donation')
    web.paragraph.create("""Thanks your payment has been recieved.""")
    web.page.section(web.paragraph.render())
    web.template.body.append(web.page.render())
    return footer()
def success_donation():
    # confirm the payment
    
    bill_id = request.args.get('resource_id')
    try:
        import gocardless
        gocardless.environment = gocardless_environment
        gocardless.set_details(**gocardless_credentials)
        gocardless.client.confirm_resource(request.args)
        web.page.create('Thanks for your donation')
        web.paragraph.create(
            """Thanks your payment has been recieved.""")
    except:
        # TODO log what actually has gone wrong
        web.page.create('Something went wrong')
        web.paragraph.create(
            """We could not confirm the payment something may have gone terribly wrong.""")

    if bill_id:
        bill = gocardless.client.bill(bill_id)
        pledge = donate.get_pledge({'name': bill.name}).get()
        
        #~ print dir(bill)

        print bill.amount
        print bill.amount_minus_fees
        print bill.charge_customer_at
        print bill.created_at
        print bill.name
        print bill.payout
        print bill.status
        print bill.user
        environment = int(gocardless_environment=='production')
        donate.add_payment().execute({'pledge_id':pledge.get('name','') , 'reference': bill_id, 'amount': bill.amount_minus_fees, 'environment': environment})


    web.template.create('Maidstone Hackspace')
    header('Maidstone Hackspace Donations')
    web.page.create('Thanks for your donation')
    web.paragraph.create(
        """Thanks your payment has been recieved.""")
    web.page.section(web.paragraph.render())
    web.template.body.append(web.page.render())
    return footer()
 def test_set_details_creates_client(self):
     gocardless.set_details(mock_account_details)
     self.assertIsNotNone(gocardless.client)
Exemple #16
0
from django.shortcuts import render, redirect
import gocardless

gocardless.environment = "sandbox"

gocardless.set_details(app_id="kzCOPw2JtJvRQxKTlFqQTGvxLvkoMS1Eb0Dgl5QVc1W0NKpOEZDvESfGOI_kkG2l",
    app_secret="IO9AlgPsbYNCtFlciV_HOBrGB3Mi07PFYSn2zx4uK5xaWJI1AzwnYeC86x46ji_g",
    token="5EFkzOrUOZ8t+iaP86NggIy+iKGJ0f7QMnMd+Q3P4mQk17Kzq9G1vYrNlEWFldlg",
    merchant_id="02FX1YS3H1"})

def index(request):
    subscriptions = gocardless.client.merchant().subscriptions()
    return render(request, "index.html", {"subscriptions":subscriptions})

def create_bill(request):
    url = gocardless.client.new_bill_url(2.99, 
        name="Domain Registration")
    return redirect(url)

def create_subscription(request):
    url = gocardless.client.new_subscription_url(99, 1, "month", 
            name="Dedicated Server Subscription",
            description="Dedicated server with quad core and 8GB of RAM")
    print(url)
    return redirect(url)

def create_preauth(request):
    max_amount = int(request.POST["budget"])
    url = gocardless.client.new_preauthorization_url(max_amount, 1, "month",
            name="Variable Priced Hosting",
            description="With our cloud-based hosting means you'll only be" 
    'oscar.apps.customer.auth_backends.Emailbackend',
    'django.contrib.auth.backends.ModelBackend',
)

LOGIN_REDIRECT_URL = '/accounts/'
APPEND_SLASH = True

DEBUG_TOOLBAR_CONFIG = {
    'INTERCEPT_REDIRECTS': False
}

# Oscar settings
from oscar.defaults import *
OSCAR_ALLOW_ANON_CHECKOUT = True

OSCAR_SHOP_TAGLINE = 'GoCardless sandbox'

# Haystack settings
HAYSTACK_SITECONF = 'oscar.search_sites'
HAYSTACK_SEARCH_ENGINE = 'dummy'

import gocardless
details = {
    "app_id":"ttTbIHRLigLKxFzWIHglLQBEIvgPI8sUa8E1Ign1jcssCBp__bxpTP1pA95fQcOe",
    "app_secret":"OU_esxeN_TQbh2XDoaD9eGmQemj_sS3ArgNax7w8yns_h8y90O2bEc9BO_CHC3gy",
    "token":"yRqZgJZgaiav5EQ/IzntZCuJqu+agdL1QPQyL86JGWXgfWcnCzDaGvvzZYUb+KJO",
    "merchant_id":"02VZEMGAKZ"
}
gocardless.set_details(details)
gocardless.environment = 'sandbox'
Exemple #18
0
assets = Environment(app)
css_all = Bundle('css/main.css', output='gen/packed.css', filters='cssmin')
css_admin = Bundle('css/admin.css',
                   output='gen/admin-packed.css',
                   filters='cssmin')
css_print = Bundle('css/print.css',
                   output='gen/print-packed.css',
                   filters='cssmin')
assets.register('css_all', css_all)
assets.register('css_admin', css_admin)
assets.register('css_print', css_print)

gocardless.environment = app.config['GOCARDLESS_ENVIRONMENT']
gocardless.set_details(app_id=app.config['GOCARDLESS_APP_ID'],
                       app_secret=app.config['GOCARDLESS_APP_SECRET'],
                       access_token=app.config['GOCARDLESS_ACCESS_TOKEN'],
                       merchant_id=app.config['GOCARDLESS_MERCHANT_ID'])

stripe.api_key = app.config['STRIPE_SECRET_KEY']


def external_url(endpoint, **values):
    """ Generate an absolute external URL. If you need to override this,
        you're probably doing something wrong. """
    return url_for(endpoint, _external=True, **values)


from views import *
from models import *

if __name__ == "__main__":
Exemple #19
0
from django.conf import settings
from django.views.generic import RedirectView, TemplateView, View
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponse
from django.utils import simplejson

import gocardless

__all__ = ('Purchase', 'Subscribe', 'Preauth', 'Confirm', 'Success', 'Error',
           'Webhook')

gocardless.set_details(app_id=settings.GC_APP_ID,
                       app_secret=settings.GC_APP_SECRET,
                       access_token=settings.GC_ACCESS_TOKEN,
                       merchant_id=settings.GC_MERCHANT_ID)
gocardless.environment = settings.GC_ENVIRONMENT

User = get_user_model()


# Generate a URL for a one-off payment and redirect to it
class Purchase(RedirectView):
    def get_redirect_url(self, **kwargs):
        url = gocardless.client.new_bill_url(
            10, name=self.request.POST.get('name'))
        return url


# Generate a URL for a subscription and redirect to it
Exemple #20
0
from django.views.generic import RedirectView, TemplateView, View
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponse
from django.utils import simplejson

import gocardless

__all__ = ('Purchase', 'Subscribe', 'Preauth',
           'Confirm', 'Success', 'Error', 'Webhook')

gocardless.set_details(
    app_id='',
    app_secret='',
    access_token='',
    merchant_id=''
)
gocardless.environment = 'sandbox'


# Generate a URL for a one-off payment and redirect to it
class Purchase(RedirectView):
    def get_redirect_url(self, **kwargs):
        url = gocardless.client.new_bill_url(
            10,
            name=self.request.POST.get('name')
        )
        return url

Exemple #21
0
from django.views.generic import RedirectView, TemplateView, View
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponse
from django.utils import simplejson

import gocardless

__all__ = ('Purchase', 'Subscribe', 'Preauth',
           'Confirm', 'Success', 'Error', 'Webhook')

gocardless.set_details(
    app_id=settings.GC_APP_ID,
    app_secret=settings.GC_APP_SECRET,
    access_token=settings.GC_ACCESS_TOKEN,
    merchant_id=settings.GC_MERCHANT_ID
)
gocardless.environment = settings.GC_ENVIRONMENT

User = get_user_model()


# Generate a URL for a one-off payment and redirect to it
class Purchase(RedirectView):
    def get_redirect_url(self, **kwargs):
        url = gocardless.client.new_bill_url(
            10,
            name=self.request.POST.get('name')
        )
        return url
 def test_set_details_creates_client(self):
     gocardless.set_details(app_id=mock_account_details["app_id"],
             app_secret=mock_account_details["app_secret"],
             access_token=mock_account_details["token"],
             merchant_id=mock_account_details["merchant_id"])
     self.assertIsNotNone(gocardless.client)
Exemple #23
0
def create_app(dev_server=False):
    app = Flask(__name__)
    app.config.from_envvar('SETTINGS_FILE')
    app.jinja_options['extensions'].append('jinja2.ext.do')

    if install_logging:
        logger.setup_logging(app)

    for extension in (cdn, csrf, cache, db, mail, assets, toolbar):
        extension.init_app(app)

    migrate.init_app(app, db, render_as_batch=True)

    login_manager.setup_app(app, add_context_processor=True)
    app.login_manager.login_view = 'users.login'

    from models.user import User
    from models import site_state, feature_flag

    @login_manager.user_loader
    def load_user(userid):
        user = User.query.filter_by(id=userid).first()
        if user:
            _request_ctx_stack.top.user_email = user.email
        return user

    if app.config.get('TICKETS_SITE'):
        gocardless.environment = app.config['GOCARDLESS_ENVIRONMENT']
        gocardless.set_details(
            app_id=app.config['GOCARDLESS_APP_ID'],
            app_secret=app.config['GOCARDLESS_APP_SECRET'],
            access_token=app.config['GOCARDLESS_ACCESS_TOKEN'],
            merchant_id=app.config['GOCARDLESS_MERCHANT_ID'])

        stripe.api_key = app.config['STRIPE_SECRET_KEY']

        @app.before_request
        def load_per_request_state():
            site_state.get_states()
            feature_flag.get_db_flags()

    if app.config.get('DEBUG'):
        # Prevent staging site from being displayed on Google
        @app.after_request
        def send_noindex_header(response):
            response.headers['X-Robots-Tag'] = 'noindex, nofollow'
            return response

        # Prevent DB connections and random numbers being shared
        ppid = os.getpid()

        @app.before_request
        def fix_shared_state():
            if os.getpid() != ppid:
                db.engine.dispose()
                random.seed()

    @app.before_request
    def simple_cache_warning():
        if not dev_server and app.config.get('CACHE_TYPE', 'null') == 'simple':
            logging.warn(
                'Per-process cache being used outside dev server - refreshing will not work'
            )

    @app.after_request
    def send_security_headers(response):
        use_hsts = app.config.get('HSTS', False)
        if use_hsts:
            max_age = app.config.get('HSTS_MAX_AGE', 3600 * 24 * 7 * 4)
            response.headers[
                'Strict-Transport-Security'] = 'max-age=%s' % max_age

        response.headers['X-Frame-Options'] = 'deny'
        response.headers['X-Content-Type-Options'] = 'nosniff'

        return response

    @app.errorhandler(404)
    def handle_404(e):
        return render_template('errors/404.html'), 404

    @app.errorhandler(500)
    def handle_500(e):
        return render_template('errors/500.html'), 500

    from apps.common import load_utility_functions
    load_utility_functions(app)

    from apps.base import base
    from apps.users import users
    from apps.tickets import tickets
    from apps.payments import payments
    from apps.cfp import cfp
    from apps.cfp_review import cfp_review
    from apps.schedule import schedule
    from apps.arrivals import arrivals
    from apps.admin import admin
    app.register_blueprint(base)
    app.register_blueprint(users)
    app.register_blueprint(tickets)
    app.register_blueprint(payments)
    app.register_blueprint(cfp)
    app.register_blueprint(cfp_review, url_prefix='/cfp-review')
    app.register_blueprint(schedule)
    app.register_blueprint(arrivals, url_prefix='/arrivals')
    app.register_blueprint(admin, url_prefix='/admin')

    return app
 def test_set_details_creates_client(self):
     gocardless.set_details(app_id=mock_account_details["app_id"],
             app_secret=mock_account_details["app_secret"],
             access_token=mock_account_details["token"],
             merchant_id=mock_account_details["merchant_id"])
     self.assertIsNotNone(gocardless.client)
Exemple #25
0
def create_app(dev_server=False):
    app = Flask(__name__)
    app.config.from_envvar('SETTINGS_FILE')
    app.jinja_options['extensions'].append('jinja2.ext.do')

    if install_logging:
        logger.setup_logging(app)

    for extension in (cdn, csrf, cache, db, mail, assets, toolbar):
        extension.init_app(app)

    migrate.init_app(app, db, render_as_batch=True)

    login_manager.setup_app(app, add_context_processor=True)
    app.login_manager.login_view = 'users.login'

    from models.user import User
    from models import site_state, feature_flag

    @login_manager.user_loader
    def load_user(userid):
        user = User.query.filter_by(id=userid).first()
        if user:
            _request_ctx_stack.top.user_email = user.email
        return user

    if app.config.get('TICKETS_SITE'):
        gocardless.environment = app.config['GOCARDLESS_ENVIRONMENT']
        gocardless.set_details(app_id=app.config['GOCARDLESS_APP_ID'],
                               app_secret=app.config['GOCARDLESS_APP_SECRET'],
                               access_token=app.config['GOCARDLESS_ACCESS_TOKEN'],
                               merchant_id=app.config['GOCARDLESS_MERCHANT_ID'])

        stripe.api_key = app.config['STRIPE_SECRET_KEY']

        @app.before_request
        def load_per_request_state():
            site_state.get_states()
            feature_flag.get_db_flags()

    if app.config.get('DEBUG'):
        # Prevent staging site from being displayed on Google
        @app.after_request
        def send_noindex_header(response):
            response.headers['X-Robots-Tag'] = 'noindex, nofollow'
            return response

        # Prevent DB connections and random numbers being shared
        ppid = os.getpid()
        @app.before_request
        def fix_shared_state():
            if os.getpid() != ppid:
                db.engine.dispose()
                random.seed()

    @app.before_request
    def simple_cache_warning():
        if not dev_server and app.config.get('CACHE_TYPE', 'null') == 'simple':
            logging.warn('Per-process cache being used outside dev server - refreshing will not work')

    @app.after_request
    def send_security_headers(response):
        use_hsts = app.config.get('HSTS', False)
        if use_hsts:
            max_age = app.config.get('HSTS_MAX_AGE', 3600 * 24 * 7 * 4)
            response.headers['Strict-Transport-Security'] = 'max-age=%s' % max_age

        response.headers['X-Frame-Options'] = 'deny'
        response.headers['X-Content-Type-Options'] = 'nosniff'

        return response

    @app.errorhandler(404)
    def handle_404(e):
        return render_template('errors/404.html'), 404

    @app.errorhandler(500)
    def handle_500(e):
        return render_template('errors/500.html'), 500

    from apps.common import load_utility_functions
    load_utility_functions(app)

    from apps.base import base
    from apps.users import users
    from apps.tickets import tickets
    from apps.payments import payments
    from apps.cfp import cfp
    from apps.cfp_review import cfp_review
    from apps.schedule import schedule
    from apps.arrivals import arrivals
    from apps.admin import admin
    app.register_blueprint(base)
    app.register_blueprint(users)
    app.register_blueprint(tickets)
    app.register_blueprint(payments)
    app.register_blueprint(cfp)
    app.register_blueprint(cfp_review, url_prefix='/cfp-review')
    app.register_blueprint(schedule)
    app.register_blueprint(arrivals, url_prefix='/arrivals')
    app.register_blueprint(admin, url_prefix='/admin')

    return app
Exemple #26
0
login_manager = LoginManager()

assets = Environment(app)
css_all = Bundle('css/main.css',
                  output='gen/packed.css', filters='cssmin')
css_admin = Bundle('css/admin.css',
                   output='gen/admin-packed.css', filters='cssmin')
css_print = Bundle('css/print.css',
                   output='gen/print-packed.css', filters='cssmin')
assets.register('css_all', css_all)
assets.register('css_admin', css_admin)
assets.register('css_print', css_print)

gocardless.environment = app.config['GOCARDLESS_ENVIRONMENT']
gocardless.set_details(app_id=app.config['GOCARDLESS_APP_ID'],
                        app_secret=app.config['GOCARDLESS_APP_SECRET'],
                        access_token=app.config['GOCARDLESS_ACCESS_TOKEN'],
                        merchant_id=app.config['GOCARDLESS_MERCHANT_ID'])

stripe.api_key = app.config['STRIPE_SECRET_KEY']


def external_url(endpoint, **values):
    """ Generate an absolute external URL. If you need to override this,
        you're probably doing something wrong. """
    return url_for(endpoint, _external=True, **values)

from views import *
from models import *

if __name__ == "__main__":
    if app.config.get('DEBUG'):
from django.views.generic import RedirectView, TemplateView, View
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponse
from django.utils import simplejson

import gocardless

__all__ = ('Purchase', 'Subscribe', 'Preauth', 'Confirm', 'Success', 'Error',
           'Webhook')

gocardless.set_details(app_id='',
                       app_secret='',
                       access_token='',
                       merchant_id='')
gocardless.environment = 'sandbox'


# Generate a URL for a one-off payment and redirect to it
class Purchase(RedirectView):
    def get_redirect_url(self, **kwargs):
        url = gocardless.client.new_bill_url(
            10, name=self.request.POST.get('name'))
        return url


# Generate a URL for a subscription and redirect to it
class Subscribe(RedirectView):
    def get_redirect_url(self, **kwargs):
        url = gocardless.client.new_subscription_url(