Esempio n. 1
0
    def pay_for_merchant(self, Item):
        sender_batch_id = ''.join(
            random.choice(string.ascii_uppercase) for i in range(12))

        payout = Payout({
            "sender_batch_header": {
                "sender_batch_id": sender_batch_id,
                "email_subject": "You have a payment"
            },
            "items": Item
        })

        if payout.create():
            print("payout[%s] created successfully" %
                  (payout.batch_header.payout_batch_id))

            logging.basicConfig(level=logging.INFO)
            try:
                payout_batch = Payout.find(payout.batch_header.payout_batch_id)
                return payout_batch.items[0].payout_item_id

            except ResourceNotFound as error:
                print("Web Profile Not Found")

            return 1
        else:
            print(payout.error)
            return 0
Esempio n. 2
0
def mixpay_payout(payment_list):
    
    sender_batch_id = ''.join(
        random.choice(string.ascii_uppercase) for i in range(12))
    items = []
    for i, payment in enumerate(payment_list):
        items.append({
            "recipient_type": "EMAIL",
            "amount": {
                "value": payment["amount"],
                "currency": "SGD"
            },
            "receiver": payment["email"],
            "note": payment["note"],
            "sender_item_id": "item_%d" %i,
        })        
    payout = Payout({
        "sender_batch_header": {
            "sender_batch_id": sender_batch_id,
            "email_subject": "You have a payment, powered by MixPay"
        },
        "items" : items
    })

    if payout.create():
        print("payout[%s] created successfully" % (payout.batch_header.payout_batch_id))
    else:
        print(payout.error)
Esempio n. 3
0
    def execute(self):
        if (self.paid):
            return False
        batch_id = "batch_{0}_{1}".format(
            str(self.id), str(int(round(time.time(), -1) / 10)))
        payout = Payout({
            "sender_batch_header": {
                "sender_batch_id": batch_id,
                "email_subject": "You have a payment from GambealMeal"
            },
            "items": [{
                "recipient_type":
                "EMAIL",
                "amount": {
                    "value": self.amount,
                    "currency": "USD"
                },
                "receiver":
                self.user.paypal,
                "note":
                "Thank you.",
                "sender_item_id":
                str(self.amount) + " Payout from GambealMeal"
            }]
        })

        if payout.create(sync_mode=True):
            print("payout[%s] created successfully" %
                  (payout.batch_header.payout_batch_id))
            self.paid = True
            self.save()
        else:
            print(payout.error)
Esempio n. 4
0
def create_payout(sender_batch_id, reimbursement_amount, receiver_email,
                  sender_item_id):
    configure_paypal()
    payout = Payout({
        "sender_batch_header": {
            "sender_batch_id": sender_batch_id,
            "email_subject": "You have a payment"
        },
        "items": [{
            "recipient_type": "EMAIL",
            "amount": {
                "value": str(reimbursement_amount),
                "currency": "USD"
            },
            "receiver": receiver_email,
            "note": "Thank you.",
            "sender_item_id": sender_item_id
        }]
    })

    if payout.create():
        print("Payout created successfully")
        return payout.batch_header.payout_batch_id
    else:
        print(payout.error)
        return None
Esempio n. 5
0
def pagarProductores(datosProductores, numPedido):
    paypalrestsdk.configure({
        'mode': settings.PAYPAL_MODE,  #sandbox or live
        'client_id': settings.PAYPAL_CLIENT_ID,
        'client_secret': settings.PAYPAL_CLIENT_SECRET
    })

    payout = Payout({
        "sender_batch_header": {
            "sender_batch_id": numPedido,
            "email_subject": "Tienes un pago"
        },
        "items": []
    })

    senderItemId = 1

    for email, cantidad in datosProductores.items():
        payout.items.append({
            "recipient_type": "EMAIL",
            "amount": {
                "value": cantidad,
                "currency": "EUR"
            },
            "receiver": email,
            "note": "Gracias por sus servicios.",
            "sender_item_id": "item_" + str(senderItemId)
        })
        senderItemId += 1

    if payout.create(sync_mode=False):
        print("Pago[%s] creado con éxito" %
              (payout.batch_header.payout_batch_id))
    else:
        print(payout.error)
