Ejemplo n.º 1
0
def change(request):
    client = get_client().Subscription
    form = SubscriptionUpdateForm(request.DATA)

    if not form.is_valid():
        raise FormError(form.errors)

    subscription = form.cleaned_data['subscription']
    method = form.cleaned_data['paymethod']
    result = client.update(
        subscription.provider_id,
        {'payment_method_token': method.provider_id}
    )

    log_msgs = (subscription.id, subscription.paymethod_id, method.pk)

    if not result.is_success:
        log.warning('Error on changing subscription: {} from {} to {}'
                    .format(*log_msgs))
        raise BraintreeResultError(result)

    subscription.paymethod = method
    subscription.save()

    log.info('Subscription changed: {} from {} to {}'.format(*log_msgs))
    res = Namespaced(
        mozilla=LocalSubscription(instance=subscription),
        braintree=Subscription(instance=result.subscription)
    )
    return Response(res.data, status=200)
Ejemplo n.º 2
0
def create(request):
    client = get_client().Customer
    form = BuyerForm(request.DATA)

    if not form.is_valid():
        raise FormError(form.errors)

    result = client.create()
    if not result.is_success:
        log.warning('Error on creating Customer: {0}, {1}'
                    .format(form.cleaned_data['uuid'], result.message))
        raise BraintreeResultError(result)

    log.info('Braintree customer created: {0}'.format(result.customer.id))

    braintree_buyer = BraintreeBuyer.objects.create(
        buyer=form.buyer, braintree_id=result.customer.id)

    log.info('Braintree buyer created: {0}'.format(braintree_buyer.pk))

    res = serializers.Namespaced(
        mozilla=serializers.LocalBuyer(instance=braintree_buyer),
        braintree=serializers.Customer(instance=result.customer)
    )
    return Response(res.data, status=201)
Ejemplo n.º 3
0
def create(request):
    client = get_client().Customer
    form = BuyerForm(request.DATA)

    if not form.is_valid():
        raise FormError(form.errors)

    result = client.create()
    if not result.is_success:
        log.warning('Error on creating Customer: {0}, {1}'
                    .format(form.cleaned_data['uuid'], result.message))
        raise BraintreeResultError(result)

    log.info('Braintree customer created: {0}'.format(result.customer.id))

    braintree_buyer = BraintreeBuyer.objects.create(
        buyer=form.buyer, braintree_id=result.customer.id)

    log.info('Braintree buyer created: {0}'.format(braintree_buyer.pk))

    res = serializers.Namespaced(
        serializers.LocalBuyer(instance=braintree_buyer),
        serializers.Customer(instance=result.customer)
    )
    return Response(res.data, status=201)
Ejemplo n.º 4
0
def create(request):
    client = get_client().PaymentMethod
    form = PaymentMethodForm(request.DATA)

    if not form.is_valid():
        raise FormError(form.errors)

    buyer = form.buyer
    braintree_buyer = form.braintree_buyer
    result = client.create(form.braintree_data)

    if not result.is_success:
        log.warning('Error on creating Payment method: {0}, {1}'.format(
            buyer.uuid, result.message))
        raise BraintreeResultError(result)

    braintree_method = result.payment_method
    log.info('PaymentMethod created for: {0}'.format(buyer.uuid))

    solitude_method = BraintreePaymentMethod.objects.create(
        braintree_buyer=braintree_buyer,
        type=PAYMENT_METHOD_CARD,
        type_name=braintree_method.card_type,
        provider_id=braintree_method.token,
        truncated_id=result.payment_method.last_4)
    log.info('Method {0} created.'.format(solitude_method.pk))

    res = serializers.Namespaced(
        mozilla=serializers.LocalPayMethod(instance=solitude_method),
        braintree=serializers.PayMethod(instance=braintree_method))
    return Response(res.data, status=201)
