Пример #1
0
def test_order_payment_POST(base_items, user_client, user_user):
    gateway = braintree.BraintreeGateway(settings.BRAINTREE_CONF)
    user = user_user
    client = user_client
    order = OrderFactory(user=user)
    url3 = reverse("payments:order_payment", kwargs={"order_id": order.id})
    # FAILED
    response = client.post(url3)
    assert response.status_code == 302

    order = Order.objects.get(id=order.id)
    session = client.session
    assert order.status == "unpaid"
    with pytest.raises(KeyError):
        assert session[settings.CART_SESSION_ID]

    ## CELERY TASK
    # result = order_confirmation.delay(order.id, order.status, '/')
    # print(result)
    # ACCEPTED
    result = gateway.transaction.sale(
        {
            "amount": "10.00",
            "payment_method_nonce": "fake-valid-nonce",
            "options": {"submit_for_settlement": True},
        }
    )
    assert result.is_success
Пример #2
0
def payment_process(request: WSGIRequest, id: int) -> HttpResponse:
    gateway = braintree.BraintreeGateway(settings.BRAINTREE_CONF)
    order_info = OrderInformation.objects.get(id=id)
    order_items = OrderItem.objects.filter(order_information=order_info).all()
    total_cost = sum(order_item.get_total_cost for order_item in order_items)
    if request.method == "POST":
        nonce = request.POST.get('payment_method_nonce', None)
        result = gateway.transaction.sale({
            'amount': f"{total_cost:.2f}",
            'payment_method_nonce': nonce,
            'options': {
                'submit_for_settlement': True
            }
        })
        if result.is_success:
            order_info.paid = True
            order_info.braintree_id = result.transaction.id
            order_info.save()
            return redirect('payment_done')
        return redirect('payment_canceled')
    else:
        client_token = gateway.client_token.generate()
        return render(request,
                      'payment/process.html', {
                          'order': order_info,
                          'item': order_items,
                          'client_token': client_token
                      },
                      status=HTTPStatus.OK)
Пример #3
0
def init_braintree_gateway(app):
    """Configure the Braintree API gateway.

    :param app: The current app.
    :return: Braintree gateway.
    """

    with app.app_context():

        # The default environment is set to the Sandbox.
        merchant_id = app.config['MERCHANT_ID']
        public_key = app.config['MERCHANT_PUBLIC_KEY']
        private_key = app.config['MERCHANT_PRIVATE_KEY']
        braintree_environment = app.config['BRAINTREE_ENVIRONMENT']

        if braintree_environment == 'production':
            braintree_environment = braintree.Environment.Production
        else:
            braintree_environment = braintree.Environment.Sandbox

        gateway = braintree.BraintreeGateway(
            braintree.Configuration(braintree_environment,
                                    merchant_id=merchant_id,
                                    public_key=public_key,
                                    private_key=private_key))

        return gateway
Пример #4
0
def payments(request):
    gateway = braintree.BraintreeGateway(
            braintree.Configuration(
            environment=braintree.Environment.Sandbox,
            merchant_id='t2w5dbzprv32crd7',
            public_key='q2np62tjvdmmn6fk',
            private_key='814c67e277a7bc12bdfa448c6ed32e6f'  )
    )
    client_token = gateway.client_token.generate()
    if request.method=='POST':
        
        #return redirect("/takethis")
        nonce=request.POST.get('payment_method_nonce',None)
        payment_amt=request.POST.get('payment_amt',"ERROR")
        try:
            if(float(payment_amt)<0 or float(payment_amt)>100000):
                return JsonResponse({"LOL":"NO"})
        except:
            return JsonResponse({"LOL":"NO"})

        print(payment_amt)
        result = gateway.transaction.sale({
            "amount": payment_amt,
            "payment_method_nonce": nonce,
            "options": {
            "submit_for_settlement": True
            }
        })
        if result.is_success:
            return JsonResponse({"LOL":"YUH"})
        else:
            return JsonResponse({"LOL":"NO"})
    context={"token":client_token}
    template=loader.get_template('payments/index.html')
    return HttpResponse(template.render(context,request))