Esempio n. 6
0
def balanceRedeem(email, amount):
    sender_batch_id = ''.join(
        random.choice(string.ascii_uppercase) for i in range(12))

    payout = Payout({
        "sender_batch_header": {
            "sender_batch_id": sender_batch_id,
            "email_subject": "ClickNWin Balance Redeeemed"
        },
        "items": [{
            "recipient_type": "EMAIL",
            "amount": {
                "value": amount,
                "currency": "EUR"
            },
            "receiver": email,
            "note": "Thank you.",
            "sender_item_id": "item_1"
        }]
    })

    if payout.create(sync_mode=True):
        return True
    else:
        return False
Esempio n. 7
0
def pay(amt, note, receiver_email, sender_email):	
	configure()
	sender_batch_id = ''.join(random.choice(string.ascii_uppercase) for x in range(12))
	jsn = {
		"sender_batch_header": {
            	"sender_batch_id": "",
				"sender": "",
            	"email_subject": "You have a payment"
        },
        "items": [
            {
                "recipient_type": "EMAIL",
                "amount": {
                    "value": "",
                    "currency": "USD"
                },
                "receiver": "",
                "note": "",
                "sender_item_id": "item_1"
            }    
		]
	} 
	jsn["sender_batch_header"]["sender"] = sender_email
	jsn["sender_batch_header"]["sender_batch_id"] = sender_batch_id
	jsn["items"][0]["amount"]["value"] = float(amt)
	jsn["items"][0]["receiver"] = receiver_email
	jsn["items"][0]["note"] = note

	payout = Payout(jsn)

	if payout.create(sync_mode=True):
		return True
	else:
		print(payout.error)
		return False
Esempio n. 8
0
def paypal_payout(song_id, pp_transaction_id):
	# Look up transaction info
	response = get_order_details(pp_transaction_id)
	if response.status_code != 200:
		return 'Error'

	transaction = json.loads(response.content.decode('utf-8'))
	if transaction.status != "COMPLETED":
		return

	amount = transaction['purchase_units'][0]['amount']['value']

	# Payout
	ts = time.time()
	timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d%H%M%S')
	sender_batch_id = 'Payouts_' + timestamp

	song = app.db.Songs.find_one({'song_id': song_id}, {'_id': False})
	song_title = song.song_title

	if len(song.performer_known_as) > 0:
		song_artist = song.performer_known_as
	else:
		song_artist = song.song_writer

	user_to_pay = app.db.User.find_one({ 'user_id': song.user_id }, {'_id': False})
	email_address = user_to_pay.email

	paypalrestsdk.configure({
	        "mode": app.paypal_mode, # sandbox or live
	        "client_id": app.paypal_username,
	        "client_secret": app.paypal_password
	})

	payout = Payout({
		"sender_batch_header": {
			"sender_batch_id": sender_batch_id,
			"email_subject": "Someone purchased your song on RAIDAR!",
			"email_message": "Someone purchased a license to your song '" + song_title + "' by '" + song_artist + "' through the RAIDAR app. You can claim your payout through the link in this email. If you do not have a PayPal account associated with this email address, you will be prompted to create one. Thanks for using RAIDAR!"
			},
			"items": [
				{
				  "recipient_type": "EMAIL",
				  "amount": {
				    "value": amount,
				    "currency": "USD"
				  },
				  "receiver": email_address,
				  "note": "Thanks for using RAIDAR!",
				  "sender_item_id": song_id + '_' + timestamp,
				}
			]
	})

	if payout.create(sync_mode=False):
		# print("payout[%s] created successfully" %
		# (payout.batch_header.payout_batch_id))
		return payout.batch_header.payout_batch_id
	else:
		return payout.error
Esempio n. 9
0
def paypal_payment(request):
	data = {}
	logger.info("pp")
	if request.method == "POST":
		try:
			
			my_api = paypalrestsdk.Api({
				'mode': 'sandbox',
				'client_id': settings.PAYPAL_CLIENT_ID,
				'client_secret': settings.PAYPAL_CLIENT_SECRET})

			access_token = my_api.get_access_token()
			#logger.info("token %s" % access_token)
			
			batchId = request.POST.get("batchId")

			if batchId:
				resp = Payout.find(batchId, my_api)
				data["successMsg"] = resp["items"]

			else:
				emails = request.POST.get("email").split(',')
				amounts = request.POST.get("amount").split(',')
				items = []
				i = 0
				for email in emails:
					item ={
						"recipient_type": "EMAIL",
						"amount": {
							"value": amounts[i],
							"currency": "USD"
						},
						"receiver": email,
						"note": "Thank you.",
						"sender_item_id": "item_" + str(i)
					}
					items.append(item)
					i = i + 1
				
				payout = Payout({
					"sender_batch_header": {
					"sender_batch_id": "batch_2",
					"email_subject": "You have a payment"
					},
					

					"items": items
				}, api=my_api)

				if payout.create(sync_mode=False):
					data["successMsg"] = "You've successfully sent a payout, batch id: " + payout.batch_header.payout_batch_id
				else:
					logger.info(payout.error)
					data["message"] = payout.error
		except Exception as e:
			logger.info(e)
			data["message"] =	"Something went wrong."

	return render(request, "paypalTest.html", {'data': data})
