Exemplo n.º 1
0
def create_payment(request, item_list, tax = None, currency = 'USD'):
	currency = 'USD' if currency == None else str(currency)
	tax = '0' if tax == None else str(tax)
	current_site_domain = (get_current_site(request).domain + reverse('paypal_return_url').lstrip('/'))
	total_due = 0
	services_list = []
	for item in item_list:
		item_quote_price =  decimal.Decimal(item.quote_price)
		total_due += item_quote_price
		description =  getattr(item, str(item.service_type).lower()).description
		service_data = {
	                "name": item.service_type + ' service',
	                "sku": str(item.id),
	                "price": str( item_quote_price ),
	                "currency": str(currency),
	                "quantity": 1,
	                "description":  str(description)
	                #'user': str(request.user.id)
	    }	
		services_list.append( service_data )


	payment = Payment({
	    "intent": "sale",

	    # Payer
	    # A resource representing a Payer that funds a payment
	    # Payment Method as 'paypal'
	    "payer": {
	        "payment_method": "paypal"},

	    # Redirect URLs
	    "redirect_urls": {
	        "return_url": current_site_domain,
	        "cancel_url": get_current_site(request).domain},

	    # Transaction
	    # A transaction defines the contract of a
	    # payment - what is the payment for and who
	    # is fulfilling it.
	    "transactions": [{

	        # ItemList
	        "item_list": {
	            "items": services_list
	                },

	        # Amount
	        # Let's you specify a payment amount.
	        "amount": {
	            "total": str(total_due),
	            "currency": "USD"},
	        "description": "This is the payment transaction description."}]})

	# Create Payment and return status
	if payment.create():
	    return payment
	else:
	    print("Error while creating payment:")
	    print(payment.error)
Exemplo n.º 2
0
    def test_issue_credit(self):
        refund = self.create_refund(self.processor_name)
        order = refund.order
        basket = order.basket
        amount = refund.total_credit_excl_tax
        currency = refund.currency
        source = order.sources.first()

        transaction_id = 'PAY-REFUND-1'
        paypal_refund = paypalrestsdk.Refund({'id': transaction_id})

        payment = Payment(
            {'transactions': [Resource({'related_resources': [Resource({'sale': Sale({'id': 'PAY-SALE-1'})})]})]})
        with mock.patch.object(Payment, 'find', return_value=payment):
            with mock.patch.object(Sale, 'refund', return_value=paypal_refund):
                self.processor.issue_credit(source, amount, currency)

        # Verify PaymentProcessorResponse created
        self.assert_processor_response_recorded(self.processor.NAME, transaction_id, {'id': transaction_id}, basket)

        # Verify Source updated
        self.assertEqual(source.amount_refunded, amount)

        # Verify PaymentEvent created
        paid_type = PaymentEventType.objects.get(code='refunded')
        order = basket.order_set.first()
        payment_event = order.payment_events.first()
        self.assert_valid_payment_event_fields(payment_event, amount, paid_type, self.processor.NAME, transaction_id)
Exemplo n.º 3
0
    def test_issue_credit_error(self):
        refund = self.create_refund(self.processor_name)
        order = refund.order
        basket = order.basket
        amount = refund.total_credit_excl_tax
        currency = refund.currency
        source = order.sources.first()

        transaction_id = 'PAY-REFUND-FAIL-1'
        expected_response = {'debug_id': transaction_id}
        paypal_refund = paypalrestsdk.Refund({'error': expected_response})

        payment = Payment(
            {'transactions': [Resource({'related_resources': [Resource({'sale': Sale({'id': 'PAY-SALE-1'})})]})]})

        # Test general exception
        with mock.patch.object(Payment, 'find', return_value=payment):
            with mock.patch.object(Sale, 'refund', side_effect=ValueError):
                self.assertRaises(GatewayError, self.processor.issue_credit, source, amount, currency)
                self.assertEqual(source.amount_refunded, 0)

        # Test error response
        with mock.patch.object(Payment, 'find', return_value=payment):
            with mock.patch.object(Sale, 'refund', return_value=paypal_refund):
                self.assertRaises(GatewayError, self.processor.issue_credit, source, amount, currency)

        # Verify PaymentProcessorResponse created
        self.assert_processor_response_recorded(self.processor.NAME, transaction_id, expected_response, basket)

        # Verify Source unchanged
        self.assertEqual(source.amount_refunded, 0)
Exemplo n.º 4
0
    def process(self):
        configure_paypal()

        payment = Payment({
            "intent":
            "sale",

            # Set payment method
            "payer": {
                "payment_method": "paypal"
            },

            # Set redirect urls
            "redirect_urls": {
                "return_url": self.cleaned_data['return_url'],
                "cancel_url": self.cleaned_data['cancel_url'],
            },

            # Set transaction object
            "transactions": [{
                "amount": {
                    "total": self.cleaned_data['total_amount'],
                    "currency": self.cleaned_data['currency'],
                },
            }]
        })

        created = payment.create()
        return created, payment
Exemplo n.º 5
0
def create_payment(total_amount):
    server_address = "127.0.0.1:8000"
    if sys.argv[-1] != "runserver":
        server_address = sys.argv[-1]

    # Create payment object
    payment = Payment({
        "intent":
        "sale",

        # Set payment method
        "payer": {
            "payment_method": "paypal"
        },

        # Set redirect URLs
        "redirect_urls": {
            "return_url": "http://%s/process" % server_address,
            "cancel_url": "http://%s/cancel" % server_address,
        },

        # Set transaction object
        "transactions": [{
            "amount": {
                "total": total_amount,
                "currency": "HKD"
            },
            "description": "payment description",
            "payment_options": {
                "allowed_payment_method": "IMMEDIATE_PAY"
            },
        }]
    })

    # Create payment
    if payment.create():
        # print(payment)
        # Extract redirect url
        for link in payment.links:
            if link.rel == "approval_url":
                # Capture approval_url
                approval_url = link.href

                payment_token = parse_qs(
                    urlparse(approval_url).query).get('token')[0]
                return {
                    "approval_url": approval_url,
                    "payment_id": payment.id,
                    "payment_token": payment_token,
                }
                # Redirect the customer to approval_url
    else:
        print("Error while creating payment:")
        print(payment.error)

    return {"error": payment.error}