Ejemplo n.º 5
0
def change(request):
    client = get_client().Subscription
    form = SubscriptionUpdateForm(request.DATA)

    if not form.is_valid():
        raise FormError(form.errors)

    subscription = form.cleaned_data['subscription']
    method = form.cleaned_data['paymethod']
    result = client.update(subscription.provider_id,
                           {'payment_method_token': method.provider_id})

    log_msgs = (subscription.id, subscription.paymethod_id, method.pk)

    if not result.is_success:
        log.warning('Error on changing subscription: {} from {} to {}'.format(
            *log_msgs))
        raise BraintreeResultError(result)

    subscription.paymethod = method
    subscription.save()

    log.info('Subscription changed: {} from {} to {}'.format(*log_msgs))
    res = Namespaced(mozilla=LocalSubscription(instance=subscription),
                     braintree=Subscription(instance=result.subscription))
    return Response(res.data, status=200)
Ejemplo n.º 6
0
def create(request):
    client = get_client().Subscription
    form = SubscriptionForm(request.DATA)

    if not form.is_valid():
        raise FormError(form.errors)

    data = form.braintree_data
    result = client.create(data)

    if not result.is_success:
        log.warning('Error on creating subscription: {0}'.format(
            result.message))
        raise BraintreeResultError(result)

    braintree_subscription = result.subscription
    log.info('Subscription created in braintree {} for paymethod {}'.format(
        braintree_subscription.id, form.cleaned_data['paymethod']))

    subscription = BraintreeSubscription.objects.create(
        amount=form.cleaned_data['amount'],
        paymethod=form.cleaned_data['paymethod'],
        seller_product=form.seller_product,
        provider_id=braintree_subscription.id)
    log.info('Subscription created in solitude: {}; braintree: {}'.format(
        subscription.pk, braintree_subscription.id))

    res = Namespaced(mozilla=LocalSubscription(instance=subscription),
                     braintree=Subscription(instance=braintree_subscription))
    return Response(res.data, status=201)
Ejemplo n.º 7
0
def create(request):
    client = get_client().PaymentMethod
    form = PaymentMethodForm(request.DATA)

    if not form.is_valid():
        raise FormError(form.errors)

    buyer = form.buyer
    braintree_buyer = form.braintree_buyer
    result = client.create(form.braintree_data)

    if not result.is_success:
        log.warning('Error on creating Payment method: {0}, {1}'
                    .format(buyer.uuid, result.message))
        raise BraintreeResultError(result)

    braintree_method = result.payment_method
    log.info('PaymentMethod created for: {0}'.format(buyer.uuid))

    solitude_method = BraintreePaymentMethod.objects.create(
        braintree_buyer=braintree_buyer,
        type=PAYMENT_METHOD_CARD,
        type_name=braintree_method.card_type,
        provider_id=braintree_method.token,
        truncated_id=result.payment_method.last_4
    )
    log.info('Method {0} created.'.format(solitude_method.pk))

    res = serializers.Namespaced(
        mozilla=serializers.LocalPayMethod(instance=solitude_method),
        braintree=serializers.PayMethod(instance=braintree_method)
    )
    return Response(res.data, status=201)
Ejemplo n.º 8
0
def create(request):
    client = get_client().Subscription
    form = SubscriptionForm(request.DATA)

    if not form.is_valid():
        raise FormError(form.errors)

    data = form.braintree_data
    result = client.create(data)

    if not result.is_success:
        log.warning('Error on creating subscription: {0}'
                    .format(result.message))
        raise BraintreeResultError(result)

    braintree_subscription = result.subscription
    log.info('Subscription created in braintree: {0}'
             .format(braintree_subscription.id))

    subscription = BraintreeSubscription.objects.create(
        paymethod=form.cleaned_data['paymethod'],
        seller_product=form.seller_product,
        provider_id=braintree_subscription.id
    )
    log.info('Subscription created in solitude: {0}'.format(subscription.pk))

    res = Namespaced(
        LocalSubscription(instance=subscription),
        Subscription(instance=braintree_subscription)
    )
    return Response(res.data, status=201)
Ejemplo n.º 9
0
 def get_plans(self):
     # Note price is a string not a decimal or something useful:
     # https://github.com/braintree/braintree_python/issues/52
     self.mocks['plans'].all.return_value = [
         Plan(None, {'id': 'mozilla-concrete-mortar', 'price': '1'}),
         Plan(None, {'id': 'mozilla-concrete-brick', 'price': '10'})
     ]
     return config.get_plans(get_client())
