class PayPalUI(QtGui.QDialog):
    def __init__(self):
        super(PayPalUI, self).__init__()
        self.ui = Ui_PaypalDialog()
        self.ui.setupUi(self)
        self.ui.happySlider.valueChanged.connect(self.ch_value)
        self.ui.happyButton.clicked.connect(self.create_payment)
        img = QtGui.QPixmap(get_file("paypal_logo.jpg"))
        self.ui.label_5.setPixmap(img)
        self.ui.label_5.setScaledContents(True)
        self.ui.label_5.setFixedSize(300, 50)
        self.ui.happyEdit.textChanged.connect(self.ch_text)
        self.ui.happyEdit.setText("3")
        self.ui.happyWebView.urlChanged.connect(self.ch_web_view)
        self.ui.happyWebView.loadProgress.connect(self.progress_webview)

    def progress_webview(self, progress):
        self.ui.progressBar.setValue(progress)

    def ch_value(self):
        self.ui.happyEdit.setText(str(self.ui.happySlider.value()))

    def ch_text(self):
        self.ui.happySlider.setValue(float(self.ui.happyEdit.text()))

    def ch_web_view(self):
        url = self.ui.happyWebView.url()
        url_string = url.toString()

        if "PayerID=" in url_string:
            for s in url_string.split("&"):
                if s.startswith("PayerID="):
                    id = s.strip("PayerID=")
                    if self.payment.execute({"payer_id": id}):
                        m_box_exec_success("Congratulations, you have made someone happy!")
                    else:
                        m_box_exec("Sorry, your transaction could not be completed.")

    def create_payment(self):
        price = self.ui.happyEdit.text()
        paypalrestsdk.configure(
            {
                "mode": "sandbox",  # sandbox or live
                "client_id": "ASS1fRDDkhHgMRXFYLJ9J02663eBb1ktC65nEQ6iVKbD4PyJPilbycGv6pxF",
                "client_secret": "EDo-XBCkEY72na40ngY_D6h8r6T2IhfBYtZoHEFV9Rf2sSYtsYDqmhexF3tO",
            }
        )
        self.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://roandigital.com/applications/synchronizerd/thanks",
                    "cancel_url": "http://roandigital.com/applications/synchronizerd/sorry",
                },
                # 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": "SynchroniZeRD", "sku": "1", "price": price, "currency": "USD", "quantity": 1}
                            ]
                        },
                        # Amount
                        # Let's you specify a payment amount.
                        "amount": {"total": price, "currency": "USD"},
                        "description": "This is the payment transaction for SynchroniZeRD.",
                    }
                ],
            }
        )
        if self.payment.create():
            m_box_exec_success("Your payment was created, redirecting to paypal for authorization.")
            for link in self.payment.links:
                if link.method == "REDIRECT":
                    red = link.href
                    self.ui.happyWebView.load(red)
                    self.setMinimumSize(1024, 600)

        else:
            print("error")
Exemple #2
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
Exemple #3
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)
Exemple #4
0
def create_raw_payment_for_invoice(invoice, options):
  return_url = options.get('return_url')
  cancel_url = options.get('cancel_url')

  description = 'Fruitex Invoice #' + str(invoice.id)
  payment = Payment({
    'intent': 'sale',
    'payer': {
      'payment_method': 'paypal',
    },
    'transactions': [{
      'amount': {
        'total': str(invoice.total),
        'currency': 'CAD',
        'details': {
          'subtotal': str(invoice.subtotal - invoice.discount),
          'tax': str(invoice.tax),
          'shipping': str(invoice.delivery),
        },
      },
      'description': description,
    }],
    'redirect_urls': {
      'return_url': return_url,
      'cancel_url': cancel_url,
    }
  })

  if not payment.create():
    return None

  return payment
Exemple #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}
Exemple #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)
        })
Exemple #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
Exemple #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)
Exemple #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")
Exemple #10
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.")
Exemple #11
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)
Exemple #12
0
def create_payment(ccid, amount, userid):
    payment = Payment({
      "intent": "sale",
      # 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": ccid }}]},

        # ###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": "snapcash",
            "sku": "item",
            "price": amount,
            "currency": "USD",
            "quantity": 1 }]},

        # ###Amount
        "amount": {
          "total": amount,
          "currency": "USD" },
        "description": "Snapcash transaction." }]})

    # Create Payment and return status
    if payment.create():
        logging.info("Payment[%s] created successfully"%(payment.id))
        # no reason to store this, just execute
        execute_payment(payment.id, userid)
    else:
        logging.error("Error while creating payment:")
        logging.error(payment.error)
