Exemplo n.º 1
0
def configView(request):
	if(has_permission('root', Donate, request)):
		permission = 'root'
	else:
		permission = 'admin'

	if 'form.submitted' in request.params and validateCSRF(request):
		if request.params['config.community'] != Settings.Community:
			Settings.parse.set('app:main', 'community', request.params['config.community'])
			Settings.Community = request.params['config.community']
		if request.params['config.steamkey'] != Settings.SteamAPI:
			Settings.parse.set('app:main', 'steam_key', request.params['config.steamkey'])
			Settings.SteamAPI = request.params['config.steamkey']
		if 'config.regenerate' in request.params:
			Settings.APIKey = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(32))
			Settings.parse.set('app:main', 'api_key', Settings.APIKey)
		if request.params['paypal.client_id'] != Settings.parse.get('app:paypal', 'client_id', 0):
			Settings.parse.set('app:paypal', 'client_id', request.params['paypal.client_id'])
			Settings.parse.set('app:paypal', 'client_secret', request.params['paypal.secret'])
		if request.params['paypal.mode'] != Settings.parse.get('app:paypal', 'mode', 0):
			Settings.parse.set('app:paypal', 'mode', request.params['paypal.mode'])
		config = open(Settings.configFile, 'w+')
		Settings.parse.write(config)
		config.close()
		paypalrestsdk.configure({
			"mode": Settings.parse.get('app:paypal', 'mode', 0),
			"client_id": Settings.parse.get('app:paypal', 'client_id', 0),
			"client_secret": Settings.parse.get('app:paypal', 'client_secret', 0)}, ssl_options={'ca_certs': certifi.where()})	
		
	path = [{'name': 'Home', 'url': request.route_url('admin')}, {'name': 'Configuration', 'url': request.route_url('admin/config')}]
	
	return {'community': Settings.Community,  'path': path, 'permission': permission, 'settings': Settings}
Exemplo n.º 2
0
    def configure_paypal():
        """
        Configure the paypal sdk
        :return: Credentials
        """
        # Use Sandbox by default.
        settings = get_settings()
        paypal_mode = 'sandbox'
        paypal_client = settings.get('paypal_sandbox_client', None)
        paypal_secret = settings.get('paypal_sandbox_secret', None)

        # Switch to production if paypal_mode is production.
        if settings['paypal_mode'] == Environment.PRODUCTION:
            paypal_mode = 'live'
            paypal_client = settings.get('paypal_client', None)
            paypal_secret = settings.get('paypal_secret', None)

        if not paypal_client or not paypal_secret:
            raise ConflictException({
                'pointer': ''
            }, "Payments through Paypal hasn't been configured on the platform"
                                    )

        paypalrestsdk.configure({
            "mode": paypal_mode,
            "client_id": paypal_client,
            "client_secret": paypal_secret
        })
Exemplo n.º 3
0
    def post(self, request):
        import paypalrestsdk

        paypalrestsdk.configure({
          'mode': 'sandbox',
          'client_id': settings.PAYPAL_CLIENTID,
          'client_secret': settings.PAYPAL_SECRET})

        payment_id = request.POST['payment_id']
        try:
            p = paypalrestsdk.Payment.find(payment_id)
        except:
            raise Http404

        tr = p.transactions[0]
        order_tpv = tr.invoice_number
        tk = get_ticket_or_404(order_tpv=order_tpv)

        if (float(tr.amount.total) == tk.get_price() and
                p.intent == 'sale' and p.state == 'approved'):
            tk.confirm(method="paypal")
            online_sale(tk)
        else:
            return JsonResponse({'status': 'error'})

        return JsonResponse({'status': 'ok'})
Exemplo n.º 4
0
 def __init__(self, client_id, client_secret, mode):
     paypalrestsdk.configure({
         'mode': mode,                                  # live or sandbox
         'client_id': client_id,
         'client_secret': client_secret
     })
     self.paypal_client = paypalrestsdk
Exemplo n.º 5
0
def paypal_execute(request):
    """
    MyApp > Paypal > Execute a Payment
    """
    
    if not 'PayerID' in request.GET:
        return render_to_response('BondizApp/purchase.html',context_instance=RequestContext(request,{'caption': 'Naaa'}))
    
    payment_id = request.session['payment_id']
    payer_id = request.GET['PayerID']
     
    paypalrestsdk.configure({
        "mode": PAYPAL_MODE,
        "client_id": PAYPAL_CLIENT_ID,
        "client_secret": PAYPAL_CLIENT_SECRET })

    payment = paypalrestsdk.Payment.find(payment_id)
    payment_name = payment.transactions[0].item_list.items[0].name

    if payment.execute({"payer_id": payer_id}):
        return render_to_response('BondizApp/purchase.html',context_instance=RequestContext(request,{'caption': 'OK'}))
    else:
        return render_to_response('BondizApp/purchase.html',context_instance=RequestContext(request,{'caption': 'Naaa'}))

    return HttpResponseRedirect(reverse('BondizApp.views.home'))     