Пример #5
0
    def __init__(self, *args, **kwargs):

        if settings.BRAINTREE_PRODUCTION:
            braintree_env = braintree.Environment.Production
        else:
            braintree_env = braintree.Environment.Sandbox

        # Configure Braintree
        braintree_config = braintree.Configuration(
            braintree_env,
            merchant_id=settings.BRAINTREE_MERCHANT_ID,
            public_key=settings.BRAINTREE_PUBLIC_KEY,
            private_key=settings.BRAINTREE_PRIVATE_KEY,
        )
        self.gateway = braintree.BraintreeGateway(braintree_config)
        self.braintree_client_token = self.gateway.client_token.generate({})

        self.co_params = {}
        amount = kwargs.pop('amount', None)
        self.invnum = kwargs.pop('invnum', None)
        currency = kwargs.pop('currency', None)
        retval = super().__init__(*args, **kwargs)
        self.initial['installment'] = InstallmentTypes.FULL  # default
        self.initial['amount'] = amount
        return retval
Пример #6
0
def get_gateway():
    gateway = braintree.BraintreeGateway(
        braintree.Configuration(environment=braintree.Environment.Sandbox,
                                merchant_id=settings.BRAINTREE_MERCHANT_ID,
                                public_key=settings.BRAINTREE_PUBLIC_KEY,
                                private_key=settings.BRAINTREE_PRIVATE_KEY))
    return gateway
Пример #7
0
    def post(self, request, *args, **kwargs):
        gateway = braintree.BraintreeGateway(
            braintree.Configuration(
                braintree.Environment.Sandbox,
                merchant_id=os.environ.get("BRAINTREE_MERCHANT_ID"),
                public_key=os.environ.get("BRAINTREE_PUBLIC_KEY"),
                private_key=os.environ.get("BRAINTREE_PRIVATE_KEY")))

        # Parse Braintree webhook
        body = json.loads(request.body)
        webhook_notification = gateway.webhook_notification.parse(
            body["bt_signature"], body["bt_payload"])

        braintree_subscription = webhook_notification.subscription

        # Make sure we can find the subscription
        subscription = get_object_or_404(
            Subscription, braintree_subscription_id=braintree_subscription.id)

        if webhook_notification.kind == "subscription_charged_successfully":
            # Grace period so subscribers maintain access
            grace_period = timedelta(days=5)

            # Use Braintree paid through date (with grace period), if available
            if braintree_subscription.get("paid_through_date"):
                subscription.end_date = braintree_subscription.paid_through_date + grace_period
            # Otherwise extend by one year with grace period
            else:
                one_year_with_grace = timedelta(days=365) + grace_period

                subscription.end_date = subscription.end_date + one_year_with_grace

            subscription.save()

        return HttpResponse()
Пример #8
0
def get_braintree_gateway():
    return braintree.BraintreeGateway(
        braintree.Configuration(
            braintree.Environment.Sandbox,
            merchant_id=os.environ.get("BRAINTREE_MERCHANT_ID"),
            public_key=os.environ.get("BRAINTREE_PUBLIC_KEY"),
            private_key=os.environ.get("BRAINTREE_PRIVATE_KEY"),
        ))
Пример #9
0
 def __init__(self):
     mode = braintree.Environment.Production if braintree_config.CONFIG_MODE == "live" else braintree.Environment.Sandbox
     self.configuration = braintree.Configuration(
         mode,
         merchant_id=braintree_config.CONFIG_MERCHANT_ID,
         public_key=braintree_config.CONFIG_PUBLIC_KEY,
         private_key=braintree_config.CONFIG_PRIVATE_KEY)
     self.gateway = braintree.BraintreeGateway(self.configuration)