Exemple #13
0
def ride_booking_execute_payment(payer_id, ride_booking):
    payment = Payment.find(ride_booking.paypal_payment_id)

    if ride_booking.status == RideBookingStatus.CREATED:
        if payment.execute({"payer_id": payer_id}):
            ride_booking.status = RideBookingStatus.PAYED
            ride_booking.save()
            ride = ride_booking.ride
            send_mail(
                'email_passenger_ride_booking_payed',
                [ride_booking.client.email], {
                    'ride': ride,
                    'ride_detail':
                    settings.RIDE_DETAIL_URL.format(ride_pk=ride.pk)
                })
            send_mail(
                'email_driver_ride_booking_payed',
                [ride_booking.ride.car.owner.email], {
                    'ride': ride,
                    'ride_detail':
                    settings.RIDE_DETAIL_URL.format(ride_pk=ride.pk)
                })
            if ride_booking.ride.car.owner.sms_notifications:
                send_sms(
                    'sms_driver_ride_booking_payed',
                    [ride_booking.ride.car.owner.normalized_phone], {
                        'ride':
                        ride,
                        'ride_detail':
                        settings.RIDE_DETAIL_URL.format(ride_pk=ride.pk)
                    })

            return True

    return False
Exemple #14
0
def payment_execute(request, template="shop/payment_confirmation.html"):
    order = None
    lookup = {}
    if request.GET.has_key('token'):
        paypal_api()
        token = request.GET['token']
        payer_id = request.GET['PayerID']
        order = get_object_or_404(Order, paypal_redirect_token=token)
        payment = Payment.find(order.transaction_id)
        payment.execute({"payer_id": payer_id})
    elif request.GET.has_key('transaction_id'):
        api = pagseguro_api()
        email = api.data['email']
        token = api.data['token']
        transaction = request.GET['transaction_id']
        url = api.config.TRANSACTION_URL % transaction
        resp = urllib2.urlopen("%s?email=%s&token=%s" %
                               (url, email, token)).read()
        lookup["id"] = ETree.fromstring(resp).findall("reference")[0].text
        print ETree.fromstring(resp).findall("reference")[0].text
        if not request.user.is_authenticated():
            lookup["key"] = request.session.session_key
        if not request.user.is_staff: lookup["user_id"] = request.user.id
        order = get_object_or_404(Order, **lookup)
        order.transaction_id = transaction
    elif request.GET.has_key('orderid'):
        return redirect("/store/bank?order_id=%s" % request.GET['orderid'])
    order.status = 2
    order.save()
    context = {"order": order}
    response = render(request, template, context)
    return response
Exemple #15
0
def finish_payment(bot, trigger):
  api = create_api(bot.config.donabot)
  payment_id = trigger.group(1)
  bot.msg(trigger.nick, "Hold on, checking your payment...")

  try:
    payment = Payment.find(payment_id, api=api)

  except ResourceNotFound:
    payment = None

  if payment is not None:
    payer_id = payment["payer"]["payer_info"]["payer_id"]
    result = payment.execute({"payer_id": payer_id})

    if result is True:
      amount = float(payment["transactions"][0]["amount"]["total"])
      currency = payment["transactions"][0]["amount"]["currency"]

      channel = bot.config.donabot.channel

      bot.write(("MODE", channel, "+v", trigger.nick))
      bot.msg(
        channel,
        "*** {} just donated {:.2f} {}!".format(trigger.nick, amount, currency)
      )
      bot.msg(trigger.nick, "Thank you for your support!")

    else:
      bot.msg(trigger.nick, "Unable to execute the payment. :-(")

  else:
    bot.msg(trigger.nick, "I'm sorry, but I can't find your payment. :-(")
    def post(self, request, *args, **kwargs):
        """
        Place an order.

        We fetch the txn details again and then proceed with oscar's standard
        payment details view for placing the order.
        """
        error_msg = _("A problem occurred communicating with PayPal "
                      "- please try again later")
        try:
            self.payer_id = request.POST['payer_id']
            self.token = request.POST['token']
            self.payment_id = request.POST['payment_id']
        except KeyError:
            # Probably suspicious manipulation if we get here
            print("IS THIS THE SPOT OF ERROR???")
            messages.error(self.request, error_msg)
            return HttpResponseRedirect(reverse('basket:summary'))

        try:
            self.payment = Payment.find(self.payment_id)
            #fetch_transaction_details(self.token)
        except PayPalError:
            # Unable to fetch txn details from PayPal - we have to bail out
            messages.error(self.request, error_msg)
            return HttpResponseRedirect(reverse('basket:summary'))

        # Reload frozen basket which is specified in the URL
        basket = self.load_frozen_basket(kwargs['basket_id'])
        if not basket:
            messages.error(self.request, error_msg)
            return HttpResponseRedirect(reverse('basket:summary'))

        submission = self.build_submission(basket=basket)
        return self.submit(**submission)