Exemplo n.º 6
0
    def create_paypal(self, request):
        """
        Create a new transaction record (record will be verified before saving to db)
        ---
        serializer : credit.serializers.TransactionSerializer
        """
        serializedTransaction = TransactionSerializer(data=request.data)
        if serializedTransaction.is_valid():
            package = get_object_or_404(Package,id=request.data['package'])

            # CHECK PAYPAL TRANSACTION WHETHER ITS VALID OR NOT
            # EXAMPLE : PAY-0XR76137BE293122CKVOLLWI
            paypalrestsdk.configure({'mode':PAYPAL_MODE, 'client_id':PAYPAL_CLIENT_ID, 'client_secret':PAYPAL_SECRET})
            try:
                pp = paypalrestsdk.Payment.find(request.data['transaction_id'])
            except:
                return Response({'error':{'transaction_id':['We cannot find your paypal transaction, please verify that the transaction_id is correct']}}, status=status.HTTP_400_BAD_REQUEST)

            # IF NOT APPROVED THROW USER ERROR
            if pp['state'] != 'approved':
                return Response({'error':{'transaction_id':['Payment is not approved, please check your transaction_id and try again']}}, status=status.HTTP_400_BAD_REQUEST)

            # IF THE VALUE OF THE TRANSACTION DOES NOT MATCH PACKAGE, THROW USER ERROR
            elif pp['transactions'][0]['amount']['total'] != str(package.price):
                return Response({'error':{'transaction_id':['Payment total for this transaction does not match the package price']}}, status=status.HTTP_400_BAD_REQUEST)


            # ADD CREDITS TO THE USER
            request.user.credit += package.credit
            request.user.save()

            # SAVE TRANSACTION AND RETURN DATA
            serializedTransaction.save(member=request.user, amount=package.price, is_paypal=True)
            return Response({'transaction':serializedTransaction.data}, status=status.HTTP_201_CREATED)
        return Response({'error':serializedTransaction.errors}, status=status.HTTP_403_BAD_REQUEST)
Exemplo n.º 7
0
def create_paypal():
    __location__ = os.path.realpath(
        os.path.join(os.getcwd(), os.path.dirname(__file__)))
    try:  # dev
        with open(os.path.join(__location__, 'secrets.json')) as secrets_file:
            secrets = json.load(secrets_file)

            paypalrestsdk.configure({
                "mode":
                "sandbox",  # sandbox or live
                "client_id":
                secrets.get('paypal_id'),
                "client_secret":
                secrets.get('paypal_secret')
            })

            return paypalrestsdk
    except IOError:  # prod
        paypalrestsdk.configure({
            "mode":
            "sandbox",  # sandbox or live
            "client_id":
            os.environ.get("PAYPAL_ID"),
            "client_secret":
            os.environ.get("PAYPAL_SECRET")
        })

        return paypalrestsdk
Exemplo n.º 8
0
def makePayment(url_data):

    paypalrestsdk.configure({
      'mode': 'sandbox',
      'client_id': config.paypal_client_id,
      'client_secret': config.paypal_client_secret
    })
    
    payment = paypalrestsdk.Payment({
      "intent": "sale",
      "payer": {
        "payment_method": "paypal" },
      "redirect_urls": {
        "return_url": "http://localhost:8000/finalize?" + url_data,
        "cancel_url": "http://localhost:8000/reading?" + url_data},
    
      "transactions": [ {
        "amount": {
          "total": "20",
          "currency": "USD" },
        "description": "Payment for a custom astrology profile" } ] } )
    
    payment.create()
    
    return payment
Exemplo n.º 9
0
	def post(self):
		args = parse.parse_args()
		try:
			c_id = args['contact_id']
			dcontact = Contact.query.get(c_id).first()
		except:
			abort(404, message="Contact id: %s doesn't exist" % (c_id))
		inv = Invoice()
		inv.email = args['email']
		inv.invoice_date = args['invoice_date']
		inv.recipient_note = args['recipient_note']
		inv.subtotal = args['subtotal']
		inv.total = args['total']
		inv.paid = False
		inv.contact_id = c_id
		import paypalrestsdk
		paypalrestsdk.configure({
				"mode": "sandbox", # PAYPAL_MODE
				"client_id": app.config['PAYPAL_CLIENT_ID'], # PAYPAL_CLIENT_ID
				"client_secret": app.config['PAYPAL_CLIENT_SECRET'] })		# PAYPAL_CLIENT_SECRET
		paypal_invoice = paypalrestsdk.Invoice({
				"merchant_info": {
					"email":"*****@*****.**",
					"first_name":"Francisco",
					"last_name": "Barcena",
					"business_name":"fdev.tk",
					"phone":{"country_code": "001","national_number":"5555555555"},
					"address":{
						"line1":"123 Fake St. Apt.A",
						"city":"Fake City",
						"country_code":"US",
						"state":"California"
					},
				},
				"billing_info":[{"email":request.form["email"]}],
				"note":"MAKE MONEY F*CK B*TCHES"
		})
		# inv_lines (from list in args)
		the_items = []
		for the_item in inv_lines:
			# append to the_items (for paypal)
			the_items.append(dict({"name":the_item.d_description.data,"quantity":str(the_item.qty.data),"unit_price":{"currency":"USD","value":str(the_item.unit_price.data)}}))
			# Create and append to Invoice model
			new_invoice_line = InvoiceLine()
			new_invoice_line.description
			new_invoice_line.quantity
			new_invoice_line.unit_price
			new_invoice_line.amount
			inv.invoice_lines.append(new_invoice_line)	
		paypal_invoice.items = the_items
		error = None
		if paypal_invoice.create():
			print('paypal invoice created')
			# Add invoice lines here (from list as argument) 
			db.session.add(inv)
			db.session.commit()
		else:
			error = paypal_invoice.error
			abort(404, message="Invoice creation error: %s" % (error)) 
		return inv, 201
