def __init__(self, gateway): self.gateway = gateway self.mode = 'sandbox' if gateway.is_sandbox else 'live' params = dict( (param.name, param.value) for param in self.gateway.params.all()) if 'client_id' in params and params['client_id']: client_id = params['client_id'] else: raise ImproperlyConfigured( '"client_id" parameter not configured for PayPal gateway %s.' % self.gateway.account) if 'client_secret' in params and params['client_secret']: client_secret = params['client_secret'] else: raise ImproperlyConfigured( '"client_secret" parameter not configured for PayPal gateway %s.' % self.gateway.account) self.api = paypalrestsdk.Api({ 'mode': self.mode, 'client_id': client_id, 'client_secret': client_secret })
def _get_connection(self): account = self._get_account() params = account.get_data() experience_profile = params.pop("experience_profile_id", None) params['client_secret'] = account.get_password() # create_profile(paypal) return paypalrestsdk.Api(params), experience_profile
def execute_transaction(self, paid_payment_details): try: payee_client_api = paypalrestsdk.Api({ 'mode': MODE, 'client_id': self.boto_utils.get_ssm_parameter(PAYPAL_CLIENT), 'client_secret': self.boto_utils.get_ssm_parameter(PAYPAL_SECRET) }) except Exception as e: logger.error("Failed to get ssm parameters") raise e paypal_payment_id = self._payment_details["payment_id"] payer_id = paid_payment_details["payer_id"] payment = paypalrestsdk.Payment.find(paypal_payment_id, api=payee_client_api) if payment.execute({"payer_id": payer_id}): logger.info(f"Paypal payment execution is success for paypal_payment_id:{paypal_payment_id}") self._payment_status = PaymentStatus.SUCCESS return True elif self._payment_status == PaymentStatus.PENDING: logger.info(f"Paypal payment execution is failed for paypal_payment_id:{paypal_payment_id}") self._payment_status = PaymentStatus.FAILED logger.error(payment.error) return False
def get_paypal_api(cls): api = paypalrestsdk.Api({ 'mode': settings.SHOP_PAYPAL['MODE'], 'client_id': settings.SHOP_PAYPAL['CLIENT_ID'], 'client_secret': settings.SHOP_PAYPAL['CLIENT_SECRET'], }) return api
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})
def __init__(self, mode): self._mode = mode self._api = paypalrestsdk.Api({ "mode": mode, # noqa "client_id": settings.PAYPAL_CLIENT_ID, "client_secret": settings.PAYPAL_CLIENT_SECRET })
def paypal_api(self): """ Returns Paypal API instance with appropriate configuration Returns: Paypal API instance """ return paypalrestsdk.Api({ 'mode': self.configuration['mode'], 'client_id': self.configuration['client_id'], 'client_secret': self.configuration['client_secret'] })
def __init__(self, payment_id, amount, currency, payment_status, created_at, payment_details): super().__init__(payment_id, amount, currency, payment_status, created_at, payment_details) try: self.payee_client_api = paypalrestsdk.Api({ 'mode': MODE, 'client_id': get_ssm_parameter(PAYPAL_CLIENT), 'client_secret': get_ssm_parameter(PAYPAL_SECRET)} ) except Exception as e: logger.error("Failed to get ssm parameters") raise e
def __init__(self, mode, client_id, client_secret): """ 配置指定的PayPal APP :param mode: 这个APP的模式("live"或者"sandbox") :param client_id: APP的client_id :param client_secret: APP的client_secret """ # 配置指定的PayPal APP self.api = paypalrestsdk.Api({ "mode": mode, "client_id": client_id, "client_secret": client_secret })
def _generar_pago_paypal(self, shopping_cart): my_api = paypalrestsdk.Api({ 'mode': 'sandbox', 'client_id': settings.PAYPAL_CLIENT_ID, 'client_secret': settings.PAYPAL_CLIENT_SECRET }) pago_paypal = paypalrestsdk.Payment(self._generar_peticion_pago_paypal(shopping_cart), api = my_api) if pago_paypal.create(): for link in pago_paypal.links: if link.method == 'REDIRECT': url_pago = link.href else: raise Exception(pago_paypal.error) return url_pago, pago_paypal
def __init__(self, token, sandbox=False, return_url="http://localhost:3000/payment/execute", cancel_url="http://localhost:3000/payment/cancel", fablab_name="Technistub"): self.token = token self.fablab_name = fablab_name self.return_url = return_url self.cancel_url = cancel_url self.api = paypalrestsdk.Api({ 'mode': 'sandbox' if sandbox else 'live', 'client_id': self.token.id, 'client_secret': self.token.secret }) print('sandbox' if sandbox else 'live')
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
def initiate_payment(self, order_id, item_details): try: payee_client_api = paypalrestsdk.Api({ 'mode': MODE, 'client_id': self.boto_utils.get_ssm_parameter(PAYPAL_CLIENT), 'client_secret': self.boto_utils.get_ssm_parameter(PAYPAL_SECRET) }) except Exception as e: logger.error("Failed to get ssm parameters") raise e paypal_payload = self.get_paypal_payload(order_id, item_details["org_id"], item_details["service_id"]) payment = paypalrestsdk.Payment(paypal_payload, api=payee_client_api) if not payment.create(): logger.error(f"Paypal error:{payment.error}") raise Exception("Payment failed to create") logger.info(f"Paypal payment initiated with paypal_payment_id: {payment.id}") approval_url = "" for link in payment.links: if link.rel == "approval_url": approval_url = str(link.href) if len(approval_url) == 0: raise Exception("Payment link not found") self._payment_details["payment_id"] = payment.id response_payload = { "payment": { "id": payment.id, "payment_url": approval_url } } return response_payload
from parties import partyHandling from bids.models import Bid from parties.models import Party from accounts.models import UserProfile from apogee1.utils.auth.auth import get_blocking_lists from .pagination import StandardResultsPagination from .serializers import PartyModelSerializer from paypalrestsdk.notifications import WebhookEvent from decouple import config import paypalrestsdk logger = logging.getLogger(__name__) paypal_api = paypalrestsdk.Api({ 'mode': config("PAYPAL_ENV", default="sandbox"), 'client_id': config("PAYPAL_CLIENT_ID"), 'client_secret': config("PAYPAL_CLIENT_SECRET") }) class PaypalVerificationAPI(APIView): """ This function acts as an endpoint for the Paypal Webhook https://developer.paypal.com/docs/integration/direct/webhooks/ that handles the PAYMENT.SALE.COMPLETED event, the event that shows when a payment has completed. """ @csrf_exempt def post(self, request, format=None): # Webhook headers transmission_id = request.META.get("HTTP_PAYPAL_TRANSMISSION_ID")
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
def process_payment(request): print('a') try: gateway = Gateway.objects.get(name='PP') mode = 'sandbox' if gateway.is_sandbox else 'live' params= dict((param.name,param.value) for param in gateway.params.all()) if 'client_id' in params and params['client_id']: client_id = params['client_id'] print('d') else: raise ImproperlyConfigured('"client_id" parameter not configured for Paypal gateway{}'.format(self.gateway.account)) if 'client_secret' in params and params['client_secret']: client_secret = params['client_secret'] else: raise ImproperlyConfigured('"client_secret" parameter not configured for PayPal gateway {}.'.format(self.gateway.account)) print('f') try: print('api start') api = paypalrestsdk.Api({ 'mode':mode, 'client_id':client_id, 'client_secret':client_secret }) print('api done') except Exception as e: print ('api',e) access_token = get_random_string(20) order = Order.objects.get(customer=request.user) try: payment = { 'intent':'sale', 'redirect_urls':{ 'return_url':'http://127.0.0.1/modules', 'cancel_url':'http://127.0.0.1/purchase/cancel', }, 'payer':{'payment_method':'paypal', }, 'transactions':[{ 'item_list':{ 'items':[{ 'name':str(order.membership_type), 'sku':str(order.membership_type), 'currency': 'AUD', 'quantity':1, 'price':str(order.total) }] }, 'amount':{ 'total':str(order.total), 'currency':'AUD', 'details':{ 'subtotal':str(order.total), 'tax':str(0), } }, 'description':'Payment for order #{}'.format(order.id) }], } logger.info('Processing PayPal account.', extra=payment) payment = paypalrestsdk.Payment(payment, api=api) payment_created = payment.create() except Exception as e: logger.error('Failed to process PayPal account(transaction_id:)') logger.exception(e) if payment_created: 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) print("Redirect for approval: %s" % (approval_url)) return HttpResponseRedirect(approval_url) except Exception as e: print (e)
import paypalrestsdk from paypalrestsdk import BillingPlan, BillingAgreement from ..membership.models import MembershipPlan api = paypalrestsdk.Api({ 'mode': 'sandbox', 'client_id': 'AS6BGmUdoBXLhbOva4zTlakpC6cb6IA_sovlZed-dd4BOkQZuFPtlPKn5RloYi3Zze57cIUHKmSH4EiI', 'client_secret': 'EMiyfLU4uEN_755tgdoeGOcpzghPInxYFNpqaBYQgHYSECSMZTklkHND1iqCVNcdpyEAcjydXkXc4_tI' }) def getplans(): plans = BillingPlan.all(api=api) if 'plans' in plans: return plans['plans'] else: return None def generate_billing_plan(membershipplan: MembershipPlan, replace=False): base_plan = { "name": membershipplan.name, "description": membershipplan.description, "merchant_preferences": { "auto_bill_amount": "yes", "cancel_url": "http://www.paypal.com/cancel",
def get_paypal_api(): return paypalrestsdk.Api({ 'mode': 'sandbox' if app.config["DEBUG"] else 'live', 'client_id': config["paypal-client-id"], 'client_secret': config["paypal-client-secret"] })
import paypalrestsdk my_api = paypalrestsdk.Api({ 'mode': 'sandbox', 'client_id': '...', 'client_secret': '...' }) payment = paypalrestsdk.Payment({...}, api=my_api)
from __future__ import absolute_import from django.conf import settings import paypalrestsdk from django.core.exceptions import ImproperlyConfigured if not getattr(settings, 'PAYPAL_REST_API_MODE') or \ not getattr(settings, 'PAYPAL_REST_API_CLIENT_ID') or \ not getattr(settings, 'PAYPAL_REST_API_SECRET'): raise ImproperlyConfigured("PAYPAL API is not configured perperly") api = paypalrestsdk.Api( dict( mode=settings.PAYPAL_REST_API_MODE, client_id=settings.PAYPAL_REST_API_CLIENT_ID, client_secret=settings.PAYPAL_REST_API_SECRET ) ) PAYPAL_API_DATE_FORMAT = "%Y-%m-%dT%H:%M:%SZ" __all__ = ['api', 'PAYPAL_API_DATE_FORMAT']
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")
import paypalrestsdk #configure through non-global object my_api = paypalrestsdk.Api({ 'mode': 'sandbox', 'client_id': 'AVjs9hBnsXrNRFPkf6mb_yR3LulfFCQskg4ykW5VoldpIdD5wLpG8rmVL62G', 'client_secret': 'EAow8BAohtlukqznNXFCQp5VKgVgMMZQ9PWW8SiMXw4LOcDR3vkQh8VQWKuE' }) #print my_api.get_token_hash() #get payment history payment_history = paypalrestsdk.Payment.all({"count": 10}, api=my_api) print payment_history.payments payment = paypalrestsdk.Payment( { "intent": "sale", "payer": { "payment_method": "paypal", }, "transactions": [{ "amount": { "total": "7.47", "currency": "USD", "details": { "subtotal": "7.41", "tax": "0.03",
def blockchainAjax(request): action = request.POST.get('action') result = '' import json if action == 'register': result = userRegisterAndUpdate(request) elif action == 'getKey': profile = request.user.get_profile() if profile.blockchain_wallet: result = profile.blockchain_wallet else: profile.blockchain_wallet = blockchain_user_getkey_request(request.user.username) profile.save() elif action == 'getBalance': profile = request.user.get_profile() wallet = profile.blockchain_wallet result = blockchain_user_getbalance_request(request.user.username, wallet) res = json.loads(result) if 'Balance' in res: res['BalanceDollars'] = res['Balance'] * GIFT_USD_RATE result = json.dumps(res) elif action == 'confirmGoal': project = int(request.POST.get('projectId')) try: project = PM_Project.objects.get(pk=project) goal = int(request.POST.get('goalId')) result = blockchain_goal_confirmation_request( request.user.username, project.blockchain_name, 'opengift.io:' + str(goal) ) except PM_Project.DoesNotExist: result = 'Error: Project does not exists' elif action == 'addProject': # profile = request.user.get_profile() project = int(request.POST.get('id')) name = request.POST.get('name') if name and project: try: project = PM_Project.objects.get(pk=project) if request.user.get_profile().blockchain_wallet: result = blockchain_user_newproject_request(request.user.username, name) if result == 'ok': project.blockchain_name = name project.blockchain_registered = True project.save() except PM_Project.DoesNotExist: result = 'error' elif action == 'pay': # profile = request.user.get_profile() wallet = request.POST.get('wallet') sum = request.POST.get('sum') result = blockchain_pay_request(request.user.username, wallet, sum) if result == 'ok': try: targetProfile = PM_User.objects.get(blockchain_wallet=wallet) from PManager.viewsExt.tools import emailMessage from tracker.settings import ADMIN_EMAIL mail_sender = emailMessage( 'you_got_gifts', { 'wallet': wallet, 'sum': sum, 'sender': { 'first_name': request.user.first_name, 'last_name': request.user.last_name, } }, u'You received GIFTs!' ) try: mail_sender.send([targetProfile.user.email]) mail_sender.send([ADMIN_EMAIL]) except Exception: print 'Email has not sent' except PM_User.DoesNotExist: pass elif action == 'move': # profile = request.user.get_profile() project = request.POST.get('project') qty = request.POST.get('qty') wallet = request.POST.get('wallet') result = blockchain_token_move_request(request.user.username, project, wallet, qty) elif action == 'donate': # profile = request.user.get_profile() project = request.POST.get('project') milestone = request.POST.get('milestone', None) task = request.POST.get('task', None) try: project = PM_Project.objects.get(blockchain_name=project) except PM_Project.DoesNotExist: return HttpResponse('Fatal error: projects does not exist') if milestone: try: milestone = PM_Milestone.objects.get(pk=int(milestone)) except PM_Milestone.DoesNotExist: pass if task: try: task = PM_Task.objects.get(pk=int(task)) except PM_Task.DoesNotExist: pass ref = request.COOKIES.get('ref') refUser = None if ref: try: refUser = PM_User.objects.get(blockchain_wallet=ref) except PM_User.DoesNotExist: pass qty = float(request.POST.get('qty', 0)) currency = request.POST.get('currency', 'gift') uid = request.user.id if request.user.is_authenticated() else '-1' # if request.user.is_authenticated() and request.user.get_profile().hasRole(project): # return HttpResponse('error') mtId = milestone.id if milestone else 't'+str(task.id) if task else '-1' if currency == 'gift': if refUser and refUser.id != uid: qtyRef = qty * GIFT_USD_RATE blockchain_pay_request( request.user.username, refUser.blockchain_wallet, qtyRef ) qty -= qtyRef result = donate( qty, project, request.user, milestone, None, refUser.user if refUser else None, task ) elif currency == 'btc': result = bitcoin_set_request( ':'.join( [ project.blockchain_name, str(uid), mtId, (str(refUser.id) if refUser else '0') ] ), qty ) result = json.dumps(result) elif currency == 'usd': import paypalrestsdk from tracker.settings import PAYPAL_MODE, PAYPAL_CLIENT_ID, PAYPAL_SECRET my_api = paypalrestsdk.Api({ 'mode': PAYPAL_MODE, 'client_id': PAYPAL_CLIENT_ID, 'client_secret': PAYPAL_SECRET }) payment = paypalrestsdk.Payment({ "intent": "sale", "payer": { "payment_method": "paypal"}, "redirect_urls": { "return_url": "https://opengift.io/paypal/", "cancel_url": "https://opengift.io/" }, "transactions": [{ "item_list": { "items": [{ "name": project.blockchain_name, "sku": mtId, "price": str(qty), "currency": "USD", "quantity": 1 }]}, "amount": { "total": str(qty), "currency": "USD"}, "description": "This is the payment transaction description."} ]}, api=my_api) approval_url = '' if payment.create(): 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) # result = bitcoin_set_request( # ':'.join( # [ # project.blockchain_name, # str(uid), # (str(milestone.id) if milestone else '-1'), # (str(refUser.id) if refUser else '0') # ] # ), # qty # ) result = json.dumps(approval_url) elif action == 'getRate': currency = request.POST.get('currency', None) if currency == 'btc': result = get_rate() elif currency == 'gift': result = 1.0 / GIFT_USD_RATE else: result = 'Incorrect currency' elif action == 'getProjectVals': # profile = request.user.get_profile() project = request.POST.get('pName') try: project = PM_Project.objects.get(blockchain_name=project) result = blockchain_project_getbalance_request(request.user.username, project.blockchain_name) project.blockchain_state = result project.save() except PM_Project.DoesNotExist: result = '' elif action == 'getProjectStatus': # profile = request.user.get_profile() project = request.POST.get('pName') result = blockchain_project_status_request(request.user.username, project) return HttpResponse(result)
def paypalExecute(request): import paypalrestsdk from tracker.settings import PAYPAL_MODE, PAYPAL_CLIENT_ID, PAYPAL_SECRET my_api = paypalrestsdk.Api({ 'mode': PAYPAL_MODE, 'client_id': PAYPAL_CLIENT_ID, 'client_secret': PAYPAL_SECRET }) paymentId = request.GET.get('paymentId') payerId = request.GET.get('PayerID') if paymentId and payerId: # Payment id obtained when creating the payment (following redirect) payment = paypalrestsdk.Payment.find(paymentId, api=my_api) projectName = str(payment.transactions[0].item_list.items[0].name) if projectName: if payment.execute({"payer_id": payerId}): goalId = str(payment.transactions[0].item_list.items[0].sku) milestone = None task = None if goalId != '-1': try: milestone = PM_Milestone.objects.get(pk=goalId) except (PM_Milestone.DoesNotExist, ValueError): try: task = PM_Task.objects.get(pk=int(goalId.replace('t', ''))) except PM_Task.DoesNotExist: pass ref = request.COOKIES.get('ref') refUser = None if ref: try: refUser = PM_User.objects.get(blockchain_wallet=ref) except PM_User.DoesNotExist: pass try: project = PM_Project.objects.get(blockchain_name=projectName) except PM_Project.DoesNotExist: raise Http404 qty = float(payment.transactions[0].amount.total) * 1 giftQty = round(qty / GIFT_USD_RATE) if donate( giftQty, project, request.user if request.user.is_authenticated() else None, milestone, '*****@*****.**', refUser, task ): if task: redirectUrl = '/task_detail/?number=' + str(task.number) + '&project=' + str(project.id) + '&donated=yes' else: redirectUrl = '/project/'+str(project.id)+'/public/?donated=yes' return HttpResponseRedirect(redirectUrl) else: return HttpResponse('error') else: return HttpResponse(payment.error)
PLAN = "plan" SUBSCRIPTION = 'subscription' ORDER = 'order' def mode(): if settings.DEBUG: return "sandbox" return "live" myapi = paypalrestsdk.Api({ "mode": mode(), # noqa "client_id": settings.PAYPAL_CLIENT_ID, "client_secret": settings.PAYPAL_CLIENT_SECRET }) def get_url_from(iterator, what): for link in iterator: if link['rel'] == what: return link['href'] def plus_days(count): _date = datetime.now() return _date + timedelta(days=count)