Exemple #17
0
def err_execute_and_complete_payment(paypal_payment_id, paypal_payer_id):
    """"Returns ERROR or None"""
    payment = get_og_payment(paypal_payment_id)
    if not payment:
        return jsonify({'message': 'aucun paiement'}), 404

    ticket = get_ticket_from_payment(payment)

    err = get_err_from_ticket(ticket)
    if err:
        return err

    prepare_payment_execution(payment, paypal_payer_id, ticket)

    # Validate payment is created
    paypal_payment = PaypalPayment.find(paypal_payment_id)
    if paypal_payment.state.lower() != 'created':
        app.logger.critical('Possible tentative de fraude: "%s"' %
                            str(paypal_payment))
        return jsonify({'message': ERR_CREATE_PAYPAL}), 402

    # Execute the payment
    if (not paypal_payment.execute({"payer_id": paypal_payer_id})
            or paypal_payment.state.lower() != 'approved'):
        # Could not execute or execute did not approve transaction
        app.logger.critical('Possible tentative de fraude: "%s"' %
                            str(paypal_payment))
        return jsonify({'message': ERR_INVALID_PAYPAL}), 402

    return complete_purchase(ticket)
Exemple #18
0
def err_execute_and_complete_payment(paypal_payment_id, paypal_payer_id):
    """"Returns ERROR or None"""
    # lock table tickets
    db_session.execute('LOCK TABLES tickets WRITE, payments WRITE;')

    payment = get_og_payment(paypal_payment_id)
    if not payment:
        return jsonify({'message': 'aucun paiement'}), 404

    ticket = get_ticket_from_payment(payment)

    err = get_err_from_ticket(ticket)
    if err:
        return err

    prepare_payment_execution(payment, paypal_payer_id, ticket)

    # Unlock tables (we do not want to lock while we query the paypal api)
    db_session.execute('UNLOCK TABLES;')

    # Validate payment is created
    paypal_payment = PaypalPayment.find(paypal_payment_id)
    if paypal_payment.state.lower() != 'created':
        # TODO log status
        print(paypal_payment)
        return jsonify({'message': ERR_CREATE_PAYPAL}), 402

    # Execute the payment
    if (not paypal_payment.execute({"payer_id": paypal_payer_id})
            or paypal_payment.state.lower() != 'approved'):
        # Could not execute or execute did not approve transaction
        return jsonify({'message': ERR_INVALID_PAYPAL}), 402

    return complete_purchase(ticket)
    def get(self, request):

        payment_id = request.GET.get('paymentId')
        payer_id = request.GET.get('PayerID')

        paypalrestsdk.configure({
            "mode": "sandbox",  # sandbox or live
            "client_id": "AWNIRUxctIc8ELjCrYLK8Zbv9L0EqL0aLplmLHpXPaPT_BVXINg66096i4jIO6i448h2fH-7sdaaiAtE",
            "client_secret": "ECnA0hUuNZShemfJq5sD-UAfDUuEbr1i5j6RQcHdZJZiDkrYMTo1S6kA6E_OEwA_zX8FMEz4-57TfOaN"})
        payment = Payment.find(payment_id)
        print('aaaaaaaaaaaaaa')
        import pdb; pdb.set_trace()
        if payment.execute({'payer_id':payer_id}):
            user_id = request.user
            payment_id = payment.id
            payer_id = payer_id
            status = payment['state']
            for pymt in payment['transactions']:
                total_amount = pymt['amount']['total']
                for amt in pymt['related_resources']:
                    subtotal = amt['sale']['amount']['details']['subtotal']
                for itm in pymt['item_list']['items']:
                    fees_type = itm['name']
                    import pdb; pdb.set_trace()
                    user = FeesTransactionDetails.objects.create(student=user_id,amount=subtotal,payment_response=json.dumps(payment.to_dict()),status=status,payment_id=payment_id,payer_id=payer_id)
                    if user:
                        return HttpResponseRedirect(reverse('payment_success'))
        else:
            return HttpResponseRedirect(reverse('payment_wrong'))
Exemple #20
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)
Exemple #21
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)
Exemple #22
0
def err_execute_and_complete_payment(paypal_payment_id, paypal_payer_id):
    """"Returns ERROR or None"""
    # lock table tickets
    db_session.execute('LOCK TABLES tickets WRITE, payments WRITE;')

    payment = get_og_payment(paypal_payment_id)
    if not payment:
        return jsonify({'message': 'aucun paiement'}), 404

    ticket = get_ticket_from_payment(payment)

    err = get_err_from_ticket(ticket)
    if err:
        return err

    prepare_payment_execution(payment, paypal_payer_id, ticket)

    # Unlock tables (we do not want to lock while we query the paypal api)
    db_session.execute('UNLOCK TABLES;')

    # Validate payment is created
    paypal_payment = PaypalPayment.find(paypal_payment_id)
    if paypal_payment.state.lower() != 'created':
        # TODO log status
        print(paypal_payment)
        return jsonify({'message': ERR_CREATE_PAYPAL}), 402

    # Execute the payment
    if (not paypal_payment.execute({"payer_id": paypal_payer_id}) or
            paypal_payment.state.lower() != 'approved'):
        # Could not execute or execute did not approve transaction
        return jsonify({'message': ERR_INVALID_PAYPAL}), 402

    return complete_purchase(ticket)