Exemplo n.º 10
0
    def handle(self, *args, **options):
        """
        Main dispatch.
        """
        args = list(args)

        if len(args) < 2:
            raise CommandError("Required arguments `partner` and `action` are missing")

        partner = args.pop(0)
        action = args.pop(0)

        try:
            paypal_configuration = settings.PAYMENT_PROCESSOR_CONFIG[partner.lower()][self.PAYPAL_CONFIG_KEY.lower()]
        except KeyError:
            raise CommandError(
                "Payment Processor configuration for partner `{0}` does not contain PayPal settings".format(partner)
            )

        # Initialize the PayPal REST SDK
        paypalrestsdk.configure({
            'mode': paypal_configuration['mode'],
            'client_id': paypal_configuration['client_id'],
            'client_secret': paypal_configuration['client_secret']
        })

        try:
            handler = getattr(self, 'handle_{}'.format(action))
        except IndexError:
            raise CommandError("no action specified.")
        except AttributeError:
            raise CommandError("unrecognized action: {}".format(action))
        return handler(args)
Exemplo n.º 11
0
def success_payment(request):

    paypalrestsdk.configure({
        'mode': PAYPAL_MODE,
        'client_id': PAYPAL_CLIENT_ID,
        'client_secret': PAYPAL_CLIENT_SECRET
    })
    payer_id = request.GET.get('PayerID', None)
    payment_id = request.session['Payment_id']

    payment = paypalrestsdk.Payment.find(payment_id)
    payment.execute({"payer_id": payer_id})

    sn = request.session.get('dummy_booking_id', None)
    if sn:
        dummy_booking = DummyBooking.objects.get(id=int(sn))
        booking = Booking.objects.create(
            artist=dummy_booking.artist,
            listing=dummy_booking.listing,
            client=dummy_booking.client,
            cancellation_policy=dummy_booking.cancellation_policy,
            price=dummy_booking.price,
            title=dummy_booking.title,
            start_time=dummy_booking.start_time,
            end_time=dummy_booking.end_time,
            status=0,
        )
        create_payment(request, payment, booking.id)
        dummy_booking.delete()
        request.session['dummy_booking_id'] = ''
        request.session['Payment_id'] = ''
    else:
        return HttpResponseRedirect(reverse("error"))

    return render(request, 'payments/success.html', {})
Exemplo n.º 12
0
def partially_capture(booking_id):
    ''' Partially capture the money. Example for listing 100$. 50 for the client, 45 for artist, 5 for us. '''
    from glamazer.payments.models import Payment
    from glamazer.booking.models import Booking

    booking = Booking.objects.select_related().get(id=booking_id)
    artist = booking.artist

    price = booking.price  # booking price
    percent = booking.cancellation_policy.percent  # the percent from cancellation policy
    for_us = booking.revenue
    for_artist = (price - for_us) * percent / 100

    payment = Payment.objects.filter(
        booking_id=booking_id).order_by("last_updated")[0]
    auth_id = payment.authorization_id
    method = payment.payment_method
    currency = payment.currency

    if method == 1:
        paypalrestsdk.configure({
            'mode': PAYPAL_MODE,
            'client_id': PAYPAL_CLIENT_ID,
            'client_secret': PAYPAL_CLIENT_SECRET
        })

        authorization = paypalrestsdk.Authorization.find(auth_id)
        capture = authorization.capture({
            "amount": {
                "currency": currency,
                "total": format(for_artist, ',.2f')
            },
            "is_final_capture": True
        })

        if not capture.success():
            return False

        payment.current_status = "partially_captured"
        payment.save()

    elif method == 2:
        p = pymill.Pymill(PR_PAYMILL_API_KEY)
        trans = p.transact(amount=int(for_artist + for_us) * 100,
                           currency=currency,
                           description="{0}-{1}".format(
                               booking.title, booking.price),
                           preauth=auth_id)

        payment.current_status = "captured"
        payment.authorization_id = trans.id
        payment.save()

    artist.money = artist.money + for_artist
    artist.save()

    if artist.salon:
        salon = artist.salon
        salon.money = salon.money + for_artist
        salon.save()