Exemplo n.º 6
0
def ride_booking_create_payment(ride_booking, request):
    ride_total = ride_booking.ride.price_with_fee * ride_booking.seats_count
    ride_detail_url = settings.RIDE_DETAIL_URL.format(
        ride_pk=ride_booking.ride.pk)
    payment = Payment({
        "intent":
        "sale",
        "payer": {
            "payment_method": "paypal"
        },
        "redirect_urls": {
            "return_url":
            request.build_absolute_uri(
                reverse('ridebooking-paypal-payment-execute',
                        kwargs={'pk': ride_booking.pk})),
            "cancel_url":
            ride_detail_url
        },
        "transactions": [{
            "item_list": {
                "items": [{
                    "name": "ride_booking",
                    "sku": "{0}".format(ride_booking.pk),
                    "price": '{0:.2f}'.format(ride_total),
                    "currency": "USD",
                    "quantity": 1
                }]
            },
            "amount": {
                "total": '{0:.2f}'.format(ride_total),
                "currency": "USD"
            },
            "description":
            "This is the payment transaction for the ride booking."
        }]
    })

    if not payment.create():
        raise Exception("Cannot create a payment:\n{0}".format(payment.error))

    approval_link = [
        link['href'] for link in payment.links if link['rel'] == 'approval_url'
    ][0]
    ride_booking.paypal_payment_id = payment.id
    ride_booking.paypal_approval_link = approval_link
    ride_booking.save()
    send_mail(
        'email_passenger_ride_booking_created', [ride_booking.client.email], {
            'booking':
            ride_booking,
            'ride_detail':
            settings.RIDE_DETAIL_URL.format(ride_pk=ride_booking.ride.pk)
        })
Exemplo n.º 7
0
def handle_paypal_payment(request, order, cart_items):
    items = [{
        'name': item.product.name,
        'quantity': item.quantity,
        'price': float(item.subtotal / item.quantity),
        'shipping': '0.00',
        'currency': 'USD'
    } for item in cart_items]

    items.append({
        'name': 'shipping',
        'quantity': 1,
        'price': float(order.shipping),
        'currency': 'USD'
    })

    payment = Payment({
        'intent':
        'sale',
        'payer': {
            'payment_method': 'paypal',
        },
        'redirect_urls': {
            'return_url': 'http://{}{}'.format(host,
                                               reverse('checkout_complete')),
            'cancel_url': 'http://{}{}'.format(host,
                                               reverse('checkout_canceled')),
        },
        'transactions': [{
            'amount': {
                'total': float(order.total),
                'currency': 'USD',
            },
            'description': order.ref_code,
            'item_list': {
                'items': items
            }
        }],
    })

    if payment.create():
        for link in payment.links:
            if link.method == 'REDIRECT':
                redirect_url = (link.href)
                order.charge_id = payment.id
                order.save()
                return redirect(redirect_url)
    else:
        messages.error(request,
                       'There was an error while processing your payment')
        messages.error(request, str(payment.error))
        pass
Exemplo n.º 8
0
def pay(id):
    item = Item.query.get_or_404(id)

    order = Order(
        buyer=current_user,
        item=item,
        amount=item.price,
    )
    db.session.add(order)
    db.session.commit()

    payment = Payment(
        dict(
            intent='sale',
            payer=dict(payment_method='paypal'),
            redirect_urls=dict(
                return_url=url_for('execute', id=order.id, _external=True),
                cancel_url=url_for('cancel', id=order.id, _external=True),
            ),
            transactions=[
                dict(
                    item_list=dict(items=[
                        dict(
                            name=item.name,
                            price=float(item.price),
                            currency='EUR',
                            quantity=1,
                        ),
                    ]),
                    amount=dict(total=float(item.price), currency='EUR'),
                    description='Thank you for your purchase!',
                )
            ],
        ))

    if not payment.create():
        db.session.delete(order)
        db.session.commit()

        flash('An error occured while creating your payment: {}'.format(
            payment.error))
        return redirect(url_for('view_shop_item', id=item.id))

    order.payment_id = payment.id
    db.session.commit()

    for link in payment.links:
        if link.rel == 'approval_url':
            return redirect(link.href)

    abort(500)
Exemplo n.º 9
0
def paypal_buy(request):
    paypalrestsdk.configure({
        "mode": settings.PAYPAL_MODE,
        "client_id": settings.PAYPAL_CLIENT_ID,
        "client_secret": settings.PAYPAL_CLIENT_SECRET})

    payment = Payment({
        "intent": "sale",

        # ###Payer
        # A resource representing a Payer that funds a payment
        # Payment Method as 'paypal'
        "payer": {
            "payment_method": "paypal"
        },

        # ###Redirect URLs
        "redirect_urls": {
            "return_url": settings.PAYPAL_RETURN_URL,
            "cancel_url": settings.PAYPAL_CANCEL_URL,
        },

        # ###Transaction
        # A transaction defines the contract of a
        # payment - what is the payment for and who
        # is fulfilling it.
        "transactions": [{

                             # ### ItemList
                             "item_list": {
                                 "items": [{
                                               "name": "item",
                                               "sku": "item",
                                               "price": "0.10",
                                               "currency": "USD",
                                               "quantity": 1}]},

                             # ###Amount
                             # Let's you specify a payment amount.
                             "amount": {
                                 "total": "0.10",
                                 "currency": "USD"},
                             "description": "This is the payment transaction description......"}]})

    # Create Payment and return status
    if payment.create():
        response = {'data': {'url': payment.links[1]}}
    else:
        response = {'error': 'Something went wrong.'}
    return HttpResponse(json.dumps(response, sort_keys=True, indent=4, cls=DjangoJSONEncoder), content_type="application/json")