Exemple #23
0
def payment_execute(request, template="shop/payment_confirmation.html"):    
	order = None
	lookup = {}
	if request.GET.has_key('token'):
		paypal_api()
		token = request.GET['token']
		payer_id = request.GET['PayerID']
		order = get_object_or_404(Order, paypal_redirect_token=token)
		payment = Payment.find(order.transaction_id)
		payment.execute({ "payer_id": payer_id })
	elif request.GET.has_key('transaction_id'):
		api = pagseguro_api()
		email = api.data['email']
		token = api.data['token']
		transaction = request.GET['transaction_id']
		url = api.config.TRANSACTION_URL % transaction
		resp = urllib2.urlopen("%s?email=%s&token=%s" % (url,email,token)).read()
		lookup["id"] = ETree.fromstring(resp).findall("reference")[0].text
		print ETree.fromstring(resp).findall("reference")[0].text
		if not request.user.is_authenticated(): lookup["key"] = request.session.session_key
		if not request.user.is_staff: lookup["user_id"] = request.user.id
		order = get_object_or_404(Order, **lookup)
		order.transaction_id = transaction
	elif request.GET.has_key('orderid'):
		return redirect("/store/bank?order_id=%s" % request.GET['orderid'])
	order.status = 2
	order.save()
	context = { "order" : order }
	response = render(request, template, context)
	return response
Exemple #24
0
    def accept_paypal_payment(self, request, order_key=None):
        try:
            payer_id = request.GET['PayerID']
            payment_id = request.GET['paymentId']
            token = request.GET.get('token', None)
            order_key = order_key
        except KeyError:
            return HttpResponseBadRequest('Bad request.')
        else:
            paypal_payment = PaypalPaymentSDK.find(payment_id, api=shopiepaypal)

            if paypal_payment.execute({'payer_id': payer_id}):
                # this will success
                order = Order.objects.get(order_key=order_key)
                self._create_payment(
                    order=order, token=token, payment_id=payment_id,
                    payer_id=payer_id
                )
                # because we want to give acccess to download "thing" as soon
                # as customer pay the bill, and we just do that here. We will
                # go ahead and accept this order.
                order.accept()

                return HttpResponseRedirect(self.get_thank_you_page(request))
            else:
                raise PaymentProcessingError(
                    "There was an error contacting the payment processor"
                )
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)
 def get_payment(payment_id, paypal_mode, paypal_client_id,
                 paypal_client_secret):
     return Payment.find(resource_id=payment_id,
                         api=Api({
                             'mode': paypal_mode,
                             'client_id': paypal_client_id,
                             'client_secret': paypal_client_secret
                         }))
    def get(self, request, *args, **kwargs):
        paypalrestsdk.configure({
            "mode": "sandbox",
            "client_id": settings.PAYPAL_CLIENT_ID,
            "client_secret": settings.PAYPAL_CLIENT_SECRET
        })
        """
        Fetch details about the successful transaction from PayPal.  We use
        these details to show a preview of the order with a 'submit' button to
        place it.
        """
        try:
            print("GET: SuccessResponseView - views.py: can you see me?")
            self.payer_id = request.GET['PayerID']
            self.token = request.GET['token']
            self.payment_id = request.GET['paymentId']
        except KeyError:
            # Manipulation - redirect to basket page with warning message
            logger.warning("Missing GET params on success response page")
            messages.error(self.request,
                           _("Unable to determine PayPal transaction details"))
            return HttpResponseRedirect(reverse('basket:summary'))

        try:
            # self.txn = fetch_transaction_details(self.token)
            print("TOKEN:")
            print(self.token)
            print("END TOKEN")
            self.payment = Payment.find(self.payment_id)
            print("PAYMENT:")
            print(self.payment)
            print("END PAYMENT")
        except PayPalError as e:
            logger.warning(
                "Unable to fetch transaction details for token %s: %s",
                self.token, e)
            messages.error(
                self.request,
                _("A problem occurred communicating with PayPal - please try again later"
                  ))
            return HttpResponseRedirect(reverse('basket:summary'))

        # Reload frozen basket which is specified in the URL
        kwargs['basket'] = self.load_frozen_basket(kwargs['basket_id'])
        if not kwargs['basket']:
            logger.warning("Unable to load frozen basket with ID %s",
                           kwargs['basket_id'])
            messages.error(
                self.request,
                _("No basket was found that corresponds to your "
                  "PayPal transaction"))
            return HttpResponseRedirect(reverse('basket:summary'))

        logger.info(
            "Basket #%s - showing preview with payer ID %s and token %s",
            kwargs['basket'].id, self.payer_id, self.token)

        return super(SuccessResponseView, self).get(request, *args, **kwargs)