Esempio n. 10
0
    def request(self):
        receiver = (
            PAYPAL_PAYOUT_RECIPIENT if PAYPAL_PAYOUT_RECIPIENT
            else self.claim.user.email
        )
        paypal_fee = PayoutFee(
            payout=self,
            fee_type='PayPal',
            amount=Decimal('0.25')
        )
        paypal_fee.save()

        codesy_fee = PayoutFee(
            payout=self,
            fee_type='codesy',
            amount=self.amount * Decimal('0.025'),
        )
        codesy_fee.save()

        total_fees = paypal_fee.amount + codesy_fee.amount
        self.charge_amount = self.amount - total_fees
        self.save()
        # attempt paypal payout
        # user generated id sent to paypal is limited to 30 chars
        sender_id = self.short_key()
        paypal_payout = PaypalPayout({
            "sender_batch_header": {
                "sender_batch_id": sender_id,
                "email_subject": "Your codesy payout is here!"
            },
            "items": [
                {
                    "recipient_type": "EMAIL",
                    "amount": {
                        "value": int(self.charge_amount),
                        "currency": "USD"
                    },
                    "receiver": receiver,
                    "note": "Here's your payout for fixing an issue.",
                    "sender_item_id": sender_id
                }
            ]
        })
        try:
            payout_attempt = paypal_payout.create(sync_mode=True)
        except:
            payout_attempt = False

        if payout_attempt:
            if paypal_payout.items:
                for item in paypal_payout.items:
                    if item.transaction_status == "SUCCESS":
                        self.api_success = True
                        self.confirmation = item.payout_item_id
                        self.save()
                    else:
                        payout_attempt = False
        return payout_attempt
Esempio n. 11
0
def paypalConfirmed(username, email, uid, exactRequestDate):
    paypalrestsdk.configure({
        "mode": "sandbox",
        "client_id": "",
        "client_secret": ""
    })
    '''
    url = 'https://api.paypal.com/v1/payments/payouts?sync_mode=false'
    header = {
        'Accept': 'application/json',
        'Authorization': 'Bearer ' + getAccessToken(),
        'Content-Type': 'application/json'
    }
    '''
    sender_batch_id = ''.join(
        random.SystemRandom().choice(string.ascii_uppercase + string.digits)
        for _ in range(8))
    payout = Payout({
        "sender_batch_header": {
            "sender_batch_id":
            sender_batch_id,
            "email_subject":
            "Click Clash: You have a payment!",
            "email_message":
            "This is a cashout prize for: " + username +
            ". Your User ID is: " + uid + ". This was sent on " +
            exactRequestDate + "."
        },
        "items": [{
            "recipient_type": "EMAIL",
            "amount": {
                "value": 5.00,
                "currency": "USD"
            },
            "receiver": email,
            "note":
            "Thank you and enjoy your prize! Email [email protected] for disputes.",
            "sender_item_id": "Standard Cashout"
        }]
    })
    if payout.create(sync_mode=False):
        print("payout[%s] created successfully" %
              (payout.batch_header.payout_batch_id))
        paymentHistory = open("payouthistory.txt", "a")
        paymentHistory.write("Username: "******"\n")
        paymentHistory.write("UID: " + uid + "\n")
        paymentHistory.write("Email: " + email + "\n")
        paymentHistory.write("Date: " + exactRequestDate + "\n")
        paymentHistory.write("Batch ID: " + sender_batch_id + "\n")
        paymentHistory.write("Other: " + payout.batch_header.payout_batch_id +
                             "\n")
        paymentHistory.write("--------------------------------------------" +
                             "\n")
        paymentHistory.close()
        return True
    else:
        print(payout.error)
        return False
Esempio n. 12
0
def paypal_payout_release(items):
    items = items

    payout = Payout({
        "sender_batch_header": {
            "sender_batch_id": sender_batch_id,
            "email_subject": "You have a payment"
        },
        "items":items
    })

    if payout.create(sync_mode=False):
        print("payout[%s] created successfully" %
            (payout.batch_header.payout_batch_id))
    else:
        print(payout.error)