Exemplo n.º 13
0
def paypal_create(request):
    """
    MyApp > Paypal > Create a Payment
    """

    logging.basicConfig(level=logging.DEBUG)

    paypalrestsdk.configure({
        "mode": PAYPAL_MODE,
        "client_id": PAYPAL_CLIENT_ID,
        "client_secret": PAYPAL_CLIENT_SECRET })

    payment = paypalrestsdk.Payment({
        "intent": "sale",
        "payer": {
            "payment_method": "paypal"
        },
        "redirect_urls": {
            "return_url": request.build_absolute_uri(reverse('paypal_execute')),
            "cancel_url": request.build_absolute_uri(reverse('home page')) },
        "transactions": [{
            "item_list": {
                "items": [{
                    "name": "name of your item 1",
                    "price": "10.00",
                    "currency": "GBP",
                    "quantity": 1,
                    "sku": "1"
                }, {
                    "name": "name of your item 2",
                    "price": "10.00",
                    "currency": "GBP",
                    "quantity": 1,
                    "sku": "2"
                }]
            },
            "amount":  {
                "total": "20.00",
                "currency": "GBP"
            },
            "description": "purchase description"
        }]
    })

    redirect_url = ""

    if payment.create():
        # Store payment id in user session
        request.session['payment_id'] = payment.id

        # Redirect the user to given approval url
        for link in payment.links:
            if link.method == "REDIRECT":
                redirect_url = link.href
        return HttpResponseRedirect(redirect_url)

    else:
        messages.error(request, 'We are sorry but something went wrong. We could not redirect you to Paypal.')
        return HttpResponse('<p>We are sorry but something went wrong. We could not redirect you to Paypal.</p><p>'+str(payment.error)+'</p>')
Exemplo n.º 14
0
    def post(self, request, *args, **kwargs):
        paypalrestsdk.configure({
            'mode': settings.PAYPAL_MODE,
            'client_id': settings.PAYPAL_CLIENT_ID,
            'client_secret': settings.PAYPAL_CLIENT_SECRET,
        })

        payment = paypalrestsdk.Payment({
            'intent':
            'sale',

            # Payer
            'payer': {
                'payment_method': 'paypal',
            },

            # Redirect URLs
            'redirect_urls': {
                'return_url':
                request.build_absolute_uri(reverse('shop:execute-payment')),
                'cancel_url':
                request.build_absolute_uri(reverse('shop:cart')),
            },

            # Transaction
            # Note: This is dummy. If production, transaction should be created with reference to cart items.
            'transactions': [{
                # Item List
                'item_list': {
                    'items': [{
                        'name': 'item',
                        'sku': 'item',
                        'price': '5.00',
                        'currency': 'USD',
                        'quantity': 1,
                    }]
                },
                # Amount
                'amount': {
                    'total': '5.00',
                    'currency': 'USD',
                },
                'description':
                'This is the payment transaction description.',
            }]
        })

        # Create Payment
        if payment.create():
            logger.info("Payment[{}] created successfully.".format(payment.id))
            return JsonResponse({'success': True, 'paymentId': payment.id})
        else:
            logger.error("Payment failed to create. {}".format(payment.error))
            return JsonResponse(
                {
                    'success': False,
                    'error': "Error occurred while creating your payment."
                },
                status=500)
Exemplo n.º 15
0
def create_payment(request):

    if request.POST:
        amount = request.POST.get('total_amount')

        if amount:
            paypalrestsdk.configure({
                "mode":
                "sandbox",  # sandbox or live
                "client_id":
                config('client_id', default=''),
                "client_secret":
                config('client_secret', default='')
            })

            payment = paypalrestsdk.Payment({
                "intent":
                "sale",
                "payer": {
                    "payment_method": "paypal"
                },
                "redirect_urls": {
                    "return_url": "http://127.0.0.1:8000/pay_done",
                    "cancel_url": "http://127.0.0.1:8000/pay_fail"
                },
                "transactions": [{
                    "item_list": {
                        "items": [{
                            "name": "Education Fee",
                            "sku": "Fee",
                            "price": amount,
                            "currency": "USD",
                            "quantity": 1
                        }]
                    },
                    "amount": {
                        "total": amount,
                        "currency": "USD"
                    },
                    "description":
                    "This is the payment transaction description."
                }]
            })

            if payment.create():
                logging.info("Payment created successfully")

                for link in payment.links:
                    if link.rel == "approval_url":
                        # Convert to str to avoid Google App Engine Unicode issue
                        # https://github.com/paypal/rest-api-sdk-python/pull/58
                        approval_url = str(link.href)
                        logging.info("Redirect for approval: %s" %
                                     (approval_url))
                        return HttpResponseRedirect(approval_url)
            else:
                logging.error(payment.error)
        else:
            logging.error("Invalid Amount...")
Exemplo n.º 16
0
def configure_paypal():
    configure({
        "mode": "sandbox",  # sandbox or live
        "client_id": PAYPAL_CLIENT_ID,
        "client_secret": PAYPAL_CLIENT_SECRET
    })

    return
 def __init__(self, order):
     self._order = order
     # Configure API connection
     paypalrestsdk.configure({
         "mode": MODE,
         "client_id": PAYPAL_CLIENT_ID,
         "client_secret": PAYPAL_CLIENT_SECRET
     })