Exemplo n.º 10
0
def paypal_payment_handler(request, order_form, order):
    """
	Default payment handler - called when the final step of the
	checkout process with payment information is submitted. Implement
	your own and specify the path to import it from via the setting
	``SHOP_HANDLER_PAYMENT``. This function will typically contain
	integration with a payment gateway. Raise
	cartridge.shop.checkout.CheckoutError("error message") if payment
	is unsuccessful.
	"""

    logger.debug("integration.checkout.paypal_payment_handler()")

    logger.debug("request %s \n order_form %s \n order %s" %
                 (request, order_form, order))

    data = order_form.cleaned_data
    locale.setlocale(locale.LC_ALL, settings.SHOP_CURRENCY_LOCALE)
    currency = locale.localeconv()
    currency_code = currency['int_curr_symbol'][0:3]
    logger.debug("Currency Code %s" % currency_code)

    server_host = request.get_host()
    payment = Payment({
        "intent":
        "sale",
        "payer": {
            "payment_method": "paypal",
        },
        "redirect_urls": {
            "return_url": "http://%s/integration/execute" % server_host,
            "cancel_url": "http://%s/integration/cancel" % server_host
        },
        "transactions": [{
            "amount": {
                "total": str(order.total),
                "currency": currency_code
            },
            "description": "Compra de Produtos na loja."
        }]
    })

    if payment.create():
        logger.debug("Payment[%s] created successfully" % (payment.id))
        return payment.id
    else:
        # Display Error message
        logger.error("Payment error \n %s" % payment)
        raise CheckoutError(payment.error)
Exemplo n.º 11
0
def donate(bot, trigger):
  api = create_api(bot.config.donabot)
  currency = "EUR"

  amount = float(trigger.group(1))
  bot.reply("Just a moment, contacting PayPal...")

  return_url = "http://{}/return?nickname={}" \
    .format(bot.config.donabot.web_endpoint, bot.nick)
  cancel_url = "http://{}/cancel".format(bot.config.donabot.web_endpoint)

  payment = Payment({
      "intent": "authorize",
      "payer": {"payment_method": "paypal"},
      "redirect_urls": {
        "return_url": return_url,
        "cancel_url": cancel_url,
      },

      "transactions": [
        {
          "description": "Donation for Stefan Schindler",
          "amount": {
            "total": amount,
            "currency": currency,
          },
        },
      ],
  }, api=api)

  create_result = payment.create()

  if create_result is True:
    links = [link for link in payment.links if link.method == "REDIRECT"]

    if len(links) < 1:
      bot.msg(trigger.nick, "An error occured. :-(")

    else:
      link = links[0]

      bot.msg(
        trigger.nick,
        "Please visit the following URL to authorize the donation: {}" \
          .format(link.href),
      )

  else:
    bot.msg(trigger.nick, "Payment couldn't be created.")
Exemplo n.º 12
0
    def create(self, ticket):
        price_str = ("%.2f" % ticket.total)

        payment = Payment({
            "intent": "sale",
            "payer": {
                "payment_method": "paypal"
            },
            "redirect_urls": {
                "return_url": self.return_url,
                "cancel_url": self.cancel_url
            },
            "transactions": [{
                "item_list": {
                    "items": [{
                        "name": "Billet LAN Montmorency",
                        "sku": str(ticket.id),
                        "price": price_str,
                        "currency": "CAD",
                        "quantity": 1
                    }]
                },
                "amount": {
                    "total": price_str,
                    "currency": "CAD"
                },
                "description": ("Billet LAN Montmorency %d" % ticket.id)
            }]
        })

        if payment.create():
            temp_payment = {}

            for link in payment.links:
                if link.method == "REDIRECT":
                    # Convert to str to avoid google appengine unicode issue
                    # https://github.com/paypal/rest-api-sdk-python/pull/58
                    temp_payment['redirect_url'] = str(link.href)

            temp_payment['paypal_payment_id'] = payment['id']
            return temp_payment
        else:
            raise Exception("Erreur lors de la création du paiment: {}"
                            % payment.error)
Exemplo n.º 13
0
    def charge(self, amount):
        """
        Documentation: https://github.com/paypal/PayPal-Python-SDK

        Charge the credit card for the given amount, floored to 2 decimal
        places. Raises InvalidCreditCardException if charge fails.

        Charing is enabled by default in settings.py. However, in development,
        charges go to the PayPal Sandbox, which means that your card shouldn't
        actually be charged (it'll just show up in the Sandbox charge history).
        When on production, payments go to a live PayPal, where cards are
        actually charged.

        :param amount:
        """
        amount = "{0:.2f}".format(floor(amount * 100) / 100.0)  # floor
        payment = Payment({
            "intent": "sale",
            "payer": {
                "payment_method": "credit_card",
                "funding_instruments": [{
                    "credit_card": self.credit_card.to_dict()
                }]
            },
            "transactions": [{
                "item_list": {
                    "items": [{
                        "name": "Donation",
                        "sku": "item",
                        "price": amount,
                        "currency": "USD",
                        "quantity": 1
                    }]
                },
                "amount": {
                    "total": amount,
                    "currency": "USD"
                },
                "description": "This is a charitable donation to a Revolv funded project.",
            }]
        })

        if not payment.create():
            raise InvalidCreditCardException(payment.error)
Exemplo n.º 14
0
def pay(amount):
    payment = Payment({
        "intent":
        "sale",
        "payer": {
            "payment_method": "paypal"
        },

        # Url's that users will be redirected to after finishing their payment
        "redirect_urls": {
            "return_url":
            "https://clicknwin.pythonanywhere.com/paypalStoreReturn",
            "cancel_url": "https://clicknwin.pythonanywhere.com"
        },
        "transactions": [{
            "item_list": {
                "items": [{
                    "name": "item",
                    "sku": "item",
                    "price": amount,
                    "currency": "EUR",
                    "quantity": 1
                }]
            },
            "amount": {
                "total": amount,
                "currency": "EUR"
            },
            "description":
            "This is the payment transaction description."
        }]
    })

    if payment.create():
        print("Payment[%s] created successfully" % (payment.id))
        for link in payment.links:
            if link.method == "REDIRECT":
                redirect_url = str(link.href)
                data = [redirect_url, payment.id]
                return data
    else:
        return False