Esempio n. 13
0
def payout_to_courier(modeladmin, request, queryset):
    payout_items = []
    transaction_querysets = []

    # Step 1 - Get all the valid couriers in queryset
    for courier in queryset:
        if courier.paypal_email:
            courier_in_transactions = Transaction.objects.filter(
                job__courier=courier, status=Transaction.IN_STATUS)

            if courier_in_transactions:
                transaction_querysets.append(courier_in_transactions)
                balance = sum(i.amount for i in courier_in_transactions)
                payout_items.append({
                    "recipient_type": "EMAIL",
                    "amount": {
                        "value": "{:.2f}".format(balance * 0.8),
                        "currency": "USD"
                    },
                    "receiver": courier.paypal_email,
                    "note": "Thank you.",
                    "sender_item_id": str(courier.id)
                })

    # Step 2 - Send payout batch + email to receivers
    sender_batch_id = ''.join(
        random.choice(string.ascii_uppercase) for i in range(12))
    payout = Payout({
        "sender_batch_header": {
            "sender_batch_id": sender_batch_id,
            "email_subject": "You have a payment"
        },
        "items": payout_items
    })

    # Step 3 - Execute Payout process and Update transactions' status to "OUT" if success
    try:
        if payout.create():
            for t in transaction_querysets:
                t.update(status=Transaction.OUT_STATUS)
            messages.success(
                request, "payout[%s] created successfully" %
                (payout.batch_header.payout_batch_id))
        else:
            messages.error(request, payout.error)
    except Exception as e:
        messages.error(request, str(e))
Esempio n. 14
0
def batch_pay(payList):

	items = []
	i = 0
	data = {}
	data["success"] = False

	my_api = paypalrestsdk.Api({
			'mode': 'sandbox',
			'client_id': settings.PAYPAL_CLIENT_ID,
			'client_secret': settings.PAYPAL_CLIENT_SECRET})
	access_token = my_api.get_access_token()
	batch = str(datetime.datetime.now())

	for pay_item in payList:
		item ={
			"recipient_type": "EMAIL",
			"amount": {
				"value": str(pay_item["amount"]),
				"currency": "USD"
			},
			"receiver": pay_item["email"],
			"note": "Thank you.",
			"sender_item_id": "item_" + str(i)
		}
		items.append(item)
		i = i + 1
	
	payout = Payout({
		"sender_batch_header": {
		"sender_batch_id": "batch_" + batch,
		"email_subject": "You have a payment"
		},
		

		"items": items
	}, api=my_api)

	if payout.create(sync_mode=False):
		data["successMsg"] = "You've successfully sent a payout, batch id: " + payout.batch_header.payout_batch_id
		data["success"] = True
		data["batch_id"]  =payout.batch_header.payout_batch_id
	else:
		logger.info(payout.error)
		data["message"] = payout.error
	return data
Esempio n. 15
0
def create(batch):
    with PayPalClient():
        try:
            payout = Payout(batch.batch_body)
            if payout.create():
                batch.payout_batch_id = payout.batch_header.payout_batch_id
                batch.save()
                return {
                    'status': 'Success',
                    'payout_batch_id': payout.batch_header.payout_batch_id
                }
            else:
                return {
                    'status': 'Failed',
                    'error_level': 'local',
                    'error': payout.error
                }
        except Exception as e:
            return {'status': 'Failed', 'error_level': 'global', 'error': e}
Esempio n. 16
0
def ride_payout(ride):
    payout = Payout({
        "sender_batch_header": {
            "sender_batch_id":
            "{0}_ride_{1}".format(settings.PAYPAL_BATCH_PREFIX, ride.pk),
            "email_subject":
            "You have a payout"
        },
        "items": [{
            "recipient_type":
            "EMAIL",
            "amount": {
                "value": '{0:.2f}'.format(ride.total_for_driver),
                "currency": "USD"
            },
            "receiver":
            ride.car.owner.paypal_account,
            "note":
            "The payout for the ride {0}. Thank you.".format(ride),
            "sender_item_id":
            "ride_{0}".format(ride.pk)
        }]
    })

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

    send_mail(
        'email_driver_ride_payout', [ride.car.owner.email], {
            'ride': ride,
            'ride_detail': settings.RIDE_DETAIL_URL.format(ride_pk=ride.pk)
        })

    if ride.car.owner.sms_notifications:
        send_sms(
            'sms_driver_ride_payout', [ride.car.owner.normalized_phone], {
                'ride': ride,
                'ride_detail': settings.RIDE_DETAIL_URL.format(ride_pk=ride.pk)
            })