Exemplo n.º 18
0
 def __init__(self):
     import paypalrestsdk
     paypalrestsdk.configure({
         "mode": "sandbox",
         "client_id": settings.PAYPAL_CLIENT_ID,
         "client_secret": settings.PAYPAL_CLIENT_SECRET
     })
     self.paypalrestsdk = paypalrestsdk
Exemplo n.º 19
0
	def __init__(self):
		"""
		"""
		paypalrestsdk.configure({
                   "mode": paypalconfig.PAYPAL_MODE,
		   "client_id": paypalconfig.PAYPAL_CLIENT_ID,
		   "client_secret": paypalconfig.PAYPAL_CLIENT_SECRET
		})
Exemplo n.º 20
0
def paypal_login():
    paypalrestsdk.configure(
        {
            "mode": "sandbox",
            "client_id": "AQkquBDf1zctJOWGKWUEtKXm6qVhueUEMvXO_-MCI4DQQ4-LWvkDLIN2fGsd",
            "client_secret": "EL1tVxAjhT7cJimnz5-Nsx9k2reTKSVfErNQF-CmrwJgxRtylkGTKlU4RvrX",
        }
    )
Exemplo n.º 21
0
def partially_capture(booking_id):
    ''' Partially capture the money. Example for listing 100$. 50 for the client, 45 for artist, 5 for us. '''
    from glamazer.payments.models import Payment
    from glamazer.booking.models import Booking

    booking = Booking.objects.select_related().get(id=booking_id)
    artist = booking.artist

    price = booking.price                          # booking price
    percent = booking.cancellation_policy.percent  # the percent from cancellation policy
    for_us = booking.revenue
    for_artist = (price-for_us)*percent/100

    payment = Payment.objects.filter(booking_id=booking_id).order_by("last_updated")[0]
    auth_id = payment.authorization_id
    method = payment.payment_method
    currency = payment.currency

    if method == 1:
        paypalrestsdk.configure({
            'mode': PAYPAL_MODE,
            'client_id': PAYPAL_CLIENT_ID,
            'client_secret': PAYPAL_CLIENT_SECRET
        })

        authorization = paypalrestsdk.Authorization.find(auth_id)
        capture = authorization.capture({
            "amount": {
                "currency": currency,
                "total": format(for_artist, ',.2f')
                },
            "is_final_capture": True
            })

        if not capture.success():
            return False

        payment.current_status = "partially_captured"
        payment.save()

    elif method == 2:
        p = pymill.Pymill(PR_PAYMILL_API_KEY)
        trans = p.transact(amount=int(for_artist + for_us)*100,
                           currency=currency,
                           description="{0}-{1}".format(booking.title, booking.price),
                           preauth=auth_id)

        payment.current_status = "captured"
        payment.authorization_id = trans.id
        payment.save()

    artist.money = artist.money + for_artist
    artist.save()

    if artist.salon:
        salon = artist.salon
        salon.money = salon.money + for_artist
        salon.save()
Exemplo n.º 22
0
def pay_paypal(data, payment, test=False):
    mode = 'sandbox' if test else 'live'
    paypalrestsdk.configure({
      "mode": mode, # sandbox or live
      "client_id": data.get('code'),
      "client_secret": data.get('key')})

    payment = make_payment(paypalrestsdk, data, payment)
    return payment
Exemplo n.º 23
0
    def __init__(self, client_id_, client_secret_):
        self.client_id = client_id_
        self.client_secret = client_secret_
        logging.basicConfig(level=logging.INFO)

        paypalrestsdk.configure({
            "mode": "live", # sandbox or live
            "client_id": self.client_id,
            "client_secret": self.client_secret })
Exemplo n.º 24
0
 def ready(self):
     paypal_configuration = settings.PAYMENT_PROCESSOR_CONFIG.get('paypal')
     if paypal_configuration:
         # Initialize the PayPal REST SDK
         paypalrestsdk.configure({
             'mode': paypal_configuration['mode'],
             'client_id': paypal_configuration['client_id'],
             'client_secret': paypal_configuration['client_secret']
         })