Exemplo n.º 15
0
    def execute(self, request, data):
        from paypalrestsdk import Payment
        # https://developer.paypal.com/docs/api/quickstart/payments/#initialize-the-payment-and-redirect-the-user
        params = self.settings
        payment = Payment({
            "intent":
            "sale",
            # "experience_profile_id":"experience_profile_id",
            "redirect_urls": {
                "return_url": params['returnUrl'],
                "cancel_url": params['cancelUrl']
            },
            "payer": {
                "payment_method": "paypal"
            },
            "transactions": [{
                "amount": {
                    "total": str(self.payment.amount),
                    "currency": self.payment.currency
                },
                "description": str(self.payment.cause),
                # "invoice_number": "merchant invoice",
                # "custom":  self.payment.id
            }]
        })
        if payment.create():
            self.payment.payment_id = payment.id
            self.payment.change_status(PaymentStatus.WAITING)
            self.payment.save()
            for link in payment.links:
                if link.method == "REDIRECT":
                    # Capture redirect url
                    redirect_url = link.href
                    # REDIRECT USER to redirect_url
            else:
                print("Error while creating payment:")
                print(payment.error)

        return redirect(redirect_url)
Exemplo n.º 16
0
def get_paypal_payment_url(amount_total,
                           description_description="",
                           base_url="",
                           mode="live",
                           client_id=None,
                           client_secret=None):
    get_config(mode, client_id, client_secret)
    payment = Payment({
        "intent":
        "sale",
        "payer": {
            "payment_method": "paypal"
        },
        # Set redirect URLs
        "redirect_urls": {
            "return_url": base_url + "/payment/paypal/return",
            "cancel_url": base_url + "/payment/paypal/cancel"
        },

        # Set transaction object
        "transactions": [{
            "amount": {
                "total": amount_total,
                "currency": "USD"
            },
            "description": description_description
        }]
    })
    if payment.create():
        logging.info("payment.create, %s", payment)
        for link in payment.links:
            if link.method == "REDIRECT":
                redirect_url = (link.href)
                # print(redirect_url)
                return redirect_url
    else:
        logging.error("Error while creating payment: %s", payment)
    raise Exception("get paypal payment url error")
Exemplo n.º 17
0
    async def crowns(self, ctx):
        embed = discord.Embed(title="Crowns",
                              description="\n\nPlease type the number by the amount you want\n```md\n1. <$1.00> 100 Crowns\n2. <$2.00> 210 Crowns (10 bonus)\n3. <$5.00> 600 Crowns (100 bonus)\n4. <$10.00> 1,300 Crowns (300 bonus)\n```",
                              color=Config.MAINCOLOR)
        og_message = await ctx.send(embed=embed)

        def check(msg):
            return msg.channel.id == ctx.channel.id and msg.author.id == ctx.author.id and msg.content.lower() in [
                '1', '2', '3', '4']

        try:

            # Paypal integration wasn't completed, as KAJ7#0001 was removed from the team before they could finish
            # the feature. And so that's why this is a mess.

            msg = await self.bot.wait_for('message', timeout=200, check=check)
            choice_to_payment = {'1':
                Payment({
                    "intent": "order",

                    # Set payment method
                    "payer": {
                        "payment_method": "paypal"
                    },

                    # Set redirect urls
                    "redirect_urls": {
                        "return_url": "http://localhost:3000/process",
                        "cancel_url": "http://localhost:3000/cancel"
                    },

                    # Set transaction object
                    "transactions": [{
                        "amount": {
                            "total": "1.00",
                            "currency": "USD",
                            "details": {
                                "subtotal": "1.00",
                                "tax": "0.00"
                            }
                        },
                        "description": "Crowns for usage on Enchanted Cosmetics.",
                        "invoice_number": "23423522324234234",
                        "payment_options": {
                            "allowed_payment_method": "INSTANT_FUNDING_SOURCE"
                        },
                        "item_list": {
                            "items": [{
                                "name": "Crown",
                                "quantity": "100",
                                "price": "0.01",
                                "tax": "0.00",
                                "sku": "1",
                                "currency": "USD"
                            }]
                        }
                    }]
                })
            }

            # Create payment
            if choice_to_payment[msg.content.lower()].create():
                # Extract redirect url
                for link in choice_to_payment[msg.content.lower()].links:
                    if link.method == "REDIRECT":
                        # Capture redirect url
                        redirect_url = str(link.href)
                        await ctx.send(embed=discord.Embed(title="Complete Purchase", color=Config.MAINCOLOR,
                                                           description="To complete this purchase, please click this link:\n\n> " + redirect_url))
                        return
            else:
                await ctx.send(embed=discord.Embed(title="Failed to create order", color=Config.ERRORCOLOR,
                                                   description="Please try again later"))
                return


        except asyncio.TimeoutError:
            await og_message.delete()
            return
Exemplo n.º 18
0
    def create(self, ticket):
        if ticket.seat_num:
            item_name = "Billet LAN Montmorency 2015 BYOC {}" \
                .format(ticket.seat_num)
        else:
            item_name = "Billet LAN Montmorency 2015 Console"

        items = [{
            "name": item_name,
            "sku": "SKU2015REF{}".format(ticket.id),
            "price": "{:.2f}".format(ticket.price),
            "currency": "CAD",
            "quantity": 1
        }]

        if ticket.discount_amount > 0:
            items.append({
                "name": "Rabais pour étudiant du Collège Montmorency",
                "sku": "SKU2015RABAISMOMO",
                "price": "-{:.2f}".format(ticket.discount_amount),
                "currency": "CAD",
                "quantity": 1
            })

        payment = Payment({
            "intent":
            "sale",
            "payer": {
                "payment_method": "paypal"
            },
            "redirect_urls": {
                "return_url": self.return_url,
                "cancel_url": self.cancel_url
            },
            "transactions": [{
                "item_list": {
                    "items": items
                },
                "amount": {
                    "total": "{:.2f}".format(ticket.total),
                    "currency": "CAD"
                },
                "description":
                "Achat de votre billet LAN Montmorency 2015"
            }]
        })

        if payment.create():
            temp_payment = {}

            for link in payment.links:
                if link.method == "REDIRECT":
                    # Convert to str to avoid google appengine unicode issue
                    # https://github.com/paypal/rest-api-sdk-python/pull/58
                    temp_payment['redirect_url'] = str(link.href)

            temp_payment['paypal_payment_id'] = payment['id']
            return temp_payment
        else:
            raise Exception("Erreur lors de la création du paiment: {}".format(
                payment.error))