Пример #10
0
 def configure_braintree(self):
     self.gateway = braintree.BraintreeGateway(
         braintree.Configuration(
             environment=braintree.Environment.Sandbox
             if self.use_sandbox else braintree.Environment.Production,
             merchant_id=self.merchant_id,
             public_key=self.public_key,
             private_key=self.get_password(fieldname='private_key',
                                           raise_exception=False)))
Пример #11
0
def payment_process(request):
    order_id = request.session['order_id']
    order = get_object_or_404(Order, id=order_id)

    if request.method == 'POST':
        nonce = request.POST.get('payment_method_nonce', None)
        result = braintree.Transaction.sale({
            'amount':
            '{:.2f}'.format(order.get_total_cost()),
            'payment_method_nonce':
            nonce,
            "options": {
                "submit_for_settlement": True
            }
        })
        if result.is_success:
            order.paid = True
            order.braintree_id = result.transaction.id
            order.save()

            #record products to be bought together
            r = Recommender()
            products = [item.product for item in order.items.all()]
            r.products_bought(products)

            #create mail of invoice
            subject = "My shop - invoice no. {}".format(order.id)
            message = 'Please, find attateched the invoice for your recent purchases.'
            email = EmailMessage(subject, message, '*****@*****.**',
                                 [order.email])

            html = render_to_string('admin/orders/order/pdf.html',
                                    {'order': order})
            stylesheets = [
                weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')
            ]
            out = weasyprint.HTML(string=html).write_pdf(
                stylesheets=stylesheets)

            email.attach('order_{}'.format(order.id), out, 'application/pdf')
            email.send()

            return redirect('payment:done')
        else:
            return redirect('payment:canceled')

    else:
        #client_token=braintree.ClientToken.generate()

        gateway = braintree.BraintreeGateway(
            braintree.Configuration.instantiate())
        client_token = gateway.client_token.generate()

        return render(request, 'payment/process.html', {
            'order': order,
            'client_token': client_token
        })
Пример #12
0
	def __init__(self,config):
		self.gateway = braintree.BraintreeGateway(
		    braintree.Configuration(
		        environment = config['environment'],
		        merchant_id = config['merchant_id'],
		        public_key = config['public_key'],
		        private_key = config['private_key'],
		    )
		)
Пример #13
0
 def __init__(self):
     self.gateway = braintree.BraintreeGateway(
         braintree.Configuration(
             braintree.Environment.Production,
             merchant_id=os.getenv('BRAINTREE_MERCHANT_ID'),
             public_key=os.getenv('BRAINTREE_PUBLIC_KEY'),
             private_key=os.getenv('BRAINTREE_PRIVATE_KEY')))
     self.kount_url = os.getenv('KOUNT_URL')
     self.kount_api_key = os.getenv('KOUNT_API_KEY')
Пример #14
0
    def __init__(self, access_token=None):  # add user param ?
        # django user who is performing a transaction
        # self.user = user

        # override the access_token if its specified
        if access_token is not None:
            self.access_token = access_token

        # setup the gateway which will help us do braintree/vzero things
        self.gateway = braintree.BraintreeGateway(access_token=self.access_token)
Пример #15
0
def gateway(app):
    instance = braintree.BraintreeGateway(
        braintree.Configuration(
            braintree.Environment.Sandbox,
            merchant_id=app.config.get('BT_MERCHANT_ID'),
            public_key=app.config.get('BT_PUBLIC_KEY'),
            private_key=app.config.get('BT_PRIVATE_KEY')
        )
    )
    return instance
Пример #16
0
 def try_connect(self, logger: AirbyteLogger, config: json):
     """Test provided credentials, raises self.api_error if something goes wrong"""
     client = braintree.BraintreeGateway(
         braintree.Configuration(
             environment=getattr(braintree.Environment, config["environment"]),
             merchant_id=config["merchant_id"],
             public_key=config["public_key"],
             private_key=config["private_key"],
         )
     )
     client.transaction.search(braintree.TransactionSearch.created_at.between(datetime.now() + relativedelta(days=-1), datetime.now()))