Exemplo n.º 25
0
def complete_payment(request):
    paypalrestsdk.configure({
        'mode': settings.PAYPAL_MODE,
        'client_id': settings.PAYPAL_CLIENT_ID,
        'client_secret': settings.PAYPAL_CLIENT_SECRET
    })
    if request.session['fd'] and request.session['paypal_id']:
        time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
        reward_desc = (Reward.objects.get(name=request.session['fd']['reward_name']).desc if request.session['fd']['reward'] else 'None')
        pmt = paypalrestsdk.Payment.find(request.session['paypal_id'])
        if pmt['state'] == 'created':
            if pmt.execute({"payer_id": request.session['paypal_pid']}):
                o = Order(
                    name=(request.session['fd']['namecredit'] if request.session['fd']['namecredit'] else 'PayPal User'),
                    addr1='',
                    addr2='',
                    city='',
                    state='',
                    pcode='',
                    country='',
                    reward=(Reward.objects.get(name=request.session['fd']['reward_name']) if request.session['fd']['reward'] else None),
                    amount=decimal.Decimal(request.session['fd']['amount']),
                    ptype='PP',
                    pref=request.session['paypal_id'],
                    email=request.session['fd']['email'],
                    namecredit=request.session['fd']['namecredit'],
                    notes=request.session['fd']['notes']
                )
                request.session['paypal_id'] = {}
                request.session['paypal_pid'] = {}
                try:
                    o.notify = request.session['fd']['notify']
                except:
                    pass
                o.save()
                if request.session['fd']['email']:
                    send_mail(
                        subject=settings.PROJECT_NAME+' - Thank you for your contribution',
                        message=get_template('notify.txt').render({'order': request.session['fd'], 'proj_name': settings.PROJECT_NAME, 'proj_addr': settings.PROJECT_ADDR, 'time': time, 'reward_desc': reward_desc}),
                        from_email=settings.NOTIFY_SENDER, 
                        recipient_list=[request.session['fd']['email']],
                        fail_silently=True)
                request.session['fd'] = {}
                return render(request, 'payment/success.html', locals())
            else:
                request.session['paypal_id'] = {}
                request.session['paypal_pid'] = {}
                msg = 'There was an error with your payment.\n'+str(pmt.error)
                return render(request, 'error.html', locals())
        else:
            request.session['paypal_id'] = {}
            request.session['paypal_pid'] = {}
            msg = 'An unexpected error has occurred. Please try again.'
            return render(request, 'error.html', locals())
    else:
        msg = 'Your session data could not be found. Please retry your submission again.'
        return render(request, 'error.html', locals())
Exemplo n.º 26
0
def create_invoice_final():
	class InvoiceLineForm(Form):
		d_description = TextField()
		qty = DecimalField()
		unit_price = DecimalField()
	class InvoiceForm(Form):
		email = TextField()
		invoice_date = DateField(format='%m/%d/%Y')
		contact_id = TextField()
		recipient_note = TextField()
		subtotal = DecimalField()
		total = DecimalField()
		paid = BooleanField()
		invoice_line = FieldList(FormField(InvoiceLineForm))
	import paypalrestsdk
	paypalrestsdk.configure({
			"mode": "sandbox", # PAYPAL_MODE
			"client_id": app.config['PAYPAL_CLIENT_ID'], # PAYPAL_CLIENT_ID
			"client_secret": app.config['PAYPAL_CLIENT_SECRET'] })		# PAYPAL_CLIENT_SECRET
	paypal_invoice = paypalrestsdk.Invoice({
			"merchant_info": {
				"email":"*****@*****.**",
				"first_name":"Francisco",
				"last_name": "Barcena",
				"business_name":"fdev.tk",
				"phone":{"country_code": "001","national_number":"5555555555"},
				"address":{
					"line1":"123 Fake St. Apt.A",
					"city":"Fake City",
					"country_code":"US",
					"state":"California"
				},
			},
			"billing_info":[{"email":request.form["email"]}],
			"note":"MAKE MONEY F*CK B*TCHES"
	})
	invoice_form = InvoiceForm(request.form)
	the_items = []
	for the_item in invoice_form.invoice_line:
		the_items.append(dict({"name":the_item.d_description.data,"quantity":str(the_item.qty.data),"unit_price":{"currency":"USD","value":str(the_item.unit_price.data)}}))
	paypal_invoice.items = the_items
	error = None
	if paypal_invoice.create():
		#return ("Invoice[%s] created successfully" % (invoice.id,))
		flash('Invoice successfully created')
		invoice_model = Invoice()
		invoice_form.populate_obj(invoice_model)
		invoice_model.invoice_date = datetime.now().replace(second = 0 , microsecond = 0)
		invoice_model.contact_id = db.session.query(Contact).filter_by(Contact.email == request.form["email"]).first().id
		invoice_model.recipient_note ='Test'
		db.session.add(invoice_model)
		db.session.commit()
		# return redirect('/invoices')
		return redirect('/invoices')
	else:
		errror = paypal_invoice.error
		return redirect('/invoices')
Exemplo n.º 27
0
 def initPayPal(self):
     try:
         urllib2.urlopen('https://developer.paypal.com',timeout=5)
         paypalrestsdk.configure({
             'mode':             'sandbox',
             'client_id':        'AQvHZBAWpd-nwPq9dBf92g7x9Rb7Qnu-c6HvMlUtG3YJ4Dk9SKLBMGRjs3KK',
             'client_secret':    'EE12TxCGjMqmr1N2Z1Z8VKv4UhefqowqKGfkQbg5mBxFhtlpULonFsRLd137'
         })
     except Exception:
         raise Exception(sys.exc_info()[1])
Exemplo n.º 28
0
    def ready(self):
        # This ensures that the signal receivers are loaded
        import paypalrestsdk

        # Paypal SDK is globally con
        paypalrestsdk.configure({
            'mode': getattr(settings, 'PAYPAL_MODE', 'sandbox'),
            'client_id': getattr(settings, 'PAYPAL_CLIENT_ID',''),
            'client_secret': getattr(settings, 'PAYPAL_CLIENT_SECRET',''),
        })