Exemplo n.º 19
0
def create_direct_pay_by_paypal(payment_method, name, description, total_fee,
                                **kwargs):
    """
    paypal及时到账接口
    paid_method: 支付方式 paypal_balance, visa
    intent: payment类型 sale, authorize, order
    total_fee: 价格
    name: 商品名称
    description: 商品描述
    **kwargs: 信用卡方式信用卡信息 number, expire_month, expire_year, cvv2
    """
    if payment_method == 'paypal_balance':
        # paypal余额会确认订单, 生成重定向连接
        payment = Payment({
            "intent":
            "sale",
            "payer": {
                "payment_method": "paypal"
            },
            "redirect_urls": {
                "return_url": settings.RETURN_URL,
                "cancel_url": settings.CANCEL_URL
            },
            "transactions": [{
                "item_list": {
                    "items": [{
                        "name": name,
                        "price": total_fee,
                        "currency": "USD",
                        "quantity": 1
                    }]
                },
                "amount": {
                    "total": total_fee,
                    "currency": "USD"
                },
                "description": description
            }]
        })
    else:
        # 信用卡将不会有确认动作, 将直接执行扣款
        payment = Payment({
            "intent":
            "sale",
            "payer": {
                "payment_method":
                "credit_card",
                "funding_instruments": [{
                    "credit_card": {
                        "type": "visa",
                        "number": kwargs['number'],
                        "expire_month": kwargs['expire_month'],
                        "expire_year": kwargs['expire_year']
                    }
                }]
            },
            "transactions": [{
                "item_list": {
                    "items": [{
                        "name": name,
                        "price": total_fee,
                        "currency": "USD",
                        "quantity": 1
                    }]
                },
                "amount": {
                    "total": total_fee,
                    "currency": "USD"
                },
                "description": description
            }]
        })
    # Create Payment and return status
    if payment.create():
        log.info('[payment] paypal payment %s create success', payment.id)
        for link in payment.links:
            if link.method == "REDIRECT":
                redirect_url = str(link.href)
                return redirect_url, payment.id
        return payment, None
    else:
        log.error('[payment] paypal payment create fail, %s', payment.error)
        return None, None
Exemplo n.º 20
0
def checkout_paypal(request,cart,orders):
    items = []
    total=0
    for order in orders:
        total += (order.recipe.price)
        recipe= order.recipe
        item= {
            'name': recipe.title,
            'price': str(recipe.price),
            'currency': 'USD',
            'quantity': 1
        }
        items.append(item)

    paypalrestsdk.configure({
        "mode": "sandbox",
        "client_id": ENTER OWN,
        "client_secret": ENTER OWN,
    })
   
    payment = Payment({
    "intent": "sale",

    # Payer: A resource representing a Payer that funds a payment
    # Payment Method as 'paypal'
    "payer": {
        "payment_method": "paypal"},

    # Redirect URLs
    "redirect_urls": {
        "return_url": "http://localhost:8000/cards/process/paypal",
        "cancel_url": "http://localhost:8000/cards/home"},
   
    # Transaction
    "transactions": [{

        # ItemList
        "item_list": {
            "items": items},

        # Amount
        # Let's you specify a payment amount.
        "amount": {
            "total": str(total),
            "currency": "USD"},
        "description": "This is the payment transaction description."}]})

# Create Payment and return status
    if payment.create():
        cart_instance = cart
        cart_instance.payment_id= payment.id
        cart_instance.save()
                   
        print("Payment[%s] created successfully" % (payment.id))
        # Redirect the user to given approval url
        for link in payment.links:
            if link.method == "REDIRECT":
                redirect_url = str(link.href)
                print("Redirect for approval: %s" % (redirect_url))
                return redirect_url
    else:
        print("Error while creating payment:")
        print(payment.error)
Exemplo n.º 21
0
def payment(request):  #card payment
    context = {}
    if (request.method == 'POST'):
        paymentData = request.session['payment']
        deliveryData = request.session['delivery']
        comment = request.session['comment']
        total = request.session.get('basket_total')

        first_name, second_name = paymentData['card_holdername'].split(" ")

        payment = Payment({
            "intent":
            "sale",
            "payer": {
                "payment_method":
                "credit_card",
                "funding_instruments": [{
                    "credit_card": {
                        "type": paymentData['card_type'],  #"visa",
                        "number":
                        paymentData['card_number'],  #"4601044104515989",
                        "expire_month": paymentData['expiry_month'],  #"11",
                        "expire_year": paymentData['expiry_year'],  #"2018",
                        "cvv2": paymentData['cvv'],  #"874",
                        "first_name": first_name,  #"Joe",
                        "last_name": second_name,  #"Shopper",
                        "billing_address": {
                            "line1": deliveryData['street'],  #"52 N Main ST",
                            "city": deliveryData['city'],  #"Johnstown",
                            #"state": "OH",
                            "postal_code": deliveryData['postcode'],  #"43210",
                            "country_code": "GB"
                        }
                    }
                }]
            },
            "transactions": [{
                "amount": {
                    "total": total,  #"7.47",
                    "currency": "GBP"
                },
                "description":
                "This is the payment transaction description."
            }]
        })

        # Create payment
        if payment.create():
            order = Order(product=request.session['ordered_products'],
                          total=float(total),
                          paymentType="Card",
                          deliveryType=request.session['order_info'],
                          address=deliveryData['street'] + ", " +
                          deliveryData['city'] + ", " +
                          deliveryData['postcode'],
                          name=deliveryData['name'],
                          status="Order Received",
                          email=request.session['account']['email'],
                          date=datetime.datetime.now(),
                          comment=comment,
                          option=deliveryData['total']['selectedOption'])
            order.save()

            context = {
                "orderStatus": "Order Received",
                "status": "success",
                "message": "Payment created successfully",
                'data': payment.id,
                "orderId": order.id
            }
            request.session['basket'] = {}
            request.session['checkout'] = {}

        else:
            # Display Error message
            context = {
                "status": "failed",
                "message": "Error while creating payment:",
                "data": payment.error
            }
    return render(request, 'website/ordered.html', context)