Exemple #28
0
    def process(self):
        configure_paypal()

        # Payment id obtained when creating the payment (following redirect)
        payment = Payment.find(self.cleaned_data['paymentId'])

        # Execute payment using payer_id obtained when creating the payment (following redirect)
        executed = payment.execute({"payer_id": self.cleaned_data['PayerID']})
        return executed, payment
Exemple #29
0
def execute_payment(paymentid, userid):
    # ID of the payment. This ID is provided when creating payment.
    payment = Payment.find(paymentid)

    # PayerID is required to approve the payment.
    if payment.execute({"payer_id": userid}):  
      logging.info("Payment[%s] execute successfully"%(paymentid))
    else:
      logging.error(payment.error)
Exemple #30
0
    def execute_payment(self, payment_id, payer_id='DUFRQ8GWYMJXC'):
        # ID of the payment. This ID is provided when creating payment.
        payment = Payment.find(payment_id)

        # PayerID is required to approve the payment.
        if payment.execute({"payer_id": payer_id}):  # return True or False
            print("Payment[%s] execute successfully" % (payment.id))
        else:
            print(payment.error)
Exemple #31
0
 def start_payment(self, request, amount):
     event = self.subscription.event
     self.transaction.amount = amount
     payment = Payment({
         'transactions': [{'amount': {'total': amount.to_eng_string(),
                                      'currency': 'BRL'},
                           'description': event.name}],
         'payer': {'payment_method': 'paypal'},
         'redirect_urls': {'return_url': self.my_pay_url(request),
                           'cancel_url': self.my_view_url(request)},
         'intent': 'sale'})
     if payment.create():
         self.transaction.remote_identifier = payment.id
         self.transaction.save()
         return prg_redirect(_find_href(payment.links, 'approval_url'))
     else:
         log.error('Data returned error. %s', repr(payment))
         raise ValueError('PayPal denied pay. %s' % repr(payment))
def payment_execute(payment_id, payer_id, token):
    logging.basicConfig(level=logging.INFO)
    payment = Payment.find(payment_id)
    if payment.execute({"payer_id": payer_id}):  # return True or False
        print("Paypal -- Payment[%s] execute successfully" % (payment.id))
        # for paypal payment return
        return {'payment_id': payment.id, 'payment_state': payment.state}
    else:
        print(payment.error)
Exemple #33
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)
Exemple #34
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)
Exemple #35
0
    def post(self, request, *args, **kwargs):
        transaction = self.get_object()
        payment = Payment({
                'intent': 'sale',
                'payer': {'payment_method': 'paypal'},

                'redirect_urls': {
                    'return_url': (settings.FULL_URL +
                                   reverse('transaction_approved',
                                           args=[transaction.pk])),
                    'cancel_url': (settings.FULL_URL +
                                   reverse('transaction_detail',
                                           args=[transaction.pk])), },

                'transactions':
                    [{
                        'item_list':
                        {
                            'items':
                                [{
                                    'name': transaction.description,
                                    'sku': transaction.description,
                                    'price': transaction.credit_with_fee(),
                                    'currency': 'DKK',
                                    'quantity': 1}]},
                        'amount': {
                            'total': transaction.credit_with_fee(),
                            'currency': 'DKK'},
                        'description': 'Overførsel til ToolControl'}]})

        if payment.create():
            transaction = self.get_object()
            transaction.paypal_id = payment.id
            transaction.save()

            for link in payment.links:
                if link.method == 'REDIRECT':
                    redirect_url = link.href
                    return HttpResponseRedirect(redirect_url)
        else:
            messages.error(request, 'Der skete en fejl under overførslen til' +
                           ' PayPal')
            return self.get(request, *args, **kwargs)
Exemple #36
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
Exemple #37
0
def get_payment_url(paypal_id):
    configure_paypal()
    payment = Payment.find(paypal_id)
    print(paypal_id)
    for link in payment.links:
        if link.rel == "approval_url":
            # Convert to str to avoid Google App Engine Unicode issue
            # https://github.com/paypal/rest-api-sdk-python/pull/58
            approval_url = str(link.href)
            return approval_url
    return None