Exemplo n.º 29
0
def executePayment(payment_id, payer_id):
  
  paypalrestsdk.configure({
      'mode': 'sandbox',
      'client_id': config.paypal_client_id,
      'client_secret': config.paypal_client_secret
    })
  
  payment = paypalrestsdk.Payment.find(payment_id)
  return payment.execute({"payer_id": payer_id})  
Exemplo n.º 30
0
def bootstrap():
  # Config Paypal
  try:
    # Check environment var exists
    os.environ['PAYPAL_MODE']
    os.environ['PAYPAL_CLIENT_ID']
    os.environ['PAYPAL_CLIENT_SECRET']
  except:
    # Config with settings if no env var specified
    paypalrestsdk.configure(settings.PAYPAL_CONFIG)
Exemplo n.º 31
0
    def get(self, request, *args, **kwargs):
        try:
            self.object = self.get_object()
        except Http404:
            messages.error(self.request, "That issue was not found.")
            return redirect("/")

        if self.request.GET.get("paymentId"):
            import paypalrestsdk

            paypalrestsdk.configure(
                {"mode": settings.MODE, "client_id": settings.CLIENT_ID, "client_secret": settings.CLIENT_SECRET}
            )

            payment = paypalrestsdk.Payment.find(self.request.GET.get("paymentId"))

            custom = payment.transactions[0].custom

            if payment.execute({"payer_id": self.request.GET.get("PayerID")}):
                send_mail(
                    "Processed Payment PayerID"
                    + self.request.GET.get("PayerID")
                    + " paymentID"
                    + self.request.GET.get("paymentId"),
                    "payment occured",
                    "*****@*****.**",
                    ["*****@*****.**"],
                    html_message="payment occured",
                )
                for obj in serializers.deserialize("json", custom, ignorenonexistent=True):
                    obj.object.created = datetime.datetime.now()
                    obj.object.checkout_id = self.request.GET.get("checkout_id")
                    obj.save()
                    action.send(
                        self.request.user,
                        verb="placed a $" + str(obj.object.price) + " bounty on ",
                        target=obj.object.issue,
                    )
                    post_to_slack(obj.object)
                    if not settings.DEBUG:
                        create_comment(obj.object.issue)
            else:
                messages.error(request, payment.error)
                send_mail(
                    "Payment error: PayerID"
                    + self.request.GET.get("PayerID")
                    + " paymentID"
                    + self.request.GET.get("paymentId"),
                    "payment error",
                    "*****@*****.**",
                    ["*****@*****.**"],
                    html_message="payment error",
                )

        return super(IssueDetailView, self).get(request, *args, **kwargs)
Exemplo n.º 32
0
def member_payment_execute(request):

    payer_id = request.GET['PayerID']
    token = request.GET['token']
    user = request.user
    pph = PaypalPaymentHistory.objects.get(token=token, member=user)
    package = pph.package

    paypalrestsdk.configure({
        "mode": "sandbox", 
        "client_id": "AQW51xAPblqbEtHM_vxW7Kv_Mk2Y1lFVtr1YIhWkackcPDzzu4OJNE6WJnIz",
        "client_secret": "EJL20BC2_6Ktrk2uLBh3vFPz7hn3RWcmblmCIpjHYEGoGRq2Un7sP2c4-wR7"
    })

    payment = paypalrestsdk.Payment.find(pph.payment_id)

    if payment.execute({"payer_id": payer_id}):
        print("Payment execute successfully")

        ''' Update paypal payment history status'''
        pph.status = 'executed'
        pph.save()

        ''' Update MemberCurrentBalance '''
        current_balance, test = MemberCurrentBalance.objects.get_or_create(member=user)
        current_balance.total_sms += pph.sms
        current_balance.total_minute += pph.minute
        current_balance.total_mms += pph.mms
        current_balance.total_email += pph.email
        current_balance.total_attachement += pph.attachement
        # current_balance.dollar_amount += pph.cost
        current_balance.purchased_twilio_number += pph.twilio_number
        current_balance.financial_status = 'healthy'
        current_balance.save()

        ''' Create member profile '''
        try:
            member_profile = MemberProfile.objects.get(member=user)

        except MemberProfile.DoesNotExist:
            member_profile = MemberProfile.objects.create(member=user)

        if member_profile.profile_status not in (TWILIO_ACCONT_CREATED, TWILIO_NUMBER_ADDED, TWILIO_CONTACT_ADDED, SUSPENDED, ACTIVE):
            ''' Create twilio subaccount '''
            tw_subaccount = member_profile.create_twilio_subaccount()
            

        return HttpResponseRedirect("/member/dashboard/")

    else:
        print(payment.error) # Error Hash
        messages.error(request, payment.error['message'])
        return HttpResponseRedirect("/member/dashboard/")