Ejemplo n.º 10
0
    def braintree_delete(self):
        """
        Deletes this payment method on braintree.
        """
        result = get_client().PaymentMethod.delete(self.provider_id)
        if not result.is_success:
            log.warning('Error on deleting Payment method: {} {}'
                        .format(self.pk, result.message))
            raise BraintreeResultError(result)

        log.info('Payment method deleted in braintree: {}'.format(self.pk))
        return result
Ejemplo n.º 11
0
    def braintree_delete(self):
        """
        Deletes this payment method on braintree.
        """
        result = get_client().PaymentMethod.delete(self.provider_id)
        if not result.is_success:
            log.warning('Error on deleting Payment method: {} {}'.format(
                self.pk, result.message))
            raise BraintreeResultError(result)

        log.info('Payment method deleted in braintree: {}'.format(self.pk))
        return result
Ejemplo n.º 12
0
    def braintree_cancel(self):
        """
        Cancels this subscription on braintree. See: http://bit.ly/1M84dbi
        for more.
        """
        result = get_client().Subscription.cancel(self.provider_id)
        if not result.is_success:
            log.warning('Error on cancelling subscription: {} {}'
                        .format(self.pk, result.message))
            raise BraintreeResultError(result)

        log.info('Subscription cancelled in braintree: {}'.format(self.pk))
        return result
Ejemplo n.º 13
0
    def braintree_cancel(self):
        """
        Cancels this subscription on braintree. See: http://bit.ly/1M84dbi
        for more.
        """
        result = get_client().Subscription.cancel(self.provider_id)
        if not result.is_success:
            log.warning('Error on cancelling subscription: {} {}'.format(
                self.pk, result.message))
            raise BraintreeResultError(result)

        log.info('Subscription cancelled in braintree: {}'.format(self.pk))
        return result
Ejemplo n.º 14
0
 def handle(self, *args, **options):
     client = get_client()
     for seller_name, seller_config in sellers.items():
         log.info('Configuring: {0}'.format(seller_name))
         seller = get_or_create_seller(seller_name)
         plans = get_plans(client)
         # Iterate through each product checking they exist.
         for product in seller_config.products:
             get_or_create_seller_product(
                 external_id=product.id,
                 public_id=product.id,
                 seller=seller
             )
             product_exists(plans, product.id, product.amount)
Ejemplo n.º 15
0
 def get_plans(self):
     # Note price is a string not a decimal or something useful:
     # https://github.com/braintree/braintree_python/issues/52
     self.mocks['plans'].all.return_value = [
         Plan(None, {
             'id': 'mozilla-concrete-mortar',
             'price': '1'
         }),
         Plan(None, {
             'id': 'mozilla-concrete-brick',
             'price': '10'
         })
     ]
     return config.get_plans(get_client())
Ejemplo n.º 16
0
 def handle(self, *args, **options):
     config = settings.BRAINTREE_CONFIG
     client = get_client()
     for name, item in config.items():
         log.info('Configuring: {0}'.format(name))
         seller = get_or_create_seller(item['seller'])
         plans = get_plans(client)
         # Iterate through each product checking they exist.
         for product in item['products']:
             external_id = item['seller'] + '-' + product['name']
             get_or_create_seller_product(
                 external_id=external_id,
                 public_id=product['name'],
                 seller=seller
             )
             product_exists(plans, external_id, product['amount'])
Ejemplo n.º 17
0
def parse(request):
    form = WebhookParseForm(request.DATA)
    if not form.is_valid():
        raise FormError(form.errors)

    # Parse the gateway without doing a validation on this server.
    # The validation has happened on the solitude-auth server.
    gateway = get_client().Configuration.instantiate().gateway()
    payload = base64.decodestring(form.cleaned_data['bt_payload'])
    attributes = XmlUtil.dict_from_xml(payload)
    parsed = WebhookNotification(gateway, attributes['notification'])

    log.info('Received webhook: {p.kind}.'.format(p=parsed))
    debug_log.debug(parsed)
    Processor(parsed).process()
    return Response(status=204)