Пример #17
0
def test_order_payment_GET(base_items, user_client, user_user):
    gateway = braintree.BraintreeGateway(settings.BRAINTREE_CONF)
    user = user_user
    client = user_client
    order = OrderFactory(user=user)
    url3 = reverse("payments:order_payment", kwargs={"order_id": order.id})
    response = client.get(url3)
    assert response.status_code == 200
    assert response.context["client_token"]

    response = Client().get(url3)
    assert response.status_code == 403
Пример #18
0
def get_braintree_gateway(sandbox_mode, merchant_id, public_key, private_key):
    if not all([merchant_id, private_key, public_key]):
        raise ImproperlyConfigured('Incorrectly configured Braintree gateway.')
    environment = braintree_sdk.Environment.Sandbox
    if not sandbox_mode:
        environment = braintree_sdk.Environment.Production

    config = braintree_sdk.Configuration(environment=environment,
                                         merchant_id=merchant_id,
                                         public_key=public_key,
                                         private_key=private_key)
    gateway = braintree_sdk.BraintreeGateway(config=config)
    return gateway
Пример #19
0
def payments(request):
    paypalrestsdk.configure({
        "mode": "sandbox",  # sandbox or live
        "client_id": "",
        "client_secret": ""
    })
    access_token = ''

    gateway = braintree.BraintreeGateway(access_token=access_token)
    client_token = gateway.client_token.generate()
    if request.method == 'POST':
        payment = paypalrestsdk.Payment({
            "intent":
            "sale",
            "payer": {
                "payment_method": "paypal"
            },
            "redirect_urls": {
                "return_url": "http://localhost:8000/payment/execute",
                "cancel_url": "http://localhost:8000/"
            },
            "transactions": [{
                "item_list": {
                    "items": [{
                        "name": "item",
                        "sku": "item",
                        "price": "5.00",
                        "currency": "USD",
                        "quantity": 1
                    }]
                },
                "amount": {
                    "total": "5.00",
                    "currency": "USD"
                },
                "description":
                "This is the payment transaction description."
            }]
        })

        if payment.create():
            print("Payment created successfully")
        else:
            print(payment.error)

    context = {
        'client_token': client_token,
    }

    return render(request, 'app/paypal.html')
Пример #20
0
 def __init__(self):
     #  instance variable unique to each instance
     try:
         self.payment_gateway = PaymentGateway.objects.get(
             pk=PAYMENT_GATEWAYS['BRAINTREE'])
     except ObjectDoesNotExist as error:
         logger.error(error)
         return
     self.merchant_id = self.payment_gateway.merchant_id
     self.public_key = self.payment_gateway.public_key
     self.private_key = self.payment_gateway.private_key
     self.gateway = braintree.BraintreeGateway(
         braintree.Configuration(environment=braintree.Environment.Sandbox,
                                 merchant_id=self.merchant_id,
                                 public_key=self.public_key,
                                 private_key=self.private_key))
Пример #21
0
class PaymentProcessors:
    PAYMENT_GATEWAYS = {
        'braintree': braintree.BraintreeGateway(BRAINTREE_CONFIG)
    }

    def __init__(self, name: str):
        self._get(name)

    def _get(self, name: str):
        self.processor = self.PAYMENT_GATEWAYS.get(name)

        if self.processor is None:
            raise InvalidPaymentProcessorPaymentInformation

    def create_customer(self, details: dict):
        result = self.processor.customer.create(details)

        if result.is_success is False:
            raise InvalidPaymentProcessorCustomerInformation

        return {'customer_id': result.customer.id}

    def create_payment_method(self, details: dict):
        result = self.processor.credit_card.create(details)

        if result.is_success is False:
            raise InvalidPaymentProcessorPaymentInformation

        return {'payment_token': result.credit_card.token}

    def create_payment_method_nonce(self, details):
        result = self.processor.payment_method_nonce.create(
            details['payment_token'])

        if result.is_success is False:
            raise InvalidPaymentProcessorPaymentInformation

        return {'payment_method_nonce': result.payment_method_nonce.nonce}

    def create_sale(self, details: dict):
        result = self.processor.transaction.sale(details)

        if result.is_success is False:
            raise InvalidPaymentMethod

        return result.is_success