Esempio n. 17
0
def donate_to_charity(charity_name):
    donation_val = 1.00
    msg_file = open("notification.txt", "wb")
    charity_name = charity_name.lower().replace(" ", "") + "@mail.com"
    paypalrestsdk.configure({
        "mode": "sandbox",  # sandbox or live
        "client_id": "",
        "client_secret": ""
    })

    sender_batch_id = ''.join(
        random.choice(string.ascii_uppercase) for i in range(12))

    payout = Payout({
        "sender_batch_header": {
            "sender_batch_id": sender_batch_id,
            "email_subject": "Sending a donation"
        },
        "items": [{
            "recipient_type": "EMAIL",
            "amount": {
                "value": donation_val,
                "currency": "USD"
            },
            "receiver": charity_name,
            "note": "#GAMEFORGOOD",
            "sender_item_id": "VHJ45GR"
        }]
    })

    if payout.create(sync_mode=False):
        print("payout[%s] created successfully" %
              payout.batch_header.payout_batch_id)
        #msg_file.write(bytes("You've donated $" + str(donation_val) + "to" + charity_name, 'UTF-8'))

    else:
        print(payout.error)
 def _check_payout(self, payout):
     try:
         pay = Payout.find(payout["batch_header"]["payout_batch_id"])
         status = pay["batch_header"]["batch_status"]
         self._update_status(pay)
         if status == "DENIED":
             return False
         if status == "SUCCESS":
             self._payout_success(pay)
             return False
         if pay["batch_header"]["batch_status"] in ["PENDING", "PROCESSING"]:
             return True
         return False
     except Exception:
         return False
Esempio n. 19
0
 def _check_payout(self, payout):
     try:
         pay = Payout.find(payout['batch_header']['payout_batch_id'])
         status = pay['batch_header']['batch_status']
         self._update_status(pay)
         if status == 'DENIED':
             return False
         if status == 'SUCCESS':
             self._payout_success(pay)
             return False
         if pay['batch_header']['batch_status'] in [
                 'PENDING', 'PROCESSING'
         ]:
             return True
         return False
     except Exception:
         return False
Esempio n. 20
0
payout = Payout({
    "sender_batch_header": {
        "sender_batch_id": sender_batch_id,
        "email_subject": "You have a payment"
    },
    "items": [
        {
            "recipient_type": "EMAIL",
            "amount": {
                "value": 0.99,
                "currency": "USD"
            },
            "receiver": "*****@*****.**",
            "note": "Thank you.",
            "sender_item_id": "item_1"
        },
        {
            "recipient_type": "EMAIL",
            "amount": {
                "value": 0.90,
                "currency": "USD"
            },
            "receiver": "*****@*****.**",
            "note": "Thank you.",
            "sender_item_id": "item_2"
        },
        {
            "recipient_type": "EMAIL",
            "amount": {
                "value": 2.00,
                "currency": "USD"
            },
            "receiver": "*****@*****.**",
            "note": "Thank you.",
            "sender_item_id": "item_3"
        }
    ]
})
from paypalrestsdk import Payout, ResourceNotFound
import random
import string

sender_batch_id = ''.join(
    random.choice(string.ascii_uppercase) for i in range(12))

payout = Payout({
    "sender_batch_header": {
        "sender_batch_id": sender_batch_id,
        "email_subject": "You have a payment"
    },
    "items": [
        {
            "recipient_type": "EMAIL",
            "amount": {
                "value": 0.99,
                "currency": "USD"
            },
            "receiver": "*****@*****.**",
            "note": "Thank you.",
            "sender_item_id": "item_1"
        }
    ]
})

if payout.create(sync_mode=True):
    print("payout[%s] created successfully" %
          (payout.batch_header.payout_batch_id))
else:
    print(payout.error)