Ejemplo n.º 18
0
 def handle(self, *args, **options):
     client = get_client()
     for seller_name, seller_config in sellers.items():
         log.info('Configuring: {0}'.format(seller_name))
         seller = get_or_create_seller(seller_name)
         plans = get_plans(client)
         # Iterate through each product checking they exist.
         for product in seller_config.products:
             # Check that the product exists in Braintree.
             get_or_create_seller_product(
                 external_id=product.id,
                 public_id=product.id,
                 seller=seller
             )
             if product.recurrence:
                 # If there's recurrence, we need to check
                 # that it exists in Braintree and is set up ok.
                 product_exists(plans, product.id, product.amount)
Ejemplo n.º 19
0
def create(request):
    client = get_client().Transaction
    form = SaleForm(request.DATA)

    if not form.is_valid():
        raise FormError(form.errors)

    result = client.sale(form.braintree_data)
    if not result.is_success:
        log.warning('Error on one-off sale: {}'.format(form.braintree_data))
        raise BraintreeResultError(result)

    our_transaction = Transaction.objects.create(
        amount=result.transaction.amount,
        buyer=form.buyer,
        currency=result.transaction.currency_iso_code,
        provider=constants.PROVIDER_BRAINTREE,
        seller=form.seller_product.seller,
        seller_product=form.seller_product,
        status=constants.STATUS_CHECKED,
        type=constants.TYPE_PAYMENT,
        uid_support=result.transaction.id
    )
    our_transaction.uuid = our_transaction.create_short_uid()
    our_transaction.save()
    log.info('Transaction created: {}'.format(our_transaction.pk))

    braintree_transaction = BraintreeTransaction.objects.create(
        kind='submit_for_settlement',
        paymethod=form.cleaned_data['paymethod'],
        transaction=our_transaction,

    )
    log.info('BraintreeTransaction created: {}'
             .format(braintree_transaction.pk))

    res = Namespaced(
        braintree={},  # Not sure if there's anything useful to add here.
        mozilla={
            'braintree': LocalTransaction(braintree_transaction),
            'generic': TransactionSerializer(our_transaction)
        }
    )
    return Response(res.data, status=200)
Ejemplo n.º 20
0
    def handle(self, *args, **options):
        client = get_client()
        for seller_name, seller_config in sellers.items():
            log.info('Configuring: {0}'.format(seller_name))
            seller = get_or_create_seller(seller_name)
            plans = get_plans(client)
            # Iterate through each product checking they exist.
            for product in seller_config.products:
                # Check that the product exists in Braintree.
                get_or_create_seller_product(
                    external_id=product.id,
                    public_id=product.id,
                    seller=seller
                )
                if product.recurrence:
                    # If there's recurrence, we need to check
                    # that it exists in Braintree and is set up ok.
                    try:
                        product_exists(plans, product.id, product.amount)
                    except BraintreePlanDoesNotExist:
                        raise CommandError(textwrap.dedent('''\
                            Missing product: {product.id}

                            Currently it's not possible to automate this.

                            1. Log into https://sandbox.braintreegateway.com/
                               (or the production dashboard)
                            2. Go to Recurring Billing > Plans from the sidebar
                            3. Enter the following data:

                                Plan ID: {product.id}
                                Plan Name: {product.description}
                                Price: {price}
                                Billing Cycle Every: 1 month

                            4. re-run this script
                            5. MFBT
                        '''.format(
                            # TODO: show the right thing for recurrence
                            # other than 'month'
                            product=product,
                            price=(product.amount or '0.00'),
                        )))