Пример #22
0
 def __init__(self):
     test_mode = getattr(settings, "MERCHANT_TEST_MODE", True)
     if test_mode:
         env = braintree.Environment.Sandbox
     else:
         env = braintree.Environment.Production
     merchant_settings = getattr(settings, "MERCHANT_SETTINGS")
     if not merchant_settings or not merchant_settings.get("braintree_payments"):
         raise GatewayNotConfigured("The '%s' gateway is not correctly "
                                    "configured." % self.display_name)
     self.braintree_settings = merchant_settings['braintree_payments']
     self.configuration = braintree.Configuration(
         environment=env,
         merchant_id=self.braintree_settings['MERCHANT_ACCOUNT_ID'],
         public_key=self.braintree_settings['PUBLIC_KEY'],
         private_key=self.braintree_settings['PRIVATE_KEY']
     )
     self.braintree = braintree.BraintreeGateway(self.configuration)
Пример #23
0
    def __init__(self,
                 merchant_id=None,
                 public_key=None,
                 private_key=None,
                 timeout=None,
                 production=True):
        merchant_id = check_env('BRAINTREE_MERCHANT_ID', merchant_id)
        public_key = check_env('BRAINTREE_PUBLIC_KEY', public_key)
        private_key = check_env('BRAINTREE_PRIVATE_KEY', private_key)
        timeout = check_env('BRAINTREE_TIMEOUT', timeout, optional=True) or 200

        self.gateway = braintree.BraintreeGateway(
            braintree.Configuration(
                environment=(braintree.Environment.Production
                             if production else braintree.Environment.Sandbox),
                merchant_id=merchant_id,
                public_key=public_key,
                private_key=private_key,
                timeout=timeout))
Пример #24
0
 def get(self, request):
     user = request.user
     gateway = braintree.BraintreeGateway(
         braintree.Configuration(
             braintree.Environment.Sandbox,
             merchant_id=settings.BRAINTREE_MERCHANT_ID,
             public_key=settings.BRAINTREE_PUBLIC_KEY,
             private_key=settings.BRAINTREE_PRIVATE_KEY))
     # result = gateway.customer.create({
     # 	"first_name": user.first_name,
     # 	"email": user.email
     # 	}
     # )
     # if result.is_success:
     # 	user.customer_id = result.customer.id
     # user.save()
     client_token = gateway.client_token.generate(
         {"customer_id": user.customer_id})
     return Response({"client_token": client_token})
Пример #25
0
 def __init__(
     self,
     environment='sandbox',
     merchant_id=__MERCHANT_ID,
     public_key=__PUBLIC_KEY,
     private_key=__PRIVATE_KEY,
 ):
     environment = environment if valid_str(environment) else 'sandbox'
     merchant_id = merchant_id if valid_str(
         merchant_id) else self.__MERCHANT_ID
     public_key = public_key if valid_str(public_key) else self.__PUBLIC_KEY
     private_key = private_key if valid_str(
         private_key) else self.__PRIVATE_KEY
     self.gateway = braintree.BraintreeGateway(
         braintree.Configuration(
             braintree.Environment.parse_environment(environment),
             merchant_id=merchant_id,
             public_key=public_key,
             private_key=private_key))