payment = Payment({
    "intent":
    "sale",

    # Payer
    # A resource representing a Payer that funds a payment
    # Payment Method as 'paypal'
    "payer": {
        "payment_method": "paypal"
    },

    # Redirect URLs
    "redirect_urls": {
        "return_url": "http://localhost:3000/payment/execute",
        "cancel_url": "http://localhost:3000/"
    },

    # Transaction
    # A transaction defines the contract of a
    # payment - what is the payment for and who
    # is fulfilling it.
    "transactions": [{

        # ItemList
        "item_list": {
            "items": [{
                "name": "item",
                "sku": "item",
                "price": "5.00",
                "currency": "USD",
                "quantity": 1
            }]
        },

        # Amount
        # Let's you specify a payment amount.
        "amount": {
            "total": "5.00",
            "currency": "USD"
        },
        "description":
        "This is the payment transaction description."
    }]
})
Exemplo n.º 23
0
payment = Payment({
    "intent":
    "sale",

    # Payer
    # A resource representing a Payer that funds a payment
    # Use the List of `FundingInstrument` and the Payment Method
    # as 'credit_card'
    "payer": {
        "payment_method":
        "credit_card",

        # FundingInstrument
        # A resource representing a Payeer's funding instrument.
        # Use a Payer ID (A unique identifier of the payer generated
        # and provided by the facilitator. This is required when
        # creating or using a tokenized funding instrument)
        # and the `CreditCardDetails`
        "funding_instruments": [{

            # CreditCard
            # A resource representing a credit card that can be
            # used to fund a payment.
            "credit_card": {
                "type": "visa",
                "number": "4417119669820331",
                "expire_month": "11",
                "expire_year": "2018",
                "cvv2": "874",
                "first_name": "Joe",
                "last_name": "Shopper",

                # Address
                # Base Address used as shipping or billing
                # address in a payment. [Optional]
                "billing_address": {
                    "line1": "52 N Main ST",
                    "city": "Johnstown",
                    "state": "OH",
                    "postal_code": "43210",
                    "country_code": "US"
                }
            }
        }]
    },
    # Transaction
    # A transaction defines the contract of a
    # payment - what is the payment for and who
    # is fulfilling it.
    "transactions": [{

        # ItemList
        "item_list": {
            "items": [{
                "name": "item",
                "sku": "item",
                "price": "1.00",
                "currency": "USD",
                "quantity": 1
            }]
        },

        # Amount
        # Let's you specify a payment amount.
        "amount": {
            "total": "1.00",
            "currency": "USD"
        },
        "description":
        "This is the payment transaction description."
    }]
})
Exemplo n.º 24
0
    def post(self, request):
        # logger.error("request")
        # logger.error(request.META)
        logger.error("data")
        logger.error(request.data)

        if not 'borrow_request_slug' in request.data:
            return Response({"error": "Must supply BorrowRequest slug"},
                            status=status.HTTP_400_BAD_REQUEST)

        borrow_request = BorrowRequest.objects.get(
            slug=request.data['borrow_request_slug'])

        if request.user != borrow_request.borrower:
            return Response({"error": "User is not the borrower"},
                            status=status.HTTP_400_BAD_REQUEST)

        if borrow_request.lender_accepted != True:
            return Response(
                {
                    "error":
                    "Cannot Pay for request that lender has not accepted"
                },
                status=status.HTTP_400_BAD_REQUEST)

        item = borrow_request.item
        transaction_price = borrow_request.total_price
        start_date = str(borrow_request.date_used_start).replace(' ', 'T')
        end_date = str(borrow_request.date_used_end).replace(' ', 'T')
        days = borrow_request.duration

        start_date = start_date[:start_date.index('+')] + 'Z'
        end_date = end_date[:end_date.index('+')] + 'Z'

        today = timezone.now().date()
        _pickup = parse_datetime(start_date)
        print(today)
        print(_pickup.date())

        if _pickup.date() < today:
            return Response({"error": "Pick Up date has already passed"},
                            status=status.HTTP_400_BAD_REQUEST)

        payment = Payment({
            "intent":
            "sale",
            "payer": {
                "payment_method": "paypal"
            },
            "redirect_urls": {
                "return_url": "http://borrowonce.com",
                "cancel_url": "http://borrowonce.com"
            },
            "transactions": [{
                "item_list": {
                    "items": [{
                        "name": item.title,
                        "sku": item.id,
                        "price": str(item.price_per_day),
                        "currency": "USD",
                        "quantity": days
                    }]
                },
                "amount": {
                    "total": str(transaction_price),
                    "currency": "USD"
                },
                "description":
                "Borrowing this item for %s days" % (days),
                # used for validating that Transaction creation in DB
                "custom":
                str(request.user.id) + ',' + start_date + ',' + end_date +
                ',' + str(borrow_request.slug)
            }]
        })

        if payment.create():
            print(payment.id)
            return Response({"paymentID": payment.id})
        else:
            logger.error("Payment creation failed")
            logger.error(payment.error)
            return Response("An error has occurred.")