Esempio n. 22
0
def paypal_payment_api(request):
	data = {}

	try:
		key = request.GET.get("api_key")
		logger.info(request.GET)
		secret = request.GET.get("api_secret")
		logger.info("secret %s" % secret)
		user_id = request.GET.get("user_id")
		#logger.info("here id: %s" % request)
		app = App.objects.get(api_key = key)
		user = User.objects.get(pk=user_id)
		"""
		if app:
			app = app[0]
		"""
		logger.info("app key: %s" % app.api_secret )
		#it sends encoded alreadyhere

		if not app.api_secret == secret:
			logger.info("here")
			data["success"] = False
			data["message"] = "Authentication failed."
			return HttpResponse(json.dumps(data), content_type="application/json")
		#user = User.objects.get(pk=user_id)
		#account = Account.objects.get(user = user_id)
		available = Ledger.objects.filter(user=user_id, payout__isnull=False, payment=None)
		balance = available.aggregate(Sum('amount'))["amount__sum"]
		if not user.paypal_email:
			data["success"] = False
			data["message"] = ("You do not have a paypal email setup")

			return HttpResponse(json.dumps(data), content_type="application/json")

		if balance > 0:

			my_api = paypalrestsdk.Api({
			'mode': 'sandbox',
			'client_id': settings.PAYPAL_CLIENT_ID,
			'client_secret': settings.PAYPAL_CLIENT_SECRET})
			access_token = my_api.get_access_token()	

			item ={
				"recipient_type": "EMAIL",
				"amount": {
				"value": str(balance),
				"currency": "USD"
			},
				"receiver": user.paypal_email,
				"note": "Thank you.",
				"sender_item_id": "item_1" 
			}

			payout = Payout({
				"sender_batch_header": {
				"sender_batch_id": "batch_" + user_id + str(datetime.datetime.now()),
				"email_subject": "You have a payment"
			},


				"items": [item]
			}, api=my_api)

			p_logger.info("sending: %s" % item )

			if payout.create(sync_mode=False):
				data["success"] = True
				
				p_logger.info("returned: %s" % payout)
				#add payment history in log
				pay = Payment.objects.create(amount = balance, platform="PayPal")
				available.update(payment = pay)
				data["message"] = "Your payment was successful, payment id: " + str(pay.id)
				#zero out account
				#account.balance = 0
				#account.save()
				total =  Ledger.objects.filter(user=user_id, payment=None)
				totalMon = total.aggregate(Sum('amount'))["amount__sum"]
				if not totalMon:
					data["total"] = "0"
				else:
					data["total"] =  str(totalMon)
				data["paidAmount"] = str(balance)
			else:
				data["success"] = False
				data["message"] = "Payment failed."
		else:
			data["success"] = False
			data["message"] = ("You have no available rewards to redeem")

	except Exception as e:
		logger.info(e)
		data["success"] = False
		data["message"] = ("There was a problem. % s" % e)

	return HttpResponse(json.dumps(data), content_type="application/json")
Esempio n. 23
0
from paypalrestsdk import Payout, ResourceNotFound
import logging
logging.basicConfig(level=logging.INFO)

try:
    payout = Payout.find("R3LFR867ESVQY")
    print("Got Details for Payout[%s]" % (payout.batch_header.payout_batch_id))

except ResourceNotFound as error:
    print("Web Profile Not Found")
Esempio n. 24
0
    "client_secret": "EO422dn3gQLgDbuwqTjzrFgFtaRLRR5BdHEESmha49TM"})

sender_batch_id = ''.join(
    random.choice(string.ascii_uppercase) for i in range(12))


def adminrelease(transaction)
    payout = Payout({
        "sender_batch_header": {
            "sender_batch_id": sender_batch_id,
            "email_subject": "You have a payment"
        },
        "items": [
            {
                "recipient_type": "EMAIL",
                "amount": {
                    "value": transaction.recipient_share,
                    "currency": "USD"
                },
                "receiver": transaction.recipient.paypal_email,
                "note": "Thank you.",
                "sender_item_id": "item_1"
            }
        ]
    })
    if payout.create():
        print("payout[%s] created successfully" %
              (payout.batch_header.payout_batch_id))
        transaction.released = True
        transaction.save()
    else:
        print(payout.error)
Esempio n. 25
0
from paypalrestsdk import Payout, ResourceNotFound
import logging
logging.basicConfig(level=logging.INFO)

try:
    payout = Payout.find("R3LFR867ESVQY")
    print(("Got Details for Payout[%s]" % (payout.batch_header.payout_batch_id)))

except ResourceNotFound as error:
    print("Web Profile Not Found")