Exemple #38
0
def execute_payment_process(payment_id, payer_id):
    # Payment ID obtained when creating the payment (following redirect)
    payment = Payment.find(payment_id)

    # Execute payment with the payer ID from the create payment call (following redirect)
    if payment.execute({"payer_id": payer_id}):
        print("Payment[%s] execute successfully" % (payment.id))
        return {"payment": payment.id}
    else:
        print(payment.error)
        return {"error": payment.error}
Exemple #39
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)
Exemple #40
0
def execute_payment(raw_payment, payer_id):
  raw_payment = json.loads(raw_payment)
  payment_id = raw_payment.get('id')
  if payment_id is None or payer_id is None:
    return None

  payment = Payment.find(payment_id)
  if not payment.execute({
    'payer_id': payer_id,
  }):
    return None
  return payment
Exemple #41
0
def paypal_payment_history(**kwargs):
    query_param = {
        'count': 100,
        'sort_by': 'create_time',
        'sort_order': 'desc',
        'start_time': kwargs['start_time'],
        'end_time': kwargs['end_time']
    }
    if kwargs.get('start_id'):
        query_param['start_id'] = kwargs['start_id']
    payment_history = Payment.all(query_param)
    return payment_history
Exemple #42
0
def execute(id):
    payment = Payment.find(request.args.get('paymentId'))

    order = Order.query.get(id)

    if not order or order.buyer != current_user:
        flash('Your order was not found, maybe it was already cancelled?')
        return redirect(url_for('shop'))

    if order.paid:
        flash('Your order was already paid, not charging you twice!')
        return redirect(url_for('shop'))

    if order.payment_id != payment.id:
        flash('This payment does not seem to match your order!')
        return redirect(url_for('shop'))

    if not payment.execute(dict(payer_id=request.args.get('PayerID'))):
        flash('An error occured while processing your order: {}'.format(
            payment.error))
        return redirect(url_for('shop'))

    order.paid = True
    order.item.quantity -= 1
    db.session.commit()

    message = Message(
        html=render_template(
            'order_receipt.html',
            order=order,
            item=order.item,
            user=order.buyer,
        ),
        subject='Receipt for your purchase - {}'.format(
            app.config['SITE_NAME']),
        mail_from=(
            app.config['SITE_NAME'],
            'noreply@%s' % app.config['SUPPORT_EMAIL'].split('@')[1],
        ),
    )
    user = order.buyer
    response = message.send(to=(
        '{} {}'.format(user.first_name, user.last_name),
        user.email,
    ))

    flash('Your order was processed successfully{}. Thank you!'.format(
        '' if response.status_code == 250 else (
            ', but your purchase receipt could not be sent. '
            'Contact us at {} in order to get your receipt.'
        ).format(app.config['SUPPORT_EMAIL'])))
    return redirect(url_for('shop'))
def payment_process(payment_method, host_root, transaction_object, card_info={}):

    auth_payment()
    payment = Payment(get_payment_json(payment_method, host_root, transaction_object, card_info))
    is_approve = payment.create()

    payment_dict = {'payment_id': payment.id, 'payment_state': payment.state, 'redirect_url': None}

    if is_approve:
        print("Payment[%s] created successfully" % payment.id)
        for link in payment.links:
            if link.method == "REDIRECT":
                redirect_url = str(link.href)
                print("Redirect for approval: %s" % redirect_url)
                payment_dict['redirect_url'] = redirect_url
                return payment_dict
    else:
        print('payment cannot be approval, please check your payment info ...')
        return None
    print("Direct credit -- Payment[%s] execute successfully" % (payment.id))
    # for direct_credit return
    return payment_dict
Exemple #44
0
def execute_payment(payment_id, payer_id):
    """
    paypal执行付款
    payment_id: 账单ID
    payer_id: 客户ID
    """
    payment = Payment.find(payment_id)
    if payment.execute({"payer_id": payer_id}):
        log.info('[payment] paypal payment %s execute success', payment.id)
        return payment
    else:
        log.error('[payment] paypal payment execute fail, %s', payment.error)
        return None