Exemplo n.º 25
0
def createPaypalPayment(request):
    '''
    This view handles the creation of Paypal Express Checkout Payment objects.

    All Express Checkout payments must either be associated with a pre-existing Invoice
    or a registration, or they must have an amount and type passed in the post data
    (such as gift certificate payment requests).
    '''
    logger.info('Received request for Paypal Express Checkout payment.')

    invoice_id = request.POST.get('invoice_id')
    tr_id = request.POST.get('reg_id')
    amount = request.POST.get('amount')
    submissionUserId = request.POST.get('user_id')
    transactionType = request.POST.get('transaction_type')
    taxable = request.POST.get('taxable', False)

    # If a specific amount to pay has been passed, then allow payment
    # of that amount.
    if amount:
        try:
            amount = float(amount)
        except ValueError:
            logger.error('Invalid amount passed')
            return HttpResponseBadRequest()

    # Parse if a specific submission user is indicated
    submissionUser = None
    if submissionUserId:
        try:
            submissionUser = User.objects.get(id=int(submissionUserId))
        except (ValueError, ObjectDoesNotExist):
            logger.warning(
                'Invalid user passed, submissionUser will not be recorded.')

    try:
        # Invoice transactions are usually payment on an existing invoice.
        if invoice_id:
            this_invoice = Invoice.objects.get(id=invoice_id)
            this_description = _('Invoice Payment: %s' % this_invoice.id)
            if not amount:
                amount = this_invoice.outstandingBalance
        # This is typical of payment at the time of registration
        elif tr_id:
            tr = TemporaryRegistration.objects.get(id=int(tr_id))
            tr.expirationDate = timezone.now() + timedelta(
                minutes=getConstant('registration__sessionExpiryMinutes'))
            tr.save()
            this_invoice = Invoice.get_or_create_from_registration(
                tr, submissionUser=submissionUser)
            this_description = _('Registration Payment: #%s' % tr_id)
            if not amount:
                amount = this_invoice.outstandingBalance
        # All other transactions require both a transaction type and an amount to be specified
        elif not transactionType or not amount:
            logger.error(
                'Insufficient information passed to createPaypalPayment view.')
            raise ValueError
        else:
            # Gift certificates automatically get a nicer invoice description
            if transactionType == 'Gift Certificate':
                this_description = _('Gift Certificate Purchase')
            else:
                this_description = transactionType
            this_invoice = Invoice.create_from_item(
                float(amount),
                this_description,
                submissionUser=submissionUser,
                calculate_taxes=(taxable is not False),
                transactionType=transactionType,
            )
    except (ValueError, ObjectDoesNotExist) as e:
        logger.error(
            'Invalid registration information passed to createPaypalPayment view: (%s, %s, %s)'
            % (invoice_id, tr_id, amount))
        logger.error(e)
        return HttpResponseBadRequest()

    this_currency = getConstant('general__currencyCode')

    this_total = min(this_invoice.outstandingBalance, amount)
    this_subtotal = this_total - this_invoice.taxes

    this_transaction = {
        'amount': {
            'total': round(this_total, 2),
            'currency': this_currency,
            'details': {
                'subtotal': round(this_subtotal, 2),
                'tax': round(this_invoice.taxes, 2),
            },
        },
        'description': str(this_description),
        'item_list': {
            'items': []
        }
    }

    for item in this_invoice.invoiceitem_set.all():

        if not getConstant('registration__buyerPaysSalesTax'):
            this_item_price = item.grossTotal - item.taxes
        else:
            this_item_price = item.grossTotal

        this_transaction['item_list']['items'].append({
            'name':
            str(item.name),
            'price':
            round(this_item_price, 2),
            'tax':
            round(item.taxes, 2),
            'currency':
            this_currency,
            'quantity':
            1,
        })

    # Because the Paypal API requires that the subtotal add up to the sum of the item
    # totals, we must add a negative line item for discounts applied, and a line item
    # for the remaining balance if there is to be one.
    if this_invoice.grossTotal != this_invoice.total:
        this_transaction['item_list']['items'].append({
            'name':
            str(_('Total Discounts')),
            'price':
            round(this_invoice.total, 2) - round(this_invoice.grossTotal, 2),
            'currency':
            this_currency,
            'quantity':
            1,
        })
    if this_invoice.amountPaid > 0:
        this_transaction['item_list']['items'].append({
            'name':
            str(_('Previously Paid')),
            'price':
            -1 * round(this_invoice.amountPaid, 2),
            'currency':
            this_currency,
            'quantity':
            1,
        })
    if amount != this_invoice.outstandingBalance:
        this_transaction['item_list']['items'].append({
            'name':
            str(_('Remaining Balance After Payment')),
            'price':
            round(amount, 2) - round(this_invoice.outstandingBalance, 2),
            'currency':
            this_currency,
            'quantity':
            1,
        })

    # Paypal requires the Payment request to include redirect URLs.  Since
    # the plugin can handle actual redirects, we just pass the base URL for
    # the current site.
    site = SimpleLazyObject(lambda: get_current_site(request))
    protocol = 'https' if request.is_secure() else 'http'
    base_url = SimpleLazyObject(
        lambda: "{0}://{1}".format(protocol, site.domain))

    payment = Payment({
        'intent': 'sale',
        'payer': {
            'payment_method': 'paypal'
        },
        'transactions': [this_transaction],
        'redirect_urls': {
            'return_url': str(base_url),
            'cancel_url': str(base_url),
        }
    })

    if payment.create():
        logger.info('Paypal payment object created.')

        if this_invoice:
            this_invoice.status = Invoice.PaymentStatus.authorized
            this_invoice.save()

            # We just keep a record of the ID and the status, because the
            # API can be used to look up everything else.
            PaypalPaymentRecord.objects.create(
                paymentId=payment.id,
                invoice=this_invoice,
                status=payment.state,
            )

        return JsonResponse(payment.to_dict())
    else:
        logger.error('Paypal payment object not created.')
        logger.error(payment)
        logger.error(payment.error)
        if this_invoice:
            this_invoice.status = Invoice.PaymentStatus.error
            this_invoice.save()
        return HttpResponseBadRequest()
Exemplo n.º 26
0
def paypal_create(request):
    """
     Paypal > Create a Payment
    """
    try:
        if request.method == 'POST':
            user = request.user
            id = request.POST['id']
            o = order.objects.get(id=id)

            if o is None:
                raise Exception('app do not exist ')

            payment = Payment({
                "intent":
                "sale",

                # ###Payer
                # A resource representing a Payer that funds a payment
                # Payment Method as 'paypal'
                "payer": {
                    "payment_method": "paypal"
                },

                # ###Redirect URLs
                "redirect_urls": {
                    "return_url":
                    "http://%s/cgi-bin/defray/execute/" % DOMAIN_NAME,
                    "cancel_url":
                    "http://%s/cgi-bin/defray/execute_failed/" % DOMAIN_NAME
                },

                # ###Transaction
                # A transaction defines the contract of a
                # payment - what is the payment for and who
                # is fulfilling it.
                "transactions": [{

                    # ### ItemList
                    "item_list": {
                        "items": [{
                            "name":
                            "%s-%s" % (o.order_appname, o.order_package),
                            "sku":
                            "app",
                            "price":
                            "%s" % o.order_values,
                            "currency":
                            "USD",
                            "quantity":
                            1
                        }]
                    },

                    # ###Amount
                    # Let's you specify a payment amount.
                    "amount": {
                        "total": "%s" % o.order_values,
                        "currency": "USD"
                    },
                    "description":
                    "This is the payment for Phimpme APP."
                }]
            })

            # Create Payment and return status
            if payment.create():
                print("Payment[%s] created successfully" % (payment.id))
                request.session['payment_id'] = payment.id
                o.order_payment_id = payment.id
                o.save()
                # Redirect the user to given approval url
                for link in payment.links:
                    if link.method == "REDIRECT":
                        redirect_url = link.href
                        print("Redirect for approval: %s" % (redirect_url))
                return HttpResponseRedirect(redirect_url)
            else:
                print("Error while creating payment:")
                raise Exception(payment.error)
        else:
            raise Exception('operation is not allowed ')
    except Exception, e:
        return render_to_response('error.html', {'msg': '%s' % e})