Esempio n. 26
0
def withdraw_balance():

    form = WithdrawForm()

    if form.validate_on_submit():

        withdraw_data = {
            'steamid': current_user.id,
            'deduct_balance': form.balance.data
        }

        resp = send_post_request({}, json.dumps(withdraw_data),
                                 'user/balance/deduct')

        if resp.status_code == 200:

            purchase_data = {
                'note':
                'Withdrawal Payment Email: {0}'.format(form.email.data),
                'owner': os.environ['admin_steamid'],
                'buyer': current_user.id,
                'price': form.balance.data
            }

            send_post_request({}, json.dumps(purchase_data), 'purchase/add')

            payout = Payout({
                "sender_batch_header": {
                    "sender_batch_id":
                    "batch_id_{0}".format(random.randint(0, 9999999999999999)),
                    "email_subject":
                    "Balance withdrawal"
                },
                "items": [{
                    "recipient_type": "EMAIL",
                    "amount": {
                        "value": form.balance.data,
                        "currency": "USD"
                    },
                    "receiver": form.email.data,
                    "note": "Thanks for using RankShop.",
                    "sender_item_id": "Balance payout"
                }]
            })

            if payout.create():
                return 'Payment successfully created'
            else:
                send_put_request({},
                                 json.dumps({
                                     'receiver': current_user.id,
                                     'amount': form.balance.data / 0.8
                                 }), 'balance/give')
                return 'Failed to create payment'

        else:
            abort(resp.status_code)

    else:

        resp = send_get_request({'steamid': current_user.id}, 'user/get')

        if resp.status_code != 200:
            abort(resp.status_code)

        balance = resp.json()['balance']

        return render_template('other/withdraw.html',
                               balance=balance,
                               form=form)
Esempio n. 27
0
    def request_payout(self):
        if self.status == 'Paid':
            return False

        bid = Bid.objects.get(url=self.issue.url, user=self.user)

        codesy_payout = Payout(
            user=self.user,
            claim=self,
            amount=bid.ask,
        )
        codesy_payout.save()

        paypal_fee = PayoutFee(
            payout=codesy_payout,
            fee_type='PayPal',
            amount=Decimal('0.25')
        )
        paypal_fee.save()

        codesy_fee = PayoutFee(
            payout=codesy_payout,
            fee_type='codesy',
            amount=bid.ask * Decimal('0.025'),
        )
        codesy_fee.save()

        total_fees = paypal_fee.amount + codesy_fee.amount
        codesy_payout.amount = codesy_payout.amount - total_fees
        codesy_payout.save()
        # attempt paypay payout
        # paypal id are limited to 30 chars
        # TODO: Fix this potential non-unique key
        paypay_key = str(codesy_payout.transaction_key)[:30]
        paypal_payout = PaypalPayout({
            "sender_batch_header": {
                "sender_batch_id": paypay_key,
                "email_subject": "Your codesy payout is here!"
            },
            "items": [
                {
                    "recipient_type": "EMAIL",
                    "amount": {
                        "value": int(codesy_payout.amount),
                        "currency": "USD"
                    },
                    "receiver": "*****@*****.**",
                    "note": "You have a fake payment waiting.",
                    "sender_item_id": paypay_key
                }
            ]
        })
        # record confirmation in payout
        if paypal_payout.create(sync_mode=True):
            for item in paypal_payout.items:
                if item.transaction_status == "SUCCESS":
                    codesy_payout.api_success = True
                    codesy_payout.confirmation = item.payout_item_id
                codesy_payout.save()
                self.status = "Paid"
                self.save()
            return True
        else:
            return False