Ejemplo n.º 21
0
    def handle(self, *args, **options):
        client = get_client()
        for seller_name, seller_config in sellers.items():
            log.info('Configuring: {0}'.format(seller_name))
            seller = get_or_create_seller(seller_name)
            plans = get_plans(client)
            # Iterate through each product checking they exist.
            for product in seller_config.products:
                # Check that the product exists in Braintree.
                get_or_create_seller_product(
                    external_id=product.id,
                    public_id=product.id,
                    seller=seller
                )
                if product.recurrence:
                    # If there's recurrence, we need to check
                    # that it exists in Braintree and is set up ok.
                    try:
                        product_exists(plans, product.id, product.amount)
                    except BraintreePlanDoesNotExist:
                        raise CommandError(textwrap.dedent('''\
                            Missing product: {product.id}

                            Currently it's not possible to automate this.

                            1. Log into https://sandbox.braintreegateway.com/
                               (or the production dashboard)
                            2. Go to Recurring Billing > Plans from the sidebar
                            3. Enter the following data:

                                Plan ID: {product.id}
                                Plan Name: {product.description}
                                Price: {price}
                                Billing Cycle Every: 1 month

                            4. re-run this script
                            5. MFBT
                        '''.format(
                            # TODO: show the right thing for recurrence
                            # other than 'month'
                            product=product,
                            price=(product.amount or '0.00'),
                        )))
Ejemplo n.º 22
0
def parse(request):
    form = WebhookParseForm(request.DATA)
    if not form.is_valid():
        raise FormError(form.errors)

    # Parse the gateway without doing a validation on this server.
    # The validation has happened on the solitude-auth server.
    gateway = get_client().Configuration.instantiate().gateway()
    payload = base64.decodestring(form.cleaned_data['bt_payload'])
    attributes = XmlUtil.dict_from_xml(payload)
    parsed = WebhookNotification(gateway, attributes['notification'])

    log.info('Received webhook: {p.kind}.'.format(p=parsed))
    debug_log.debug(parsed)

    processor = Processor(parsed)
    processor.process()
    data = processor.data
    return Response(data, status=200 if data else 204)
Ejemplo n.º 23
0
def create(request):
    client = get_client().Transaction
    form = SaleForm(request.DATA)

    if not form.is_valid():
        raise FormError(form.errors)

    result = client.sale(form.braintree_data)
    if not result.is_success:
        log.warning('Error on one-off sale: {}'.format(form.braintree_data))
        raise BraintreeResultError(result)

    our_transaction = Transaction.objects.create(
        amount=result.transaction.amount,
        buyer=form.buyer,
        currency=result.transaction.currency_iso_code,
        provider=constants.PROVIDER_BRAINTREE,
        seller=form.seller_product.seller,
        seller_product=form.seller_product,
        status=constants.STATUS_CHECKED,
        type=constants.TYPE_PAYMENT,
        uid_support=result.transaction.id)
    our_transaction.uuid = our_transaction.create_short_uid()
    our_transaction.save()
    log.info('Transaction created: {}'.format(our_transaction.pk))

    braintree_transaction = BraintreeTransaction.objects.create(
        kind='submit_for_settlement',
        paymethod=form.cleaned_data['paymethod'],
        transaction=our_transaction,
    )
    log.info('BraintreeTransaction created: {}'.format(
        braintree_transaction.pk))

    res = Namespaced(
        braintree={},  # Not sure if there's anything useful to add here.
        mozilla={
            'braintree': LocalTransaction(braintree_transaction),
            'generic': TransactionSerializer(our_transaction)
        })
    return Response(res.data, status=200)
Ejemplo n.º 24
0
 def get_plans(self, plan=None):
     # Note price is a string not a decimal or something useful:
     # https://github.com/braintree/braintree_python/issues/52
     plans = [
         Plan(None, {
             'billing_day_of_month': None,
             'id': 'mozilla-concrete-mortar',
             'price': '1',
             'trial_period': None
         }),
         Plan(None, {
             'billing_day_of_month': None,
             'id': 'mozilla-concrete-brick',
             'price': '10',
             'trial_period': None
         })
     ]
     if plan:
         plans.append(plan)
     self.mocks['plans'].all.return_value = plans
     return config.get_plans(get_client())
Ejemplo n.º 25
0
def generate(request):
    return Response({'token': get_client().ClientToken.generate()})
Ejemplo n.º 26
0
 def test_normal(self):
     with self.settings(BRAINTREE_PRIVATE_KEY='test-key'):
         assert isinstance(
             get_client().Configuration.instantiate()._http_strategy,
             Http)
Ejemplo n.º 27
0
 def test_missing_proxy(self):
     with self.settings(BRAINTREE_PROXY='', BRAINTREE_MERCHANT_ID='x'):
         with self.assertRaises(ImproperlyConfigured):
             get_client()