def payment_notification(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: # Payment successful. order = get_object_or_404(Order, id=ipn_obj.invoice) # Mark order as paid. order.paid = True order.save() # Create email containing invoice. subject = 'Mój sklep - rachunek nr {}'.format(order.id) message = 'W załączniku przesyłamy rachunek dla ostatniego zakupu.' email = EmailMessage(subject, message, '*****@*****.**', [order.email]) # Generate PDF file. html = render_to_string('orders/order/pdf.html', {'order': order}) out = BytesIO() css = [weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')] weasyprint.HTML(string=html).write_pdf( out, stylesheets=[ css, "https://fonts.googleapis.com/css?family=Raleway:400,600&display=swap" ]) # Attach PDF file. email.attach('order_{}.pdf'.format(order.id), out.getvalue(), 'application/pdf') # Sending an email. email.send() valid_ipn_received.connect(payment_notification)
def test_verify_action(self): PayPalIPN._postback = lambda self: b"Internal Server Error" self.paypal_post(IPN_POST_PARAMS) ipn_obj = PayPalIPN.objects.get() self.assertEqual(ipn_obj.flag, True) url = reverse('admin:ipn_paypalipn_changelist') self.assertTrue( self.client.login(username='******', password='******')) response = self.client.get(url) self.assertContains(response, IPN_POST_PARAMS['txn_id']) self.got_signal = False self.signal_obj = None def handle_signal(sender, **kwargs): self.got_signal = True self.signal_obj = sender valid_ipn_received.connect(handle_signal) PayPalIPN._postback = lambda self: b"VERIFIED" response_2 = self.client.post(url, { 'action': 'reverify_flagged', '_selected_action': [str(ipn_obj.id)] }) response_3 = self.client.get(response_2['Location']) self.assertContains(response_3, "1 IPN object(s) re-verified") ipn_obj = PayPalIPN.objects.get() self.assertEqual(ipn_obj.flag, False) self.assertTrue(self.got_signal)
def PaymentNotification(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: order = get_object_or_404(Order, id=ipn_obj.invoice) order.paid = True order.save() # Отправка Email subject = 'Онлайн-магазин - заказ: {}'.format(order.id) message = 'К email сообщению прикреплен PDF файл с информацией о\ вашем заказе.' email = EmailMessage(subject, message, '*****@*****.**', [order.email]) # Генерация PDF html = render_to_string('orders/order/pdf.html', {'order': order}) out = BytesIO() stylesheets = [ weasyprint.CSS(settings.STATIC_ROOT + 'css/bootstrap.min.css') ] weasyprint.HTML(string=html).write_pdf(out, stylesheets=stylesheets) # Прикрепляем pdf email.attach('order_{}.pdf'.format(order.id), out.getvalue(), 'application/pdf') email.send() valid_ipn_received.connect(PaymentNotification)
def donation_completedview(request): args = {'post': request.POST, 'get': request.GET} data = donatemoney.objects.latest() data.status = '1' valid_ipn_received.connect(show_me_the_money) data.save() return render(request, 'donation/donation_done.html', args)
def payment_notification(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: # payment was succesful order = get_object_or_404(Order, id=ipn_odj.invoice) # mark the order as paid order.paid = True order.save() # create invoice e-mail subject = 'My Shop - Invoice no. {}'.format(order.id) message = 'Please, find attached the invoice for your recent purchase.' email = EmailMessage(subject, message, '*****@*****.**', [order.email]) # generate PDF html = render_to_string('orders/order/pdf.html', {'order': order}) out = BytesIO() stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')] weasyprint.HTML(string=html).write_pdf(out, stylesheets=stylesheets) # attach PDF file email.attach('order_{}.pdf'.format(order.id), out.getvalue(), 'application/pdf') # send e-mail email.send() #Remember to set up your SMTP settings in the settings.py ile of the project to send e-mails. #You can refer to Chapter 2, Enhancing Your Blog with Advanced Features #to see a working example for an SMTP coniguration. valid_ipn_received.connect(payment_notification)
def test_verify_action(self): PayPalIPN._postback = lambda self: b"Internal Server Error" self.paypal_post(IPN_POST_PARAMS) ipn_obj = PayPalIPN.objects.get() self.assertEqual(ipn_obj.flag, True) url = reverse('admin:ipn_paypalipn_changelist') self.assertTrue(self.client.login(username='******', password='******')) response = self.client.get(url) self.assertContains(response, IPN_POST_PARAMS['txn_id']) self.got_signal = False self.signal_obj = None def handle_signal(sender, **kwargs): self.got_signal = True self.signal_obj = sender valid_ipn_received.connect(handle_signal) PayPalIPN._postback = lambda self: b"VERIFIED" response_2 = self.client.post(url, {'action': 'reverify_flagged', '_selected_action': [str(ipn_obj.id)]}) response_3 = self.client.get(response_2['Location']) self.assertContains(response_3, "1 IPN object(s) re-verified") ipn_obj = PayPalIPN.objects.get() self.assertEqual(ipn_obj.flag, False) self.assertTrue(self.got_signal)
def payment_notification(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: order = get_object_or_404(Order, id=ipn_obj.invoice) # mark the order as paid order.paid = True order.save() valid_ipn_received.connect(payment_notification)
def payment_notification(sender, **kwargs): inp_obj = sender if inp_obj.payment_status == ST_PP_COMPLETED: order_id = inp_obj.invoice.split('-')[-1] order = models.Order.objects.get(id=order_id) order.paid = True order.save() valid_ipn_received.connect(payment_notification())
def payment_notification(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: #el pago fue correctamente procesado order = get_object_or_404(Orden, id=ipn_obj.invoice) #marca la orden como pagada order.paid = True order.save() valid_ipn_received.connect(payment_notification)
def payment_notification(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: #el pago fue correctamente procesado order = get_object_or_404(Orden, id=ipn_obj.invoice) #marca la orden como pagada order.paid = True order.save() subject = "My shop - Invoice no. {}".format(order.id) message = 'Please, find attached the invoice for you recent purchase.' email = EmailMessage(subject, message, '*****@*****.**', [order.email]) email.send() valid_ipn_received.connect(payment_notification)
def show_me_the_money(sender, **kwargs): print("show me the money") ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: # WARNING ! # Check that the receiver email is the same we previously # set on the `business` field. (The user could tamper with # that fields on the payment form before it goes to PayPal) if ipn_obj.receiver_email != "*****@*****.**": # Not a valid payment print("not a valid payment") return # ALSO: for the same reason, you need to check the amount # received, `custom` etc. are all what you expect or what # is allowed. # Undertake some action depending upon `ipn_obj`. lnumber = "L2278619" if ipn_obj.custom == "premium_plan": print("premium plan") else: price = 3.0 print("not premium plan") if ipn_obj.mc_gross == price and ipn_obj.mc_currency == 'USD': Lustudent.paid = 1 Lustudent.save() SQL_UPDATE = "UPDATE `lustudent` SET `Paid` = `1` WHERE `lnumber` = " + str( lnumber) + ";" print(SQL_UPDATE) with closing(connection.cursor()) as cursor: cursor = connection.cursor() cursor.execute(SQL_UPDATE) connection.close() print("okay!") else: print("error in payment status") try: ipn_obj.verify(ipn_obj) except: import sys, traceback traceback.print_exc(file=sys.stdout) valid_ipn_received.connect(show_me_the_money)
def show_me_the_money(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: # WARNING ! # Check that the receiver email is the same we previously # set on the business field request. (The user could tamper # with those fields on payment form before send it to PayPal) if ipn_obj.receiver_email != "*****@*****.**": # Not a valid payment return redirect('articles:index') # ALSO: for the same reason, you need to check the amount # received etc. are all what you expect. # Undertake some action depending upon `ipn_obj`. if ipn_obj.custom == "Upgrade all users!": #Users.objects.update(paid=True) eso = User.objects.get.all() return redirect('articles:index') else: #... valid_ipn_received.connect(show_me_the_money)
""" Signals.py: """ from paypal.standard.ipn.signals import valid_ipn_received from paypal.standard.models import ST_PP_COMPLETED def item_purchased(sender): """ item_purchased(sender): """ ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: # WARNING ! # Check that the receiver email is the same we previously # set on the `business` field. (The user could tamper with # that fields on the payment form before it goes to PayPal) if ipn_obj.receiver_email != "*****@*****.**": # Not a valid payment return else: return valid_ipn_received.connect(item_purchased)
return redirect('/s/#/patient/so') return super(AboutSoUnregisteredPage, self).dispatch(request, *args, **kwargs) class Logout(TemplateViewSPref): template_name = "static_pages/index.html" def dispatch(self, request, *args, **kwargs): try: logout(request) except: pass return redirect("/") """ class RenderPaypalButtonPremiumPromoCode(APIView): def get(self, request, *args, **kwargs): paypal_dict = { "business": settings.PAYPAL_RECEIVER_EMAIL, # amount - цена "amount": "#PRICE#", # item_name - название услуги (напр. кофейная чашка). "item_name": "Promo code", # invoice - уникальный номер счета фактуры. "invoice": "#INVOICE#", # notify_url - url по которому приходят все события (об оплате) "notify_url": settings.THIS_SERVER + reverse('paypal-ipn'),
def txn_handler(sender, **kwargs): if sender.payment_status in [ ST_PP_ACTIVE, ST_PP_CANCELED_REVERSAL, ST_PP_COMPLETED, ST_PP_CREATED, ST_PP_PAID, ST_PP_PENDING, ST_PP_PROCESSED, ST_PP_REFUNDED, ST_PP_REWARDED, ST_PP_VOIDED ]: successful_txn_handler(sender, **kwargs) else: unsuccessful_txn_handler(sender, **kwargs) def unsuccessful_txn_handler(sender, **kwargs): transaction_was_unsuccessful.send(sender=sender.__class__, type="purchase", response=sender) def successful_txn_handler(sender, **kwargs): transaction_was_successful.send(sender=sender.__class__, type="purchase", response=sender) valid_ipn_received.connect(txn_handler)
from registration.models import RegistrationProfile from registration.views import ActivationView def payment_signal(sender, **kwargs): ipn_object = sender #if ipn_object.payment_status == ST_PP_COMPLETED: if payment_status == 'Completed': print "payment_status == ST_PP_COMPLETED" """ Here use django-registration to authenticate the User """ activate_user(activation_key) activation_key = ACTIVATED #ActivationView.activate() else: print str(ipn_object.payment_status) print "error" valid_ipn_received.connect(payment_signal) payment_was_flagged.connect(payment_signal) print "SIGNALS MODULE IMPORTED"
def reload_admins(): servers = Server.objects.all() for server in servers: with RCON((server.host, server.port), settings.RCON_PASSWORD) as rcon: print(rcon("sm_reloadadmins")) def add_premium(sender, **kwargs): """ When PayPal IPN completes, add user to the PREMIUM group and set an expiry time """ ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: try: social_user = UserSocialAuth.objects.get(uid=ipn_obj.custom) except ObjectDoesNotExist: # Todo: do something here as something has gone wrong return group = Group.objects.get(name=settings.PREMIUM_GROUP_NAME) social_user.user.groups.add(group) for x in settings.DONATION_AMOUNTS: if x[0] == ipn_obj.mc_gross: end_time = timezone.now() + timedelta(days=x[1]) PremiumDonation(user=social_user.user, end_time=end_time).save() valid_ipn_received.connect(add_premium)
reverse('checkout:order_list')) paypal_dict['notify_url'] = self.request.build_absolute_uri( reverse('paypal-ipn')) context['form'] = PayPalPaymentsForm(initial=paypal_dict) return context def paypal_notification(sender, **kwargs): # A verificação aqui foi somente para o status: completed. # Pode ser feito tb para outros tipos de status. ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED and \ ipn_obj.receiver_email == settings.PAYPAL_EMAIL: try: order = Order.objects.get(pk=ipn_obj.invoice) order.complete() except order.DoesNotExist: pass valid_ipn_received.connect( paypal_notification) # funciona como um signals do django. create_cartitem = CreateCartItemView.as_view() cart_item = CartItemView.as_view() checkout = CheckoutView.as_view() order_list = OrderListView.as_view() order_detail = OrderDetailView.as_view() pagseguro_view = PagSeguroView.as_view() paypal_view = PayPalView.as_view()
try: with transaction.atomic(): charge_log, created = ChargeLog.objects.get_or_create(wallet=wallet, transaction_id=ipn_obj.txn_id, gross=Decimal(ipn_obj.payment_gross)) if created: wallet.gross = F('gross') + Decimal(ipn_obj.payment_gross) wallet.save() # 여러번 실험해서 더플리케이트 실험 하면 됨. except Exception as e: print(e) return else: pass valid_ipn_received.connect(ipn_signal) ''' @receiver(post_save, sender=TestModel_2) def create_update_log(sender, instance, created, **kwargs): if created: TestModelLog_2.objects.create(description=instance.description, status=20) else: TestModelLog_2.objects.create(description=instance.description, status=33) @receiver(post_delete, sender=TestModel_2) def delete_log(sender, instance, **kwargs): TestModelLog_2.objects.create(description=instance.description, status=2038) # 값 포함해서 보내기 ------ def save(self, commit=True):
if request.method == 'POST' and request.is_ajax(): return JsonResponse({'result': success}) else: if success: messages.add_message(request, messages.SUCCESS, 'Die Bezahlung wurde abgebrochen.') return HttpResponseRedirect(reverse('app_book:book-detail', kwargs={'id': payment.book_id})) def paypal_ipn(sender, **kwargs): ipn_obj = sender payment = Payment.objects.filter(invoice=ipn_obj.invoice).first() if payment is not None: update_payment_from_paypal_ipn(payment, ipn_obj) valid_ipn_received.connect(paypal_ipn) invalid_ipn_received.connect(paypal_ipn) @login_required def rate_seller(request, id): backpath = request.META.get('HTTP_REFERER') if backpath is None : backpath = reverse("app:startPage") rating = SellerRating.objects.filter(payment_id=id).first() if rating is not None: messages.add_message(request,messages.ERROR,"Sie können ein Verkäufer pro Einkauf nur einmal bewerten.") return HttpResponseRedirect(backpath) payment = get_object_or_404(Payment, id=id) if payment is None: messages.add_message(request,messages.ERROR,"Sie können diesen Nutzer nicht bewerten.")
print u'PayPal IPN Incoming: {} - {}'.format(ipn_obj.invoice, ipn_obj.payment_status) if ipn_obj.payment_status == ST_PP_COMPLETED: try: registration = Registrations.objects.get(paypal_invoice_id=ipn_obj.invoice) if registration.league.is_waitlist(registration.user): registration.waitlist = True registration.payment_complete = True registration.paypal_complete = True registration.registered = ipn_obj.payment_date registration.save() if registration.coupon: registration.coupon.process(registration.user) print u'PayPal IPN Complete: {} - {} - {} - {}'.format(ipn_obj.invoice, registration.id, ipn_obj.mc_gross, registration.paypal_price) except Registrations.DoesNotExist: print u'PayPal IPN Error: {} - Registration does not exist'.format(ipn_obj.invoice) except Exception, ex: print u'PayPal IPN Error: {} - Unknown error'.format(ipn_obj.invoice) print u'{}'.format(ex) else: print u'PayPal IPN Not Complete: {} - {}'.format(ipn_obj.invoice, ipn_obj.payment_status) valid_ipn_received.connect(paypal_callback)
order = None if ipn_obj.payment_status == ST_PP_COMPLETED: logger.info("PayPal: payment flaged") order = mark_payment(ipn_obj, PAYMENT_FLAGGED) else: logger.info("PayPal: payment failed") order = mark_payment(ipn_obj, PAYMENT_FAILED) if order is not None: transaction, created = PayPalOrderTransaction.objects.get_or_create(order=order) transaction.ipn.add(ipn_obj) transaction.save() else: logger.warning("PayPal: unsuccessful ipn payment, no order found for uuid %s" % ipn_obj.custom) else: logger.warning("PayPal: unsuccessful ipn payment signal with no ipn object") def successful_pdt(sender, **kwargs): logger.info("PayPal: successful pdt payment") pdt_obj = sender mark_payment(pdt_obj, True) def unsuccesful_pdt(sender, **kwargs): logger.info("PayPal: unsuccessful pdt payment") pdt_obj = sender mark_payment(pdt_obj, False) valid_ipn_received.connect(successful_payment, dispatch_uid="Order.ipn_successful") invalid_ipn_received.connect(unsuccessful_payment, dispatch_uid="Order.ipn_unsuccessful")
} return 'square-commerce-v1://payment/create?data=' + urlencode(json.dumps(initial, cls=DjangoJSONEncoder)) def paypal_forms(self): Forms = namedtuple('Forms', 'one_click,sub_click,zero_click,square_click') one_click_initial, sub_click_initial = self.paypal_form_initial() if ( self.should_invoice and self.invoice.total == 0 ): zero_click_initial = { 'ticket_id': self.id, } else: zero_click_initial = None from lindy.ticket.forms import FinalizeZeroDollarCheckout return Forms( one_click=PayPalPaymentsForm(initial=one_click_initial) if one_click_initial else None, sub_click=PayPalPaymentsForm(initial=sub_click_initial) if sub_click_initial else None, zero_click=FinalizeZeroDollarCheckout(initial=zero_click_initial) if zero_click_initial else None, square_click=self.square_form_initial(), ) valid_ipn_received.connect(Ticket.show_me_the_money) invalid_ipn_received.connect(Ticket.ipn_error) del PayPalIPN # do not export this model so it is not autodiscovered in the wrong place
pk = kwargs.get('pk') user = models.MainUser.objects.get(pk=pk) return Response({'new': len(user.paypal_transaction_id_new)}) def on_paypal_ipn_receive(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: verified = helpers.paypal_ipn.verify_ipn(ipn_obj) if not verified[0]: return info = verified[1] user = models.MainUser.objects.get(pk=info['user_pk']) if info['transaction_id'] not in user.paypal_transaction_id_new and info['transaction_id'] not in user.paypal_transaction_id_old: user.paypal_transaction_id_new.append(info['transaction_id']) user.save() cases = so_models.SODiagnosis.objects(owner=info['user_pk'], is_closed=False) helpers.tornado_ws.sendSOMsg(info['user_pk'], { 'open_so': { 'so_pk': str(cases[0].pk), 'user_pk': info['user_pk'] } }) valid_ipn_received.connect(on_paypal_ipn_receive)
for order_ticket in order_tickets: qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=6, border=0) qr.add_data(order.order_number) qr.make(fit=True) img = qr.make_image() qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=6, border=0) qr.add_data(order.order_number) qr.make(fit=True) img = qr.make_image() img.save("static/qr_codes/qr_" + order_ticket.ticket_number + ".png") debug = DebugModel(string="Hello World") debug.save() valid_ipn_received.connect(paypal_response)
Usuario, null=False, blank=False, related_name='comprobante_user_set', on_delete=models.PROTECT ) evaluacion = models.ForeignKey( Evaluacion, null=True, blank=False, related_name='evaluacion_pago_set', on_delete=models.PROTECT ) def __str__(self): return 'Comprobante con metodo de pago: {0}'.format(self.get_tipo_pago_display()) class Codigo(models.Model): codigo = models.CharField(max_length=200, null=True, blank=False) activo = models.BooleanField(null=False, blank=False, default=True) def __str__(self): return 'Codigo: {0}'.format(self.codigo) def guardar_pago_evaluacion(sender, **kwargs): print(sender) ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: if ipn_obj.receiver_email != settings.PAYPAL_BUSINESS: return else: return valid_ipn_received.connect(guardar_pago_evaluacion) invalid_ipn_received.connect(guardar_pago_evaluacion)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.conf import settings from django.utils import timezone from signals import subscription_created, subscription_was_cancelled from paypal.standard.ipn.signals import valid_ipn_received # Create your models here. class Magazine(models.Model): name = models.CharField(max_length=254, default='') description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) def __unicode__(self): return self.name class Purchase(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='purchases') magazine = models.ForeignKey(Magazine) subscription_end = models.DateTimeField(default=timezone.now) valid_ipn_received.connect(subscription_created) valid_ipn_received.connect(subscription_was_cancelled)
''' Paypal IPN listener. It gets triggered after every each payment. ''' msg = sender.POST.get('payer_email') print(msg) # CGI preamble print('content-type: text/plain') sys.stdin = sender return HttpResponse(msg) valid_ipn_received.connect(ipn) def send_email(request): ''' Prototype of call to send_email() function ''' email = '*****@*****.**' send_mail('heyy', 'message', email, [email], fail_silently=False) def error_404(request, *args, **kwargs): ''' A 404 error handling view ''' data = {}
user = custom_dict['user'] diamonds = custom_dict['diamonds'] money = ipn_obj.mc_gross #- ipn_obj.mc_fee user_m = AM.User.objects.get(username=user) profile_m = MM.Profile_Reporter.GetProfile_Mdl(user_m) profile_m.Diamonds += diamonds profile_m.LifetimeDiamonds += diamonds profile_m.save() else: excp_lg.warning("not STPP status") excp_lg.warning(ipn_obj.__dict__) valid_ipn_received.connect(PaypalHandler) # add the logged user's data to all template contexts # requires an entry in settings.template_context_processors def context_profile(request): if not request.user.is_anonymous(): season = FM.TimeMachine.GetTodaysBracket()['season'] profile_dt = MM.Profile_Reporter.GetUserData(request.user) puRoster_dx = PU.Reporter.GetUserRoster(request.user, season) unreadCnt = MM.IPostman.GetUnreadCount(request) else: profile_dt = None puRoster_dx = None unreadCnt = 0
from signals import subscription_created, subscription_was_cancelled from paypal.standard.ipn.signals import valid_ipn_received valid_ipn_received.connect(subscription_created) valid_ipn_received.connect(subscription_was_cancelled)
from mysite import models from paypal.standard.models import ST_PP_COMPLETED from paypal.standard.ipn.signals import valid_ipn_received def payment_notification(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: order_id = ipn_obj.invoice.split('-')[-1] order = models.Order.objects.get(id = order_id) order.paid = True order.save() valid_ipn_received.connect(payment_notification)
message, settings.EMAIL_HOST_USER, to=[user.email]) mail.send() print("User Account has expired!") elif ipn_obj.txn_type == "subscr_failed": try: user = User.objects.get(email=email) except ObjectDoesNotExist: user = None mail_subject = "Your Payment Was Unsuccessful" message = render_to_string( 'mails/subscription_failed.html', { 'firstname': user.first_name, 'lastname': user.last_name, 'domain': current_site }) mail = EmailMessage(mail_subject, message, settings.EMAIL_HOST_USER, to=[user.email]) mail.send() print("We were unable to process the user's payment!") else: print("User creation failed!!!") valid_ipn_received.connect(payment_receiver)
def get_form(self, post_data): from paypal.standard.forms import PayPalPaymentsForm return PayPalPaymentsForm(initial=post_data) # # def show_me_the_money(sender, **kwargs): # ipn_obj = sender # if ipn_obj.payment_status == ST_PP_COMPLETED: # # WARNING ! # # Check that the receiver email is the same we previously # # set on the business field request. (The user could tamper # # with those fields on payment form before send it to PayPal) # if ipn_obj.receiver_email != "*****@*****.**": # # Not a valid payment # return # # # ALSO: for the same reason, you need to check the amount # # received etc. are all what you expect. # # # Undertake some action depending upon `ipn_obj`. # if ipn_obj.custom == "Upgrade all users!": # Users.objects.update(paid=True) # else: from paypal.standard.ipn.signals import valid_ipn_received valid_ipn_received.connect(PaymentProcessor.ipn_signal_handler)
donation = get_object_or_404(Donation, id=ipn_obj.invoice) donation.verified = True if not donation.receipt_sent: sendSystemEmail( False, 'Thank you!', 'coderdojochi-donation-receipt', { 'first_name': donation.first_name, 'last_name': donation.last_name, 'email': donation.email, 'amount': u'${}'.format(donation.amount), 'transaction_date': arrow.get( donation.created_at ).format( 'MMMM D, YYYY h:ss a' ), 'transaction_id': donation.id }, donation.email, [v for k, v in settings.ADMINS] ) donation.receipt_sent = True donation.save() valid_ipn_received.connect(donate_callback)
Created a subscription in the db """ print('sub created') # 'sender' argument sent with the signal. In this case, is an instance of # the instant payment notification. ipn_obj = sender # ipn - instant payment notification # custom was defined in the PayPayPaymentForm in magazines/templatetags/magazine_extras.py magazine_id = ipn_obj.custom.split('-')[0] user_id = ipn_obj.custom.split('-')[1] # Create record in the db Purchase.objects.create(magazine_id=magazine_id, user_id=user_id, subscription_end=arrow.now().replace(weeks=+4).datetime) def subscription_was_cancelled(sender, **kwargs): ipn_obj = sender magazine_id = ipn_obj.custom.split('-')[0] user_id = ipn_obj.custom.split('-')[1] # Get record from the db purchase = Purchase.object.get(user_id=user_id, magazine_id=magazine_id) # Update the subscription_end (to end the subscription immediately) and save/update in the db purchase.subscription_end = arrow.now() purchase.save() # connect() method used to tell Django that we want the # relevant code to be run whenever those signals are sent. valid_ipn_received.connect(subscription_created) # see magazines/signals valid_ipn_received.connect(subscription_was_cancelled) # see magazines/signals
if match: pk = int(match.group(1)) subscription = Subscription.objects.filter(pk=pk).first() if subscription: if sender.payment_status == ST_PP_COMPLETED: subscription.paid = sender.payment_gross subscription.payment = 'eletronic' subscription.save() SubscriptionPayment.objects.create( subscription=subscription, content_object=sender ) valid_ipn_received.connect(detect_paypal_payment_and_mark_subscription) @receiver(post_save, sender=Transaction) def detect_bcash_payment_and_mark_subscription(sender, instance, **kwargs): data = getattr(instance, 'json_data', {}) pk = int(data.get('produto_codigo_1', 0)) val = float(data.get('produto_valor_1', 0)) subscription = Subscription.objects.filter(pk=pk).first() if subscription: if instance.status_code == ST_APPROVED: subscription.paid = val subscription.payment = 'eletronic' subscription.save()
if ipn_obj.payment_status == ST_PP_COMPLETED: if (ipn_obj.receiver_email != settings.PAYPAL_ACCOUNT or ipn_obj.mc_currency != 'USD'): # Not a valid payment return try: order = Order.objects.get( pk=ipn_obj.invoice[len(settings.PAYPAL_PREFIX):], amount=ipn_obj.mc_gross ) except Order.DoesNotExist: return order.payment_id = ipn_obj.txn_id order.payment_email = ipn_obj.payer_email order.save() question = order.question question.priority = question.priority[0] question.approved = 'Y' question.save() else: pass # handle other status valid_ipn_received.connect(handle_payment)
paypal_invoice_id=ipn_obj.invoice) if registration.league.is_waitlist(registration.user): registration.waitlist = True registration.payment_complete = True registration.paypal_complete = True registration.registered = ipn_obj.payment_date registration.save() if registration.coupon: registration.coupon.process(registration.user) print u'PayPal IPN Complete: {} - {} - {} - {}'.format( ipn_obj.invoice, registration.id, ipn_obj.mc_gross, registration.paypal_price) except Registrations.DoesNotExist: print u'PayPal IPN Error: {} - Registration does not exist'.format( ipn_obj.invoice) except Exception, ex: print u'PayPal IPN Error: {} - Unknown error'.format( ipn_obj.invoice) print u'{}'.format(ex) else: print u'PayPal IPN Not Complete: {} - {}'.format( ipn_obj.invoice, ipn_obj.payment_status) valid_ipn_received.connect(paypal_callback)
from django.shortcuts import get_object_or_404 from paypal.standard.models import ST_PP_COMPLETED from paypal.standard.ipn.signals import valid_ipn_received #from orders.models import orders #from orders.models import Order """ def payment_notification(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: # payment was successful order = get_object_or_404(Order, id=ipn_obj.invoice) # mark the order as paid order.paid = True order.save() valid_ipn_received.connect(payment_notification) """
from django.shortcuts import get_object_or_404 from paypal.standard.models import ST_PP_COMPLETED from paypal.standard.ipn.signals import valid_ipn_received from order.models import Order def PaymentNotification(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: order = get_object_or_404(Order, id=ipn_obj.invoice) order.paid = True order.save() valid_ipn_received.connect(PaymentNotification)
order = Order.objects.get(pk=reference) #ele busca o pedido except Order.DoesNotExist: pass else: order.pagseguro_update_status(status) #se houver o pedido return HttpResponse('OK') #sender objeto ipn , api do django paypal fornece, se receber o status completa ele dispara essa funcao def paypal_notification(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED and \ ipn_obj.receiver_email == settings.PAYPAL_EMAIL: try: order = Order.objects.get(pk=ipn_obj.invoice) order.complete() except Order.DoesNotExist: pass valid_ipn_received.connect( paypal_notification ) #recebeu uma notificação, e ele conecta uma funcao neste sinal create_cartitem = CreateCartItemView.as_view() cart_item = CartItemView.as_view() #criando views chamaveis checkout = CheckoutView.as_view() order_list = OrderListView.as_view() order_detail = OrderDetailView.as_view() pagseguro_view = PagSeguroView.as_view() paypal_view = PaypalView.as_view()
product.save() def show_me_the_money(sender, **kwargs): ipn_obj = sender print("Begin PayPal Processing") # If PayPal returns an indication that our payment was successful and # the custom callback function matches 'perform_receipt_checkout' then # find the Customer's Receipt and set it to succesffully checked out! if ipn_obj.payment_status == ST_PP_COMPLETED: print(ipn_obj) #if ipn_obj.custom == "perform_receipt_checkout": receipt_id = int(ipn_obj.invoice) try: receipt = Receipt.objects.get(receipt_id=receipt_id) print(receipt) paypal_checkout_online_receipt(receipt) except Receipt.DoesNotExist: print("Cannot find Receipt", str(receipt_id)) else: print("PayPal Error", str(ipn_obj.payment_status)) # IMPORTANT: When PayPal sends a transaction notification to our server # our "django-paypal" library will handle accepting it and # then invoking the following function called "payment_signal". valid_ipn_received.connect(show_me_the_money) # Note: # Documents: https://django-paypal.readthedocs.org/en/stable/standard/ipn.html
student=instance.student, currency=instance.group.currency, ) instance.save() def paypal_bill_paid(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: try: bill = Bill.objects.get(pk=ipn_obj.invoice) bill.is_paid = True bill.paid_date = datetime.now() bill.transaction_id = ipn_obj.txn_id bill.save() ok = True except Exception as e: ok = False # FIXME do something here if ok: invoice = render_to_string('email_invoice.html', {'bill': bill}) send_mail(_("Academica Invoice paid"), _("Go to Academica"), settings.DEFAULT_FROM_EMAIL, [bill.student.email], html_message=invoice, fail_silently=False ) valid_ipn_received.connect(paypal_bill_paid)
from paypal.standard.models import ST_PP_COMPLETED from paypal.standard.ipn.signals import valid_ipn_received def show_me_the_money(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: # WARNING ! # Check that the receiver email is the same we previously # set on the business field request. (The user could tamper # with those fields on payment form before send it to PayPal) if ipn_obj.receiver_email != PayPalInfo.objects.get().email: # Not a valid paymen print ipn_obj.receiver_email, PayPalInfo.objects.get().email return # ALSO: for the same reason, you need to check the amount # received etc. are all what you expect. # Undertake some action depending upon `ipn_obj`. user_id = ipn_obj.custom company = User.objects.get(id=user_id).companyprofile company.has_submitted_payment = True company.save() print "my boy got saved", User.objects.get(id=user_id).companyprofile.has_submitted_payment else: print "uh oh send an email" print ipn_obj.payment_status #... valid_ipn_received.connect(show_me_the_money)
paid_price = ipn_obj.mc_gross if paid_price != expected_price: Transaction.objects.create(success=False, target_email=target_email, product=product, price=paid_price) paid_currency = ipn_obj.mc_currency if paid_currency != 'USD': Transaction.objects.create(success=False, target_email=target_email, product=product, price=paid_price, currency=paid_currency) return target_user = ipn_obj.custom user = User.objects.filter(pk=target_user) if user: Account.objects.filter(user=user).update(credit=F('credit') + credits_to_add) Transaction.objects.create(success=True, target_email=target_email, product=product, price=paid_price, currency=paid_currency, user=user) else: Transaction.objects.create(success=False, target_email=target_email, product=product, price=paid_price, currency=paid_currency) else: Transaction.objects.create(success=False) return valid_ipn_received.connect(paypal_money_received)
else: order.canceled() order.save() except Order.DoesNotExist: print("No existe la orden") # unsuccessful_txn_handler(sender, **kwargs) pass except Order.MultipleObjectsReturned: # unsuccessful_txn_handler(sender, **kwargs) pass except BaseException as e: print(e) pass def unsuccessful_txn_handler(sender, **kwargs): transaction_was_unsuccessful.send(sender=sender.__class__, transaction_type="purchase", response=sender) def successful_txn_handler(sender, **kwargs): transaction_was_successful.send(sender=sender.__class__, transaction_type="purchase", response=sender) valid_ipn_received.connect(txn_handler)
obj_type.title(), 'payment to paypal email {}'.format( additional_data['test_paypal_email'] ) if obj_type == 'paypal_test' else 'id {}'.format(obj.id), ipn_obj.invoice, ipn_obj.txn_id, e ) ) send_mail( '{} There was some problem processing payment_not_received for ' '{} {}'.format( settings.ACCOUNT_EMAIL_SUBJECT_PREFIX, obj_type, 'payment to paypal email {}'.format( additional_data['test_paypal_email'] ) if obj_type == 'paypal_test' else 'id {}'.format(obj.id) ), 'Please check your booking and paypal records for ' 'invoice # {}, paypal transaction id {}.\n\nThe exception ' 'raised was "{}".\n\nNOTE: this error occurred during ' 'processing of the payment_not_received signal'.format( ipn_obj.invoice, ipn_obj.txn_id, e ), settings.DEFAULT_FROM_EMAIL, [settings.SUPPORT_EMAIL], fail_silently=False) valid_ipn_received.connect(payment_received) invalid_ipn_received.connect(payment_not_received)
status = notification_data.status reference = notification_data.reference try: order = Order.objects.get(pk=reference) except Order.DoesNotExist: pass else: order.pagseguro_update_status(status) return HttpResponse('OK') def paypal_notification(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED and \ ipn_obj.receiver_email == settings.PAYPAL_EMAIL: try: order = Order.objects.get(pk=ipn_obj.invoice) order.complete() except Order.DoesNotExist: pass valid_ipn_received.connect(paypal_notification) create_cartitem = CreateCartItemView.as_view() cart_item = CartItemView.as_view() checkout = CheckoutView.as_view() order_list = OrderListView.as_view() order_detail = OrderDetailView.as_view() pagseguro_view = PagSeguroView.as_view() paypal_view = PaypalView.as_view()
settings.PAYPAL_URL + reverse('shop:shop_main'), "custom": "{}".format(order.user) } paypal_form = PayPalPaymentsForm(initial=paypal_dict).render() data = { 'order': order, 'paypal_form': paypal_form, } return render(request, 'payment/thankyou.html', data) elif order.payment_method == 'b': data = {'order': order} return render(request, 'payment/thankyou_krw.html', data) valid_ipn_received.connect(check_payment) # Staff Order View Page @staff_member_required def orderlist(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; ' \ 'filename="IRKSHOP_ORDERLIST_{}.csv"'.format( datetime.now().strftime("%Y%m%d%H%M") ) writer = csv.writer(response) writer.writerow([ 'Invoice Number', 'User Email', 'Pay Amount', 'Order Details', 'Custom Orders', 'Shipping Address'
def payment_notification(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: # payment was successful order = get_object_or_404(Order, id=ipn_obj.invoice) # mark the order as paid order.paid = True order.save() # create invoice e-mail subject = 'My Shop - Invoice nr. {}'.format(order.id) message = 'Please, find attached the invoice for your recent purchase.' email = EmailMessage(subject, message, '*****@*****.**', [order.email]) # generate PDF html = render_to_string('orders/order/pdf.html', {'order': order}) out = BytesIO() stylesheets = [weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')] weasyprint.HTML(string=html).write_pdf(out, stylesheets=stylesheets) # attach PDF file email.attach('order_{}.pdf'.format(order.id), out.getvalue(), 'application/pdf') # send e-mail email.send() valid_ipn_received.connect(payment_notification)
def process_payment(sender, **kwargs): print "Processing payment" ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: # Undertake some action depending upon `ipn_obj`. custom_code = b64decode(ipn_obj.custom) print "Custom Code: " + ipn_obj.custom + " decoded: " + custom_code m = re.search("reservation=(.*),(\d*)", custom_code) print "txn_id = " + ipn_obj.txn_id try: reservation_id = int(m.group(2)) print "id=" + unicode(reservation_id) reservation = Reservation.objects.get(id=reservation_id) print unicode(reservation) charge = {"txn_id": ipn_obj.txn_id, "invoice": ipn_obj.invoice} reservation.pay(confirmation=json.dumps(charge), choice="P") print "paid" except Reservation.DoesNotExist: print "not exist" except: print "otro error" + sys.exc_info()[0] else: print "fallo" valid_ipn_received.connect(process_payment) invalid_ipn_received.connect(process_payment)