Esempio n. 28
0
def pay(user_id):
	data = {}
	try:
		user = User.objects.get(pk=user_id)
		#account = Account.objects.get(user = user_id)
		available = Ledger.objects.filter(user=user_id, payout__isnull=False, payment=None)
		balance = user.get_redeemable
		
		if not user.paypal_email:
			data["success"] = False
			data["message"] = ("You do not have a paypal email setup")
			return data

		if balance > 0:

			my_api = paypalrestsdk.Api({
			'mode': 'sandbox',
			'client_id': settings.PAYPAL_CLIENT_ID,
			'client_secret': settings.PAYPAL_CLIENT_SECRET})
			access_token = my_api.get_access_token()	

			item ={
				"recipient_type": "EMAIL",
				"amount": {
				"value": str(balance),
				"currency": "USD"
			},
				"receiver": user.paypal_email,
				"note": "Thank you.",
				"sender_item_id": "item_1" 
			}

			payout = Payout({
				"sender_batch_header": {
				"sender_batch_id": "batch_" + user_id + str(datetime.datetime.now()),
				"email_subject": "You have a payment"
			},


				"items": [item]
			}, api=my_api)

			p_logger.info("sending: %s" % item )

			if payout.create(sync_mode=False):
				data["success"] = True
				
				p_logger.info("returned: %s" % payout)
				#add payment history in log
				pay = Payment.objects.create(amount = balance, platform="PayPal")
				available.update(payment = pay)
				data["message"] = "Your payment was successful, payment id: " + str(pay.id)
				#zero out account
				#account.balance = 0
				#account.save()
				total =  Ledger.objects.filter(user=user_id, payment=None)
				totalMon = total.aggregate(Sum('amount'))["amount__sum"]
				if not totalMon:
					data["total"] = "0"
				else:
					data["total"] =  str(totalMon)
				data["paidAmount"] = str(balance)
			else:
				data["success"] = False
				data["message"] = "Payment failed."
		else:
			data["success"] = False
			data["message"] = ("You have no available rewards to redeem")
	except Exception as e:
		logger.info("error")
		logger.info(e)
		data["success"] = False
		data["message"] = e.message
		#pass
	return data
Esempio n. 29
0
from paypalrestsdk import Payout, ResourceNotFound
import random
import string

sender_batch_id = ''.join(
    random.choice(string.ascii_uppercase) for i in range(12))

payout = Payout({
    "sender_batch_header": {
        "sender_batch_id": sender_batch_id,
        "email_subject": "You have a payment"
    },
    "items": [{
        "recipient_type": "EMAIL",
        "amount": {
            "value": 0.99,
            "currency": "USD"
        },
        "receiver": "*****@*****.**",
        "note": "Thank you.",
        "sender_item_id": "item_1"
    }]
})

if payout.create(sync_mode=True):
    print("payout[%s] created successfully" %
          (payout.batch_header.payout_batch_id))
else:
    print(payout.error)
Esempio n. 30
0
def finishPayment(request):
    if request.method == 'GET' and 'id' in request.GET and 'sellingchoice' in request.GET and \
        'paymentId' in request.GET and 'token' in request.GET and 'PayerID' in request.GET:

        sellingchoice = request.GET['sellingchoice']
        itemid = request.GET['id']
        try:
            item = Item.objects.select_for_update().get(id=itemid)
        except:
            return render(request, 'auction/error.html',
                          {'error': 'Payment did not work'})
        #We know this will not throw and error sicne the regualr expression matches sellingchoice to an int
        sellingchoice = int(sellingchoice)
        if sellingchoice == myHash(itemid, 'buy'):
            total = item.price
        elif sellingchoice == myHash(itemid, 'bid'):
            total = item.finalPrice
        else:
            print('selling choice is wrong')
            return render(request, 'auction/error.html',
                          {'error': 'Malicious HTTP Request'})
        paymentId = request.GET['paymentId']
        token = request.GET['token']
        payerId = request.GET['PayerID']
        payment = paypalrestsdk.Payment.find(paymentId)
        payment.execute({"payer_id": payerId})
        #get rid of random nmber at end
        batchid = itemid + str(199)
        payout = Payout({
            "sender_batch_header": {
                "sender_batch_id": batchid,
                "email_subject": "You have a payment"
            },
            "items": [{
                "recipient_type": "EMAIL",
                "amount": {
                    "value": str(total),
                    "currency": "USD"
                },
                "receiver":
                "*****@*****.**",  #change reciever to be the seller
                "note": "Thank you.",
                "sender_item_id": str(itemid),
            }]
        })

        if payout.create(sync_mode=True):
            winner = request.user
            item.buyer = winner
            item.finalPrice = total
            item.boughtDate = date.today()
            item.isSold = True
            item.save()
            removeItemFromRecentlyViewed(item)
            buyerProfile = UserProfile.objects.get(user=winner)
            email_body = """You have sold %s by bid for $%s. Please send it to %s at \n %s \n %s, %s %s""" % (item.title, item.finalPrice, \
                winner, buyerProfile.address, buyerProfile.city, buyerProfile.state, buyerProfile.zipcode)
            send_mail(subject='Your bid item has been sold',
                      message=email_body,
                      from_email='*****@*****.**',
                      recipient_list=[item.seller.email])
            return redirect(reverse('home') + "?message=4")
        else:
            print('payout failed')
            return redirect(reverse('home') + "?message=5")
    else:
        return render(request, 'auction/error.html',
                      {'error': 'Payment did not work'})