Exemple #45
0
 def class_view(cls, request: HttpRequest):
     payment_id = request.GET.get('paymentId')
     payer_id = request.GET.get('PayerID')
     if not payment_id:
         raise SuspiciousOperation
     payment = PaymentMethod(payment_id)
     paypal = Payment.find(payment_id)
     if not paypal.execute({'payer_id': payer_id}):
         raise ValueError('PayPal did not complete pmt %s' % payment_id)
     payment.callback_view(paypal)
     # This is actually the user here, not a callback bot! So we must return to base.
     # TODO: What if the user never returns home after paying? Should we poll pending transactions?
     return prg_redirect(payment.my_view_url(request))
    def create_payment(self):
        price = self.ui.happyEdit.text()
        paypalrestsdk.configure(
            {
                "mode": "sandbox",  # sandbox or live
                "client_id": "ASS1fRDDkhHgMRXFYLJ9J02663eBb1ktC65nEQ6iVKbD4PyJPilbycGv6pxF",
                "client_secret": "EDo-XBCkEY72na40ngY_D6h8r6T2IhfBYtZoHEFV9Rf2sSYtsYDqmhexF3tO",
            }
        )
        self.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://roandigital.com/applications/synchronizerd/thanks",
                    "cancel_url": "http://roandigital.com/applications/synchronizerd/sorry",
                },
                # 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": "SynchroniZeRD", "sku": "1", "price": price, "currency": "USD", "quantity": 1}
                            ]
                        },
                        # Amount
                        # Let's you specify a payment amount.
                        "amount": {"total": price, "currency": "USD"},
                        "description": "This is the payment transaction for SynchroniZeRD.",
                    }
                ],
            }
        )
        if self.payment.create():
            m_box_exec_success("Your payment was created, redirecting to paypal for authorization.")
            for link in self.payment.links:
                if link.method == "REDIRECT":
                    red = link.href
                    self.ui.happyWebView.load(red)
                    self.setMinimumSize(1024, 600)

        else:
            print("error")
Exemple #47
0
 def payment_execute(self, request, template="shop/payment_confirmation.html"):    
     paypal_api()
     token = request.GET['token']
     payer_id = request.GET['PayerID']
     logger.debug("feedly.views.payment_execute(token=%s,payer_id=%s)" % (token,payer_id))
     order = get_object_or_404(Order, paypal_redirect_token=token)
     payment = Payment.find(order.transaction_id)
     payment.execute({ "payer_id": payer_id })
     # Pago, falta enviar
     order.status = 3
     order.save()
     context = { "order" : order }
     response = render(request, template, context)
     return response
Exemple #48
0
    def get_redirect(self, order, request):
        absolute_uri = request.build_absolute_uri
        items = self._get_order_items(order)
        amount_total = sum([Decimal(it['price']) for it in items])

        payment_arguments = {
            'intent': 'sale',
            'payer': {
                'payment_method': 'paypal'
            },
            'redirect_urls': {
                'return_url': absolute_uri(reverse('shopie:paypal_payment',
                    kwargs={
                        'order_key': order.order_key
                    })),
                'cancel_url': absolute_uri(reverse('shopie:checkout'))
            },
            'transactions': [{
                'item_list': {
                    'items': items
                },
                'amount': {
                    'total': moneyfmt(amount_total),
                    'currency': 'USD'
                },
                'description': 'Make sure to include'
            }]
        }
        payment = PaypalPaymentSDK(payment_arguments, api=shopiepaypal)
        if payment.create():
            for link in payment.links:
                if link.method == 'REDIRECT':
                    return str(link.href)
        else:
            raise PaymentProcessingError(
                "There was an error contacting the payment processor"
            )
# GetPayment Sample
# This sample code demonstrates how you can retrieve
# the details of a payment resource.
# API used: /v1/payments/payment/{payment-id}
from paypalrestsdk import Payment, ResourceNotFound
import logging
logging.basicConfig(level=logging.INFO)

try:
    # Retrieve the payment object by calling the
    # `find` method
    # on the Payment class by passing Payment ID
    payment = Payment.find("PAY-0XL713371A312273YKE2GCNI")
    print("Got Payment Details for Payment[%s]" % (payment.id))

except ResourceNotFound as error:
    # It will through ResourceNotFound exception if the payment not found
    print("Payment Not Found")
Exemple #50
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()
Exemple #51
0
# #GetPaymentList Sample
# This sample code demonstrate how you can
# retrieve a list of all Payment resources
# you've created using the Payments API.
# Note various query parameters that you can
# use to filter, and paginate through the
# payments list.
# API used: GET /v1/payments/payments
from paypalrestsdk import Payment
import logging
logging.basicConfig(level=logging.INFO)

# ###Retrieve
# Retrieve the PaymentHistory  by calling the
# `all` method
# on the Payment class
# Refer the API documentation
# for valid values for keys
# Supported paramters are :count, :next_id
payment_history = Payment.all({"count": 2})

# List Payments
print("List Payment:")
for payment in payment_history.payments:
  print("  -> Payment[%s]"%(payment.id))
from paypalrestsdk import Payment
import logging

logging.basicConfig(level=logging.INFO)

payment = Payment.find("<PAYMENT_ID>")