Пример #26
0
    def __init__(self, country, environment='prod'):
        self.country = country
        self.logger = logging.getLogger('billing')
        self.merchant_id = get_settings('BRAINTREE_MERCHANT_ID',
                                        country=self.country)
        self.public_key = get_settings('BRAINTREE_PUBLIC_KEY',
                                       country=self.country)
        self.private_key = get_settings('BRAINTREE_PRIVATE_KEY',
                                        country=self.country)
        if environment == 'prod':
            env = braintree.Environment.Production
        else:
            env = braintree.Environment.Sandbox

        self.gateway = braintree.BraintreeGateway(
            braintree.Configuration(
                environment=env,
                merchant_id=self.merchant_id,
                public_key=self.public_key,
                private_key=self.private_key,
            ))
Пример #27
0
 def check(self, logger: AirbyteLogger, config_container: ConfigContainer) -> AirbyteConnectionStatus:
     try:
         json_config = config_container.rendered_config
         client = braintree.BraintreeGateway(
             braintree.Configuration(
                 environment=getattr(braintree.Environment, json_config["environment"]),
                 merchant_id=json_config["merchant_id"],
                 public_key=json_config["public_key"],
                 private_key=json_config["private_key"],
             )
         )
         client.transaction.search(
             braintree.TransactionSearch.created_at.between(datetime.now() + relativedelta(days=-1), datetime.now())
         )
         return AirbyteConnectionStatus(status=Status.SUCCEEDED)
     except AuthenticationError:
         logger.error("Exception while connecting to the Braintree API")
         return AirbyteConnectionStatus(
             status=Status.FAILED,
             message="Unable to connect to the Braintree API with the provided credentials. Please make sure the input credentials and environment are correct.",
         )
Пример #28
0
 def post(self, request):
     user = request.user
     gateway = braintree.BraintreeGateway(
         braintree.Configuration(
             braintree.Environment.Sandbox,
             merchant_id=settings.BRAINTREE_MERCHANT_ID,
             public_key=settings.BRAINTREE_PUBLIC_KEY,
             private_key=settings.BRAINTREE_PRIVATE_KEY))
     result = gateway.transaction.sale({
         "amount":
         request.data.get('amount'),
         "payment_method_nonce":
         request.data.get('payment_method_nonce'),
         "options": {
             "submit_for_settlement": True
         }
     })
     if result.is_success:
         return Response({"response": result.transaction.id})
     else:
         return Response({"response": result.message})
Пример #29
0
    def __init__(
        self,
        merchant_id: str,
        public_key: str,
        private_key: str,
        use_sandbox: bool = False,
    ):
        """
        Initialise a basic Braintree connection.

        See: https://developers.braintreepayments.com/start/hello-server/python
        """
        environment = (braintree.Environment.Sandbox
                       if use_sandbox else braintree.Environment.Production)

        self._gateway = braintree.BraintreeGateway(
            braintree.Configuration(
                environment,
                merchant_id=merchant_id,
                public_key=public_key,
                private_key=private_key,
            ))
Пример #30
0
    def create_braintree_customer(self, request):
        user = request.user
        f = open("post_requst_data.txt", "a")
        f.write("{}\n".format(request.data))
        if 'cof' in request.data:
            if 'cof_payment' not in request.data:
                attachment = get_random_string(length=10)
                return Response(data={'attachment': attachment})
            if 'cof_payment' in request.data:
                self.order_placed_handled()

        if 'payment_method_nonce' in request.data:
            self.order_placed_handled()

        if 'cof' not in request.data:
            config = braintree.BraintreeGateway(
                braintree.Configuration(
                    braintree.Environment.Production,
                    merchant_id=settings.BRAINTREE_MERCHANT_ID,
                    public_key=settings.BRAINTREE_PUBLIC_KEY,
                    private_key=settings.BRAINTREE_PRIVATE_KEY))

            if user.braintree_customer_id is None:
                create_customer = config.customer.create({
                    "email":
                    request.user.email,
                    "first_name":
                    request.user.first_name,
                    "last_name":
                    request.user.last_name
                })

                user.braintree_customer_id = create_customer.customer.id
                user.save()

            client_token = config.client_token.generate(
                {"customer_id": user.braintree_customer_id})
            return Response(data={'client_token': client_token})
        return Response(data={'result': True})