Exemplo n.º 27
0
def create_payment(current_user):
    data = request.json

    if not data:
        return jsonify({'message': 'No data given'}), 400

    if current_user is not None:  # if it is None then it's an anonymous donation
        data['donator_id'] = str(current_user.id)
    else:
        data[
            'donator_id'] = None  # make sure it's set to None, otherwise user can manipulate which user donated

    # load and validate
    result = donation_schema.load(data, partial=True)

    if len(result.errors) > 0:
        return jsonify({'errors': result.errors}), 422

    project = find_project_or_404(result.data['project_id'])

    payment = Payment({
        'intent':
        'sale',
        'payer': {
            'payment_method': 'paypal'
        },
        'redirect_urls': {
            'return_url':
            url_for('.success', _external=True),  # result.data['return_url'],
            'cancel_url':
            url_for('.cancel', _external=True),  # result.data['cancel_url'],
        },
        'transactions': [{
            'amount': {
                'total': '%.2f' % result.data['amount'],
                'currency': 'EUR',
            },
            'description': "Regalos Project Donation.",
            'item_list': {
                'items': [{
                    'name':
                    'Project Donation',
                    'description':
                    'Donation to {project_title}'.format(
                        project_title=project.title),
                    'price':
                    '%.2f' % result.data['amount'],
                    'currency':
                    'EUR',
                    'quantity':
                    '1',
                }]
            }
        }]
    })

    if payment.create():
        result.data['paypal_payment_id'] = payment.id
        donation_schema.load(result.data)
        if len(result.errors) > 0:
            return jsonify({'errors': result.errors}), 422
        del result.data['project_id']
        del result.data['donator_id']
        new_donation = Donation(**result.data)
        new_donation.save()
        for link in payment.links:
            if link.rel == 'approval_url':
                return jsonify({
                    'message':
                    'Donation created!',
                    'approval_url':
                    str(link.href),
                    'donation':
                    donation_schema.dump(new_donation).data
                })
    else:
        return jsonify({
            'message': 'Could not create paypal payment',
            'error': payment.error
        }), 409
payment = Payment({
    "intent":
    "sale",
    # ###Payer
    # A resource representing a Payer that funds a payment
    # Use the List of `FundingInstrument` and the Payment Method
    # as 'credit_card'
    "payer": {
        "payment_method":
        "credit_card",

        # ###FundingInstrument
        # A resource representing a Payeer's funding instrument.
        # In this case, a Saved Credit Card can be passed to
        # charge the payment.
        "funding_instruments": [{
            # ###CreditCardToken
            # A resource representing a credit card that can be
            # used to fund a payment.
            "credit_card_token": {
                "credit_card_id": "CARD-5BT058015C739554AKE2GCEI"
            }
        }]
    },

    # ###Transaction
    # A transaction defines the contract of a
    # payment - what is the payment for and who
    # is fulfilling it
    "transactions": [{

        # ### ItemList
        "item_list": {
            "items": [{
                "name": "item",
                "sku": "item",
                "price": "1.00",
                "currency": "USD",
                "quantity": 1
            }]
        },

        # ###Amount
        # Let's you specify a payment amount.
        "amount": {
            "total": "1.00",
            "currency": "USD"
        },
        "description":
        "This is the payment transaction description."
    }]
})
Exemplo n.º 29
0
# ###Payment
# A Payment Resource of type order; intent set as 'order'
payment = Payment({
    "intent":
    "order",
    "payer": {
        "payment_method": "paypal"
    },
    "redirect_urls": {
        "return_url": "http://return.url",
        "cancel_url": "http://cancel.url"
    },
    "transactions": [{
        "item_list": {
            "items": [{
                "name": "item",
                "sku": "item",
                "price": "1.00",
                "currency": "USD",
                "quantity": 1
            }]
        },
        "amount": {
            "currency": "USD",
            "total": "1.00"
        },
        "description": "This is the payment description."
    }]
})

# Create Payment and return status
payment = Payment({
    "intent": "sale",
    "redirect_urls": {
        "return_url": "http://www.return.com",
        "cancel_url": "http://www.cancel.com"
    },
    "payer": {
        "payment_method": "paypal",
        "payer_info": {
            "tax_id_type": "BR_CPF",
            "tax_id": "Fh618775690"
        }
    },
    "transactions": [
        {
            "amount": {
                "total": "34.07",
                "currency": "USD",
                "details": {
                    "subtotal": "30.00",
                    "tax": "0.07",
                    "shipping": "1.00",
                    "handling_fee": "1.00",
                    "shipping_discount": "1.00",
                    "insurance": "1.00"
                }
            },
            "description": "This is the payment transaction description.",
            "custom": "EBAY_EMS_90048630024435",
            "invoice_number": "48787589677",
            "payment_options": {
                "allowed_payment_method": "INSTANT_FUNDING_SOURCE"
            },
            "soft_descriptor": "ECHI5786786",
            "item_list": {
                "items": [
                    {
                        "name": "bowling",
                        "description": "Bowling Team Shirt",
                        "quantity": "5",
                        "price": "3",
                        "tax": "0.01",
                        "sku": "1",
                        "currency": "USD"
                    },
                    {
                        "name": "mesh",
                        "description": "80s Mesh Sleeveless Shirt",
                        "quantity": "1",
                        "price": "17",
                        "tax": "0.02",
                        "sku": "product34",
                        "currency": "USD"
                    },
                    {
                        "name": "discount",
                        "quantity": "1",
                        "price": "-2.00",
                        "sku": "product",
                        "currency": "USD"
                    }
                ],
                "shipping_address": {
                    "recipient_name": "Betsy Buyer",
                    "line1": "111 First Street",
                    "city": "Saratoga",
                    "country_code": "US",
                    "postal_code": "95070",
                    "state": "CA"
                }
            }
        }
    ]
})