# e.g. Update shipping amount in the transactions array after payment creation
# and calling payment execute
# https://developer.paypal.com/webapps/developer/docs/api/#transaction-object
execute_payment_json = {
    "payer_id": "HCXTE7DLHVTDN",
    "transactions": [{
        "amount": {
            "total": "35.07",
            "currency": "USD",
            "details": {
                "subtotal": "30.00",
                "tax": "0.07",
                "shipping": "2.00",
                "handling_fee": "1.00",
                "shipping_discount": "1.00",
                "insurance": "1.00"
            }
        }
    }]
};

if payment.execute(execute_payment_json):  # return True or False
  print("Payment[%s] execute successfully"%(payment.id))
else:
Exemple #53
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})
Exemple #54
0
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."}]})
def index():
    # #Create Payment Using PayPal Sample
    # This sample code demonstrates how you can process a
    # PayPal Account based Payment.
    # API used: /v1/payments/payment
   
    from paypalrestsdk import Payment
    from paypalrestsdk import set_config
    import logging
    
    logging.basicConfig(level=logging.INFO)
    
    set_config(mode=settings.paypal_mode, # sandbox or live
               client_id=settings.paypal_client_id,
               client_secret=settings.paypal_client_secret)
    
    # ###Payment
    # A Payment Resource; create one using
    # the above types and intent as 'sale'
    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": "Test item",
            "sku": "001",
            "price": "5.00",
            "currency": "USD",
            "quantity": 2 },
            {
            "name": "Test item 2",
            "sku": "002",
            "price": "125.70",
            "currency": "USD",
            "quantity": 3}]},
    
        # ###Amount
        # Let's you specify a payment amount.
        "amount":  {
          "total":  "387.10",
          "currency":  "USD" },
        "description":  "This is the payment transaction description." } ] } )
    
    # Create Payment and return status
    if payment.create():
      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 = link.href
          print("Redirect for approval: %s"%(redirect_url))
    else:
      print("Error while creating payment:")
      print(payment.error)
 def getPayment(self):
     return Payment.find(self.paymentId)
# Execute an approved PayPal payment
# Use this call to execute (complete) a PayPal payment that has been approved by the payer.
# You can optionally update transaction information by passing in one or more transactions.
# API used: /v1/payments/payment
from paypalrestsdk import Payment
import logging
logging.basicConfig(level=logging.INFO)

# ID of the payment. This ID is provided when creating payment.
payment = Payment.find("PAY-28103131SP722473WKFD7VGQ")

# PayerID is required to approve the payment.
if payment.execute({"payer_id": "DUFRQ8GWYMJXC"}):  # return True or False
    print("Payment[%s] execute successfully" % (payment.id))
else:
    print(payment.error)
Exemple #58
0
def payment_process(payment_method, host_root, transaction_object, card_info={}):
    # transaction_object = {}
    # card_info = {}
    # if payment_method == PAYPAL:
    #     transaction_object = {
    #         "amount":
    #             {
    #                 "total": "2520.00",
    #                 "currency": "USD",
    #                 "details": {
    #                     "subtotal": "2500.00",
    #                     "tax": "10.00",
    #                     "shipping": "10.00"
    #                 },
    #             },
    #         "description": "creating a payment"
    #         }
    # elif payment_method == DIRECT_CREDIT:
    #     transaction_object = {
    #         "amount":
    #             {
    #                 "total": "25.55",
    #                 "currency": "USD",
    #                 "details": {
    #                     "subtotal": "25.00",
    #                     "tax": "0.05",
    #                     "shipping": "0.50"
    #                 }
    #             },
    #         "description": "This is the payment transaction description."
    #         }
    #     card_info = {
    #         "credit_card": {
    #             "type": "visa",
    #             "number": "4417119669820331",  # "4032035160291142",
    #             "expire_month": "03",
    #             "expire_year": "2020",
    #             "cvv2": "874",
    #             "first_name": "Joe",
    #             "last_name": "Shopper",
    #             "billing_address": {
    #                 "line1": "52 N Main ST",
    #                 "city": "Johnstown",
    #                 "state": "OH",
    #                 "postal_code": "43210",
    #                 "country_code": "US"
    #             }
    #         }
    #     }

    print(transaction_object)
    print(card_info)

    auth_payment()
    payment = Payment(get_payment_json(payment_method, host_root, transaction_object, card_info))
    is_approve = payment.create()

    print(is_approve)

    payment_dict = {'payment_id': payment.id, 'payment_state': payment.state, 'redirect_url': None}

    if is_approve:
        print("Payment[%s] created successfully" % payment.id)
        for link in payment.links:
            if link.method == "REDIRECT":
                redirect_url = str(link.href)
                print("Redirect for approval: %s" % redirect_url)
                payment_dict['redirect_url'] = redirect_url
                return payment_dict
    else:
        print('payment cannot be approval, please check your payment info ...')
        return None
    print("Direct credit -- Payment[%s] execute successfully" % (payment.id))
    # for direct_credit return
    return payment_dict