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")
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
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)
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
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}
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) })
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
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)
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")
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.")
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)
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 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 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 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)
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)
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)
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
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)
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)
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
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")
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" )
}, "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 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 = str(link.href) print("Redirect for approval: %s" % (redirect_url)) else: print("Error while creating payment:") print(payment.error)
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()
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 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()
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))
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)
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)
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
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})
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.")
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})
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
"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."}]}) # 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": # Convert to str to avoid google appengine unicode issue # https://github.com/paypal/rest-api-sdk-python/pull/58 redirect_url = str(link.href) print("Redirect for approval: %s" % (redirect_url)) else: print("Error while creating payment:") print(payment.error)
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