Exemplo n.º 33
0
    def get(self, request, **kwargs):
        try:
            self.object = self.get_object()
        except Http404:
            messages.error(self.request, "That solution was not found.")
            return redirect("/")

        # temporarally until we add creator to issues
        if Bounty.objects.filter(user=self.request.user).filter(issue=self.object.issue):

            import paypalrestsdk
            import random
            import string

            paypalrestsdk.configure(
                {"mode": settings.MODE, "client_id": settings.CLIENT_ID, "client_secret": settings.CLIENT_SECRET}
            )
            sender_batch_id = "".join(random.choice(string.ascii_uppercase) for i in range(12))

            payout = paypalrestsdk.Payout(
                {
                    "sender_batch_header": {
                        "sender_batch_id": sender_batch_id,
                        "email_subject": "You have a payment from Coderbounty",
                    },
                    "items": [
                        {
                            "recipient_type": "EMAIL",
                            "amount": {"value": self.object.issue.bounty(), "currency": "USD"},
                            "receiver": self.object.user.userprofile.payment_service_email,
                            "note": "Thank you for your solution",
                            "sender_item_id": str(self.object.issue),
                        }
                    ],
                }
            )

            if payout.create():
                messages.success(
                    self.request, "payout[%s] created successfully" % (payout.batch_header.payout_batch_id)
                )
                self.object.status = Solution.PAID
                self.object.save()
                self.object.issue.winner = self.object.user
                self.object.issue.status = Issue.PAID_STATUS
                self.object.issue.paid = self.object.issue.bounty()
                self.object.issue.save()

            else:
                messages.error(self.request, payout.error)

        return redirect("/issue/" + str(self.object.issue.id))
Exemplo n.º 34
0
    def ready(self):
        paypal_configuration = settings.PAYMENT_PROCESSOR_CONFIG.get('paypal')
        if paypal_configuration:
            # Initialize the PayPal REST SDK
            paypalrestsdk.configure({
                'mode': paypal_configuration['mode'],
                'client_id': paypal_configuration['client_id'],
                'client_secret': paypal_configuration['client_secret']
            })

        # Register signal handlers
        # noinspection PyUnresolvedReferences
        import ecommerce.extensions.payment.signals  # pylint: disable=unused-variable
Exemplo n.º 35
0
def checkout_paypal(request, cart, orders):
    if request.user.is_authenticated():
        items = []
        total = 0
        for order in orders:
            total += (order.book.price * order.quantity)
            book = order.book
            item = {
                'name':book.title,
                'sku':book.id,
                'price':str(book.price),
                'currency':'GBP',
                'quantity':order.quantity
            }
            items.append(item)

        paypalrestsdk.configure({
            'mode':'sandbox',
            'client_id':'AYB72SUgcUpkOm0lUHPIj2J6V4BL25MDp3NGdECO7zNTePbJw1Y7s6SMwtIdnNr5GNWnTMqqTsbtomST',
            'client_secret':'EPdg4NBSC7Z-Bca6xFFCN6hBkPiOINrpbjAUPuyaQCk205h1EfuryBHt66qTQKiEpflky0fWWRWkNz9y'
        })

        payment = paypalrestsdk.Payment({
            "intent":"sale",
            "payer":{
                "payment_method":"paypal"
            },
            "redirect_urls":{
                "return_url":"http://127.0.0.1:8000/store/process/paypal",
                "cancel_url":"http://127.0.0.1:8000/store"
            },
            "transactions":[{
                "item_list":{"items":items},
                "amount":{
                    "total":str(total),
                    "currency":"GBP"
                },
                "description":"Books order."
            }] })
        if payment.create():
            cart_instance = cart.get()
            cart_instance.payment_id = payment.id
            cart_instance.save()
            for link in payment.links:
                if link.method == "REDIRECT":
                    redirect_url = str(link.href)
                    return redirect_url
        else:
            return reverse('order_error')
    else:
        return redirect('index')
Exemplo n.º 36
0
    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 __init__(self, provider='gocardless', style='payment', mode='sandbox'):
        self.provider = provider
        self.environment = int(mode=='production')
        self.provider_id = PROVIDER_ID.get(provider)

        if provider == 'paypal':
            paypal.configure(**settings.payment_providers[provider]['credentials'])
            print(settings.payment_providers[provider]['credentials'])
            return

        #~ environment = int('production' = settings.payment_providers[provider]['environment'])
        gocardless.environment = settings.payment_providers[provider]['environment']
        gocardless.set_details(**settings.payment_providers[provider]['credentials'])
        merchant = gocardless.client.merchant()
Exemplo n.º 38
0
    def setUpClass(cls):
        """
        Class set up - setting static up paypal sdk configuration to be used in test methods
        """
        super(PaypalTests, cls).setUpClass()  # required to pass CI build

        # The test uses objects from paypalrestsdk classes extensively, and those classes require
        # paypal configuration to be passed either globally (via paypalrestsdk.configure) or as a parameter
        # to object constructor (api=..., as in Paypal payment processor class)
        paypal_configuration = settings.PAYMENT_PROCESSOR_CONFIG['edx']['paypal']
        paypalrestsdk.configure({
            'mode': paypal_configuration['mode'],
            'client_id': paypal_configuration['client_id'],
            'client_secret': paypal_configuration['client_secret']
        })