def process(self, request, item): """Process a PayPal direct payment.""" from paypal.pro.helpers import PayPalWPP wpp = PayPalWPP(request) params = self.cleaned_data params['creditcardtype'] = self.fields['acct'].card_type params['expdate'] = self.cleaned_data['expdate'].strftime("%m%Y") try: params['ipaddress'] = request.META["REMOTE_ADDR"] except KeyError: params['ipaddress'] = request.META.get("HTTP_X_FORWARDED_FOR", "0:0:0:0:0:0") params.update(item) try: # Create single payment: if 'billingperiod' not in params: nvp_obj = wpp.doDirectPayment(params) # Create recurring payment: else: nvp_obj = wpp.createRecurringPaymentsProfile(params, direct=True) except PayPalFailure: return False return True
def purchase(self, money, credit_card, options=None): """Using PAYPAL DoDirectPayment, charge the given credit card for specified money""" if not options: options = {} if not self.validate_card(credit_card): raise InvalidCard("Invalid Card") params = {} params['creditcardtype'] = credit_card.card_type.card_name params['acct'] = credit_card.number params['expdate'] = '%02d%04d' % (credit_card.month, credit_card.year) params['cvv2'] = credit_card.verification_value params['ipaddress'] = options['request'].META.get("REMOTE_ADDR", "") params['amt'] = money if options.get("email"): params['email'] = options["email"] address = options.get("billing_address", {}) first_name = None last_name = None try: first_name, last_name = address.get("name", "").split(" ") except ValueError: pass params['firstname'] = first_name or credit_card.first_name params['lastname'] = last_name or credit_card.last_name params['street'] = address.get("address1", '') params['street2'] = address.get("address2", "") params['city'] = address.get("city", '') params['state'] = address.get("state", '') params['countrycode'] = address.get("country", '') params['zip'] = address.get("zip", '') params['phone'] = address.get("phone", "") shipping_address = options.get("shipping_address", None) if shipping_address: params['shiptoname'] = shipping_address["name"] params['shiptostreet'] = shipping_address["address1"] params['shiptostreet2'] = shipping_address.get("address2", "") params['shiptocity'] = shipping_address["city"] params['shiptostate'] = shipping_address["state"] params['shiptocountry'] = shipping_address["country"] params['shiptozip'] = shipping_address["zip"] params['shiptophonenum'] = shipping_address.get("phone", "") wpp = PayPalWPP(options['request']) try: response = wpp.doDirectPayment(params) transaction_was_successful.send(sender=self, type="purchase", response=response) except PayPalFailure, e: transaction_was_unsuccessful.send(sender=self, type="purchase", response=e) # Slight skewness because of the way django-paypal # is implemented. return {"status": "FAILURE", "response": e}
def recurring(self, money, creditcard, options={}): # raise NotImplementedError params = {} params['profilestartdate'] = options.get( 'startdate') or datetime.datetime.now().strftime( "%Y-%m-%dT00:00:00Z") params['startdate'] = options.get( 'startdate') or datetime.datetime.now().strftime("%m%Y") params['billingperiod'] = options.get('billingperiod') or 'Month' params['billingfrequency'] = options.get('billingfrequency') or '1' params['amt'] = money params['desc'] = 'description of the billing' params['creditcardtype'] = creditcard.card_type.card_name params['acct'] = creditcard.number params['expdate'] = '%02d%04d' % (creditcard.month, creditcard.year) params['firstname'] = creditcard.first_name params['lastname'] = creditcard.last_name wpp = PayPalWPP(options.get('request', {})) try: response = wpp.createRecurringPaymentsProfile(params, direct=True) transaction_was_successful.send(sender=self, type="purchase", response=response) except PayPalFailure, e: transaction_was_unsuccessful.send(sender=self, type="purchase", response=e) # Slight skewness because of the way django-paypal # is implemented. return {"status": "FAILURE", "response": e}
def process(self, request, item): """Process a PayPal direct payment.""" from paypal.pro.helpers import PayPalWPP wpp = PayPalWPP(request) params = self.cleaned_data params['creditcardtype'] = self.fields['acct'].card_type params['expdate'] = self.cleaned_data['expdate'].strftime("%m%Y") params['ipaddress'] = request.META.get("REMOTE_ADDR", "") params.update(item) try: # Create single payment: if 'billingperiod' not in params: nvp_obj = wpp.doDirectPayment(params) # Create recurring payment: else: if 'profileid' in params: # Updating a payment profile. nvp_obj = wpp.updateRecurringPaymentsProfile(params, direct=True) else: # Creating a payment profile. nvp_obj = wpp.createRecurringPaymentsProfile(params, direct=True) except PayPalFailure: return False return True
def recurring(self, money, creditcard, options = None): if not options: options = {} params = {} params['profilestartdate'] = options.get('startdate') or datetime.datetime.now().strftime("%Y-%m-%dT00:00:00Z") params['startdate'] = options.get('startdate') or datetime.datetime.now().strftime("%m%Y") params['billingperiod'] = options.get('billingperiod') or 'Month' params['billingfrequency'] = options.get('billingfrequency') or '1' params['amt'] = money params['desc'] = 'description of the billing' params['creditcardtype'] = creditcard.card_type.card_name params['acct'] = creditcard.number params['expdate'] = '%02d%04d' % (creditcard.month, creditcard.year) params['firstname'] = creditcard.first_name params['lastname'] = creditcard.last_name wpp = PayPalWPP(options.get('request', {})) try: response = wpp.createRecurringPaymentsProfile(params, direct=True) transaction_was_successful.send(sender=self, type="purchase", response=response) except PayPalFailure, e: transaction_was_unsuccessful.send(sender=self, type="purchase", response=e) # Slight skewness because of the way django-paypal # is implemented. return {"status": "FAILURE", "response": e}
def redirect_to_express(self): """ First step of ExpressCheckout. Redirect the request to PayPal using the data returned from setExpressCheckout. """ wpp = PayPalWPP(self.request) try: nvp_obj = wpp.setExpressCheckout(self.item) except PayPalFailure: log.exception('paypal failure') self.context['errors'] = self.errors['paypal'] return self.render_payment_form() else: pp_params = dict( token=nvp_obj.token, L_PAYMENTREQUEST_0_AMTm=self.item['PAYMENTREQUEST_0_AMT'], PAYMENTREQUEST_0_ITEMAMT=self.item['PAYMENTREQUEST_0_AMT'], PAYMENTREQUEST_0_AMT=self.item['PAYMENTREQUEST_0_AMT'], PAYMENTREQUEST_0_DESC=self.item['PAYMENTREQUEST_0_DESC'], PAYMENTREQUEST_0_CURRENCYCODE=self. item['PAYMENTREQUEST_0_CURRENCYCODE'], RETURNURL=self.item['returnurl'], CANCELURL=self.item['cancelurl']) pp_url = self.get_endpoint() % urlencode(pp_params) # log.info('redirect data: %s'% pp_url) return HttpResponseRedirect(pp_url)
def paypal_start(request): """ Creating express checkout request from users cart """ try: params = get_cart_data_from_request(request) host_name = request.get_host() params.update({ "returnurl": "http://" + host_name + "/order/paypal/confirm", "cancelurl": "http://" + host_name + "/#!/cart", "noshipping": 2, }) wpp = PayPalWPP() nvp = wpp.setExpressCheckout(params) response = HttpResponseRedirect( settings.PAYPAL_URL + '/cgi-bin/webscr?cmd=_express-checkout&token=' + nvp.token) response.delete_cookie('cart') return response except Exception, e: #log error here print e return HttpResponseRedirect("/#!/cart")
def test_doDirectPayment_authenticated_user(self): User = get_user_model() user = User.objects.create(username='******') wpp = PayPalWPP(make_request(user=user)) data = self.get_valid_doDirectPayment_data() data.update(self.item) npm_obj = wpp.doDirectPayment(data) self.assertEqual(npm_obj.user, user)
def test_doReferenceTransaction_invalid(self, mock_request_object): reference_id = 'B-1234' amount = Decimal('10.50') mock_request_object.return_value = 'ack=Failure&l_errorcode=42&l_longmessage0=Broken' wpp = PayPalWPP(REQUEST) with self.assertRaises(PayPalFailure): wpp.doReferenceTransaction({'referenceid': reference_id, 'amt': amount})
def test_doReferenceTransaction_invalid(self, mock_request_object): reference_id = 'B-1234' amount = Decimal('10.50') mock_request_object.return_value = 'ack=Failure&l_errorcode=42&l_longmessage0=Broken' wpp = PayPalWPP(make_request()) with self.assertRaises(PayPalFailure): wpp.doReferenceTransaction({'referenceid': reference_id, 'amt': amount})
def save(request): """ Direct Paypal payment with credit card """ try: cart = get_cart_data_from_request(request) if 'order' not in request.GET: raise Exception('no order data') order_json = request.GET['order'] order_json = urllib.unquote(order_json) order = json.loads(order_json) wpp = PayPalWPP() paypal_params = { 'ipaddress': request.META.get('REMOTE_ADDR'), 'creditcardtype': order['creditcardtype'], 'acct': order['acct'], 'expdate': order['cardmonth'] + order['cardyear'], 'cvv2': order['cvv2'], 'email': order['email'], 'firstname': order['card_first_name'], 'lastname': order['card_last_name'], 'street': order['b_street'], 'city': order['b_city'], 'state': order['b_state'], 'countrycode': order['b_countrycode'], 'zip': order['b_zip'], 'amt': cart['paymentrequest_0_amt'], } nvp = wpp.doDirectPayment(paypal_params) order_data = nvp.response_dict.copy() order_data.update(cart) order_data.update(order) order = create_order_from_direct_paypal(order_data) data = { 'order_id': order.id, } send_order_email(order.email, order, order.items.all) return HttpResponse(json.dumps(data), content_type='application/json') except Exception, e: print e data = { 'error': e.message } return HttpResponseServerError(json.dumps(data), content_type='application/json')
def test_doExpressCheckoutPayment_invalid(self, mock_request_object): ec_token = 'EC-1234567890' payerid = 'LXYZABC1234' item = self.ec_item.copy() item.update({'token': ec_token, 'payerid': payerid}) mock_request_object.return_value = 'ack=Failure&l_errorcode=42&l_longmessage0=Broken' wpp = PayPalWPP(make_request()) with self.assertRaises(PayPalFailure): wpp.doExpressCheckoutPayment(item)
def test_doExpressCheckoutPayment_invalid(self, mock_request_object): ec_token = 'EC-1234567890' payerid = 'LXYZABC1234' item = self.ec_item.copy() item.update({'token': ec_token, 'payerid': payerid}) mock_request_object.return_value = 'ack=Failure&l_errorcode=42&l_longmessage0=Broken' wpp = PayPalWPP(REQUEST) with self.assertRaises(PayPalFailure): wpp.doExpressCheckoutPayment(item)
def test_doDirectPayment_valid(self): wpp = PayPalWPP(make_request()) data = self.get_valid_doDirectPayment_data() data.update(self.item) nvp = wpp.doDirectPayment(data) self.assertIsNotNone(nvp) for k, v in [('avscode', 'X'), ('amt', '9.95'), ('correlationid', '1025431f33d89'), ('currencycode', 'USD'), ('ack', 'Success')]: self.assertEqual(nvp.response_dict[k], v)
def test_doReferenceTransaction_invalid(self, mock_request_object): reference_id = "B-1234" amount = Decimal("10.50") mock_request_object.return_value = "ack=Failure&l_errorcode=42&l_longmessage0=Broken" wpp = PayPalWPP(make_request()) with self.assertRaises(PayPalFailure): wpp.doReferenceTransaction({ "referenceid": reference_id, "amt": amount })
def save(request): """ Direct Paypal payment with credit card """ try: cart = get_cart_data_from_request(request) if 'order' not in request.GET: raise Exception('no order data') order_json = request.GET['order'] order_json = urllib.unquote(order_json) order = json.loads(order_json) wpp = PayPalWPP() paypal_params = { 'ipaddress': request.META.get('REMOTE_ADDR'), 'creditcardtype': order['creditcardtype'], 'acct': order['acct'], 'expdate': order['cardmonth'] + order['cardyear'], 'cvv2': order['cvv2'], 'email': order['email'], 'firstname': order['card_first_name'], 'lastname': order['card_last_name'], 'street': order['b_street'], 'city': order['b_city'], 'state': order['b_state'], 'countrycode': order['b_countrycode'], 'zip': order['b_zip'], 'amt': cart['paymentrequest_0_amt'], } nvp = wpp.doDirectPayment(paypal_params) order_data = nvp.response_dict.copy() order_data.update(cart) order_data.update(order) order = create_order_from_direct_paypal(order_data) data = { 'order_id': order.id, } send_order_email(order.email, order, order.items.all) return HttpResponse(json.dumps(data), content_type='application/json') except Exception, e: print e data = {'error': e.message} return HttpResponseServerError(json.dumps(data), content_type='application/json')
def redirect_to_express(self): """ First step of ExpressCheckout. Redirect the request to PayPal using the data returned from setExpressCheckout. """ wpp = PayPalWPP(self.request) try: nvp_obj = wpp.setExpressCheckout(self.item) except PayPalFailure: self.context['errors'] = self.errors['paypal'] return self.render_payment_form() else: return HttpResponseRedirect(express_endpoint_for_token(nvp_obj.token))
def test_createBillingAgreement(self, mock_request_object): mock_request_object.return_value = 'ack=Success&billingagreementid=B-XXXXX&version=%s' % VERSION wpp = PayPalWPP(REQUEST) nvp = wpp.createBillingAgreement({'token': 'dummy token'}) call_args = mock_request_object.call_args self.assertIn('VERSION=%s' % VERSION, call_args[0][1]) self.assertIn('METHOD=CreateBillingAgreement', call_args[0][1]) self.assertIn('TOKEN=dummy+token', call_args[0][1]) self.assertEquals(nvp.method, 'CreateBillingAgreement') self.assertEquals(nvp.ack, 'Success') mock_request_object.return_value = 'ack=Failure&l_errorcode=42&l_longmessage0=Broken' with self.assertRaises(PayPalFailure): nvp = wpp.createBillingAgreement({'token': 'dummy token'})
def test_createBillingAgreement(self, mock_request_object): mock_request_object.return_value = f"ack=Success&billingagreementid=B-XXXXX&version={VERSION}" wpp = PayPalWPP(make_request()) nvp = wpp.createBillingAgreement({"token": "dummy token"}) call_args = mock_request_object.call_args self.assertIn(f"VERSION={VERSION}", call_args[0][1]) self.assertIn("METHOD=CreateBillingAgreement", call_args[0][1]) self.assertIn("TOKEN=dummy+token", call_args[0][1]) self.assertEqual(nvp.method, "CreateBillingAgreement") self.assertEqual(nvp.ack, "Success") mock_request_object.return_value = "ack=Failure&l_errorcode=42&l_longmessage0=Broken" with self.assertRaises(PayPalFailure): nvp = wpp.createBillingAgreement({"token": "dummy token"})
def test_createBillingAgreement(self, mock_request_object): mock_request_object.return_value = 'ack=Success&billingagreementid=B-XXXXX&version=%s' % VERSION wpp = PayPalWPP(make_request()) nvp = wpp.createBillingAgreement({'token': 'dummy token'}) call_args = mock_request_object.call_args self.assertIn('VERSION=%s' % VERSION, call_args[0][1]) self.assertIn('METHOD=CreateBillingAgreement', call_args[0][1]) self.assertIn('TOKEN=dummy+token', call_args[0][1]) self.assertEqual(nvp.method, 'CreateBillingAgreement') self.assertEqual(nvp.ack, 'Success') mock_request_object.return_value = 'ack=Failure&l_errorcode=42&l_longmessage0=Broken' with self.assertRaises(PayPalFailure): nvp = wpp.createBillingAgreement({'token': 'dummy token'})
def test_doDirectPayment_valid(self): wpp = PayPalWPP(make_request()) data = self.get_valid_doDirectPayment_data() data.update(self.item) nvp = wpp.doDirectPayment(data) self.assertIsNotNone(nvp) for k, v in [ ("avscode", "X"), ("amt", "9.95"), ("correlationid", "1025431f33d89"), ("currencycode", "USD"), ("ack", "Success"), ]: self.assertEqual(nvp.response_dict[k], v)
def test_doReferenceTransaction_valid(self, mock_request_object): reference_id = 'B-1234' amount = Decimal('10.50') mock_request_object.return_value = 'ack=Success&paymentstatus=Completed&amt=%s&version=%s&billingagreementid=%s' % \ (amount, VERSION, reference_id) wpp = PayPalWPP(REQUEST) nvp = wpp.doReferenceTransaction({'referenceid': reference_id, 'amt': amount}) call_args = mock_request_object.call_args self.assertIn('VERSION=%s' % VERSION, call_args[0][1]) self.assertIn('METHOD=DoReferenceTransaction', call_args[0][1]) self.assertIn('REFERENCEID=%s' % reference_id, call_args[0][1]) self.assertIn('AMT=%s' % amount, call_args[0][1]) self.assertEqual(nvp.method, 'DoReferenceTransaction') self.assertEqual(nvp.ack, 'Success')
def test_doDirectPayment_valid_with_signal(self): wpp = PayPalWPP(make_request()) data = self.get_valid_doDirectPayment_data() data.update(self.item) self.got_signal = False self.signal_obj = None def handle_signal(sender, **kwargs): self.got_signal = True self.signal_obj = sender payment_was_successful.connect(handle_signal) self.assertTrue(wpp.doDirectPayment(data)) self.assertTrue(self.got_signal)
def redirect_to_express(self): """ First step of ExpressCheckout. Redirect the request to PayPal using the data returned from setExpressCheckout. """ wpp = PayPalWPP(self.request) nvp_obj = wpp.setExpressCheckout(self.item) if not nvp_obj.flag: pp_params = dict(token=nvp_obj.token, AMT=self.item['amt'], RETURNURL=self.item['returnurl'], CANCELURL=self.item['cancelurl']) pp_url = self.get_endpoint() % urlencode(pp_params) return HttpResponseRedirect(pp_url) else: self.context['errors'] = self.paypal_error return self.render_payment_form()
def test_doExpressCheckoutPayment(self, mock_request_object): ec_token = 'EC-1234567890' payerid = 'LXYZABC1234' item = self.ec_item.copy() item.update({'token': ec_token, 'payerid': payerid}) mock_request_object.return_value = 'ack=Success&token=%s&version=%spaymentinfo_0_amt=%s' % \ (ec_token, VERSION, self.ec_item['paymentrequest_0_amt']) wpp = PayPalWPP(REQUEST) wpp.doExpressCheckoutPayment(item) call_args = mock_request_object.call_args self.assertIn('VERSION=%s' % VERSION, call_args[0][1]) self.assertIn('METHOD=DoExpressCheckoutPayment', call_args[0][1]) self.assertIn('TOKEN=%s' % ec_token, call_args[0][1]) self.assertIn('PAYMENTREQUEST_0_AMT=%s' % item['paymentrequest_0_amt'], call_args[0][1]) self.assertIn('PAYERID=%s' % payerid, call_args[0][1])
def test_doExpressCheckoutPayment(self, mock_request_object): ec_token = 'EC-1234567890' payerid = 'LXYZABC1234' item = self.ec_item.copy() item.update({'token': ec_token, 'payerid': payerid}) mock_request_object.return_value = 'ack=Success&token=%s&version=%spaymentinfo_0_amt=%s' % \ (ec_token, VERSION, self.ec_item['paymentrequest_0_amt']) wpp = PayPalWPP(make_request()) wpp.doExpressCheckoutPayment(item) call_args = mock_request_object.call_args self.assertIn('VERSION=%s' % VERSION, call_args[0][1]) self.assertIn('METHOD=DoExpressCheckoutPayment', call_args[0][1]) self.assertIn('TOKEN=%s' % ec_token, call_args[0][1]) self.assertIn('PAYMENTREQUEST_0_AMT=%s' % item['paymentrequest_0_amt'], call_args[0][1]) self.assertIn('PAYERID=%s' % payerid, call_args[0][1])
def redirect_to_express(self): """ First step of ExpressCheckout. Redirect the request to PayPal using the data returned from setExpressCheckout. """ wpp = PayPalWPP(self.request) nvp_obj = wpp.setExpressCheckout(self.item) if not nvp_obj.flag: pp_params = dict(token=nvp_obj.token, AMT=self.item['amt'], RETURNURL=self.item['returnurl'], CANCELURL=self.item['cancelurl']) pp_url = self.get_endpoint() % urlencode(pp_params) return HttpResponseRedirect(pp_url) else: self.context['errors'] = self.errors['paypal'] return self.render_payment_form()
def test_setExpressCheckout_deprecation(self, mock_request_object): wpp = PayPalWPP(make_request()) mock_request_object.return_value = 'ack=Success&token=EC-XXXX&version=%s' item = self.ec_item.copy() item.update({'amt': item['paymentrequest_0_amt']}) del item['paymentrequest_0_amt'] with warnings.catch_warnings(record=True) as warning_list: warnings.simplefilter("always") nvp_obj = wpp.setExpressCheckout(item) # Make sure our warning was given self.assertTrue(any(warned.category == DeprecationWarning for warned in warning_list)) # Make sure the method still went through call_args = mock_request_object.call_args self.assertIn('PAYMENTREQUEST_0_AMT=%s' % item['amt'], call_args[0][1]) self.assertEqual(nvp_obj.ack, "Success")
def process(self, ipaddress, user, item): """Process a PayPal ExpressCheckout payment.""" from paypal.pro.helpers import PayPalWPP wpp = PayPalWPP(ipaddress, user) params = self.cleaned_data params.update(item) try: # Create single payment: if 'billingperiod' not in params: nvp_obj = wpp.doExpressCheckoutPayment(params) # Create recurring payment: else: nvp_obj = wpp.createRecurringPaymentsProfile(params) except PayPalFailure: return None return nvp_obj
def process(self, request, item): """Do a direct payment.""" from paypal.pro.helpers import PayPalWPP wpp = PayPalWPP(request) # Change the model information into a dict that PayPal can understand. params = model_to_dict(self, exclude=self.ADMIN_FIELDS) params['acct'] = self.acct params['creditcardtype'] = self.creditcardtype params['expdate'] = self.expdate params['cvv2'] = self.cvv2 params.update(item) # Create recurring payment: if 'billingperiod' in params: return wpp.createRecurringPaymentsProfile(params, direct=True) # Create single payment: else: return wpp.doDirectPayment(params)
def redirect_to_express(self): """ First express flow step. Redirect to PayPal with the data in tow. """ wpp = PayPalWPP(self.request) nvp_obj = wpp.setExpressCheckout(self.item) if not nvp_obj.flag: pp_params = dict(token=nvp_obj.token, AMT=self.item['amt'], RETURNURL=self.item['returnurl'], CANCELURL=self.item['cancelurl']) pp_url = SANDBOX_EXPRESS_ENDPOINT % urllib.urlencode(pp_params) return HttpResponseRedirect(pp_url) else: self.context = {'errors':'There was a problem contacting PayPal. Please try again later.'} return self.render_payment_form()
def test_doReferenceTransaction_valid(self, mock_request_object): reference_id = "B-1234" amount = Decimal("10.50") mock_request_object.return_value = ( "ack=Success&paymentstatus=Completed&amt=%s&version=%s&billingagreementid=%s" % (amount, VERSION, reference_id)) wpp = PayPalWPP(make_request()) nvp = wpp.doReferenceTransaction({ "referenceid": reference_id, "amt": amount }) call_args = mock_request_object.call_args self.assertIn(f"VERSION={VERSION}", call_args[0][1]) self.assertIn("METHOD=DoReferenceTransaction", call_args[0][1]) self.assertIn(f"REFERENCEID={reference_id}", call_args[0][1]) self.assertIn(f"AMT={amount}", call_args[0][1]) self.assertEqual(nvp.method, "DoReferenceTransaction") self.assertEqual(nvp.ack, "Success")
def process(self, request, item): """Process a PayPal direct payment.""" from paypal.pro.helpers import PayPalWPP wpp = PayPalWPP(request) params = self.cleaned_data params['creditcardtype'] = self.fields['acct'].card_type params['expdate'] = self.cleaned_data['expdate'].strftime("%m%Y") params['ipaddress'] = request.META.get("REMOTE_ADDR", "") params.update(item) # Create single payment: if 'billingperiod' not in params: response = wpp.doDirectPayment(params) # Create recurring payment: else: response = wpp.createRecurringPaymentsProfile(params, direct=True) return response
def test_doExpressCheckoutPayment(self, mock_request_object): ec_token = "EC-1234567890" payerid = "LXYZABC1234" item = self.ec_item.copy() item.update({"token": ec_token, "payerid": payerid}) mock_request_object.return_value = "ack=Success&token={}&version={}paymentinfo_0_amt={}".format( ec_token, VERSION, self.ec_item["paymentrequest_0_amt"], ) wpp = PayPalWPP(make_request()) wpp.doExpressCheckoutPayment(item) call_args = mock_request_object.call_args self.assertIn(f"VERSION={VERSION}", call_args[0][1]) self.assertIn("METHOD=DoExpressCheckoutPayment", call_args[0][1]) self.assertIn(f"TOKEN={ec_token}", call_args[0][1]) self.assertIn(f"PAYMENTREQUEST_0_AMT={item['paymentrequest_0_amt']}", call_args[0][1]) self.assertIn(f"PAYERID={payerid}", call_args[0][1])
def redirect_to_express(self): """ First step of ExpressCheckout. Redirect the request to PayPal using the data returned from setExpressCheckout. """ wpp = PayPalWPP(self.request) try: nvp_obj = wpp.setExpressCheckout(self.item) except PayPalFailure: self.context["errors"] = self.errors["paypal"] return self.render_payment_form() else: pp_params = dict( token=nvp_obj.token, AMT=self.item["amt"], RETURNURL=self.item["returnurl"], CANCELURL=self.item["cancelurl"], ) pp_url = self.get_endpoint() % urlencode(pp_params) return HttpResponseRedirect(pp_url)
def validate_confirm_form(self): """ Third and final step of ExpressCheckout. Request has pressed the confirmation but and we can send the final confirmation to PayPal using the data from the POST'ed form. """ wpp = PayPalWPP(self.request) pp_data = dict(token=self.request.POST['token'], payerid=self.request.POST['PayerID']) self.item.update(pp_data) if self.is_recurring: success = wpp.createRecurringPaymentsProfile(self.item) else: success = wpp.doExpressCheckoutPayment(self.item) if success: payment_was_successful.send(sender=self.item) return HttpResponseRedirect(self.success_url) else: self.context['errors'] = self.processing_error return self.render_payment_form()
def process(self, ipaddress, user, item): """Process a PayPal direct payment.""" from paypal.pro.helpers import PayPalWPP wpp = PayPalWPP(ipaddress, user) params = self.cleaned_data params['creditcardtype'] = self.fields['acct'].card_type params['expdate'] = self.cleaned_data['expdate'].strftime("%m%Y") params['ipaddress'] = ipaddress params.update(item) try: # Create single payment: if 'billingperiod' not in params: nvp_obj = wpp.doDirectPayment(params) # Create recurring payment: else: nvp_obj = wpp.createRecurringPaymentsProfile(params, direct=True) except PayPalFailure: return None return nvp_obj
def process(self, request, item): """Do a direct payment.""" from paypal.pro.helpers import PayPalWPP wpp = PayPalWPP(request) # Change the model information into a dict that PayPal can understand. params = model_to_dict(self, exclude=self.ADMIN_FIELDS) params["ACCT"] = self.acct params["CREDITCARDTYPE"] = self.creditcardtype params["EXPDATE"] = self.expdate params["CVV2"] = self.cvv2 params.update(item) # Create recurring payment: if "BILLINGPERIOD" in params: return wpp.createRecurringPaymentsProfile(params, direct=True) # Create single payment: else: return wpp.doDirectPayment(params)
def validate_confirm_form(self): """ Third and final step of ExpressCheckout. Request has pressed the confirmation but and we can send the final confirmation to PayPal using the data from the POST'ed form. """ wpp = PayPalWPP(self.request) pp_data = dict(token=self.request.POST['token'], payerid=self.request.POST['PayerID']) self.item.update(pp_data) # @@@ This check and call could be moved into PayPalWPP. try: if self.is_recurring(): nvp_obj = wpp.createRecurringPaymentsProfile(self.item) else: nvp_obj = wpp.doExpressCheckoutPayment(self.item) except PayPalFailure: self.context['errors'] = self.errors['processing'] return self.render_payment_form() else: return HttpResponseRedirect(self.success_url)
def process(self, request, item): """ Do a direct payment. """ from paypal.pro.helpers import PayPalWPP wpp = PayPalWPP(request) params = self.cleaned_data params["creditcardtype"] = self.fields["acct"].card_type params["expdate"] = self.cleaned_data["expdate"].strftime("%m%Y") params["ipaddress"] = request.META.get("REMOTE_ADDR", "") params.update(item) # Create single payment: if "billingperiod" not in params: response = wpp.doDirectPayment(params) # Create recurring payment: else: response = wpp.createRecurringPaymentsProfile(params, direct=True) return response
def validate_confirm_form(self): """ Final express flow step. User has pressed the confirm button and now we send it off to PayPal. """ wpp = PayPalWPP(self.request) pp_data = dict(token=self.request.POST['token'], payerid=self.request.POST['PayerID']) self.item.update(pp_data) if self.is_recurring: success = wpp.createRecurringPaymentsProfile(self.item) else: success = wpp.doExpressCheckoutPayment(self.item) if success: payment_was_successful.send(sender=self.item) return HttpResponseRedirect(self.success_url) else: self.context['errors'] = "There was a problem processing the payment. Please check your information and try again." return self.render_payment_form()
def paypal_end(request): """ Do payment and create order object in DB """ try: wpp = PayPalWPP(request) token = request.GET['token'] params = {"token": token} nvp = wpp.getExpressCheckoutDetails(params) order_dict = nvp.response_dict.copy() params = { "token": token, "payerid": nvp.payerid, "paymentrequest_0_amt": nvp.response_dict.get("paymentrequest_0_amt"), "paymentrequest_0_currencycode": nvp.response_dict.get("paymentrequest_0_currencycode") } payment = wpp.doExpressCheckoutPayment(params) order_dict['transactionid'] = payment.response_dict.get( 'paymentinfo_0_transactionid') order = create_order_from_express_paypal(order_dict) send_order_email(order.email, order, order.items.all) data = { 'order_id': order.id, } return HttpResponse(json.dumps(data), content_type='application/json') except Exception, e: print e data = {'error': e.message} return HttpResponseServerError(json.dumps(data), content_type='application/json')
def paypal_end(request): """ Do payment and create order object in DB """ try: wpp = PayPalWPP(request) token = request.GET['token'] params = {"token": token} nvp = wpp.getExpressCheckoutDetails(params) order_dict = nvp.response_dict.copy() params = { "token": token, "payerid": nvp.payerid, "paymentrequest_0_amt": nvp.response_dict.get("paymentrequest_0_amt"), "paymentrequest_0_currencycode" : nvp.response_dict.get("paymentrequest_0_currencycode") } payment = wpp.doExpressCheckoutPayment(params) order_dict['transactionid'] = payment.response_dict.get('paymentinfo_0_transactionid') order = create_order_from_express_paypal(order_dict) send_order_email(order.email, order, order.items.all) data = { 'order_id': order.id, } return HttpResponse(json.dumps(data), content_type='application/json') except Exception, e: print e data = { 'error': e.message } return HttpResponseServerError(json.dumps(data), content_type='application/json')
def paypal_start(request): """ Creating express checkout request from users cart """ try: params = get_cart_data_from_request(request) host_name = request.get_host() params.update({ "returnurl": "http://" + host_name + "/order/paypal/confirm", "cancelurl": "http://" + host_name + "/#!/cart", "noshipping": 2, }) wpp = PayPalWPP() nvp = wpp.setExpressCheckout(params) response = HttpResponseRedirect(settings.PAYPAL_URL + '/cgi-bin/webscr?cmd=_express-checkout&token=' + nvp.token) response.delete_cookie('cart') return response except Exception, e: #log error here print e return HttpResponseRedirect("/#!/cart")
def redirect_to_express(self): """ First step of ExpressCheckout. Redirect the request to PayPal using the data returned from setExpressCheckout. """ wpp = PayPalWPP(self.request) try: nvp_obj = wpp.setExpressCheckout(self.item) except PayPalFailure: log.exception('paypal failure') self.context['errors'] = self.errors['paypal'] return self.render_payment_form() else: pp_params = dict(token=nvp_obj.token, L_PAYMENTREQUEST_0_AMTm=self.item['PAYMENTREQUEST_0_AMT'], PAYMENTREQUEST_0_ITEMAMT=self.item['PAYMENTREQUEST_0_AMT'], PAYMENTREQUEST_0_AMT=self.item['PAYMENTREQUEST_0_AMT'], PAYMENTREQUEST_0_DESC=self.item['PAYMENTREQUEST_0_DESC'], PAYMENTREQUEST_0_CURRENCYCODE=self.item['PAYMENTREQUEST_0_CURRENCYCODE'], RETURNURL=self.item['returnurl'], CANCELURL=self.item['cancelurl']) pp_url = self.get_endpoint() % urlencode(pp_params) # log.info('redirect data: %s'% pp_url) return HttpResponseRedirect(pp_url)
def test_doDirectPayment_invalid(self): wpp = PayPalWPP(make_request()) data = { 'firstname': 'Epic', 'lastname': 'Fail', 'street': '100 Georgia St', 'city': 'Vancouver', 'state': 'BC', 'countrycode': 'CA', 'zip': 'V6V 1V1', 'expdate': '012019', 'cvv2': '999', 'acct': '1234567890', 'creditcardtype': 'visa', 'ipaddress': '10.0.1.199', } data.update(self.item) self.assertRaises(PayPalFailure, wpp.doDirectPayment, data)
from paypal.pro.helpers import PayPalWPP from paypal.pro.exceptions import PayPalFailure from paypal.pro.models import PayPalNVP from users.models import UsersProfile wpp = PayPalWPP() user_email = "*****@*****.**" params = {'expdate': '012024', 'cvv2': u'123', 'acct': u'4032031179702831', 'creditcardtype': 'Visa'} usr_obj = UsersProfile.objects.get(email=user_email) paypal_obj = PayPalNVP.objects.filter(user=usr_obj).latest('updated_at') params['profileid'] = paypal_obj.profileid nvp_obj = wpp.updateRecurringPaymentsProfile(params)
def paypal_confirm(request): """ Return from Paypal and create confirmation page """ wpp = PayPalWPP(request) token = request.GET.get("token", "") params = {"token": token} nvp = wpp.getExpressCheckoutDetails(params) """ <QueryDict: { u'l_paymentrequest_0_number1': [u'7'], u'l_paymentrequest_0_number0': [u'6'], u'shippingamt': [u'0.00'], u'paymentrequest_0_shiptozip': [u'123456'], u'paymentrequest_0_shiptostreet': [u'Pug str, 15'], u'paymentrequest_0_shiptocountryname': [u'Russia'], u'l_paymentrequest_0_taxamt1': [u'0.00'], u'paymentrequest_0_shiptoname': [u'Second'], u'shiptocountryname': [u'Russia'], u'paymentrequestinfo_0_errorcode': [u'0'], u'l_paymentrequest_0_taxamt0': [u'0.00'], u'l_paymentrequest_0_amt1': [u'26.00'], u'l_paymentrequest_0_amt0': [u'29.00'], u'checkoutstatus': [u'PaymentActionNotInitiated'], u'billingagreementacceptedstatus': [u'0'], u'l_paymentrequest_0_name1': [u'Casual summer dress'], u'l_paymentrequest_0_name0': [u'Vintage faux fur vest'], u'l_taxamt0': [u'0.00'], u'shipdiscamt': [u'0.00'], u'paymentrequest_0_shipdiscamt': [u'0.00'], u'paymentrequest_0_addressstatus': [u'Unconfirmed'], u'lastname': [u'buyer'], u'paymentrequest_0_shiptocity': [u'Moscow'], u'correlationid': [u'ed7766d969878'], u'addressstatus': [u'Unconfirmed'], u'email': [u'*****@*****.**'], u'build': [u'16751317'], u'l_paymentrequest_0_qty1': [u'1'], u'l_paymentrequest_0_qty0': [u'1'], u'payerstatus': [u'verified'], u'paymentrequest_0_insuranceamt': [u'0.00'], u'firstname': [u'test'], u'paymentrequest_0_currencycode': [u'USD'], u'timestamp': [u'2015-05-22T15:34:54Z'], u'currencycode': [u'USD'], u'paymentrequest_0_amt': [u'55.00'], u'paymentrequest_0_handlingamt': [u'0.00'], u'insuranceamt': [u'0.00'], u'handlingamt': [u'0.00'], u'paymentrequest_0_insuranceoptionoffered': [u'false'], u'l_taxamt1': [u'0.00'], u'amt': [u'55.00'], u'paymentrequest_0_itemamt': [u'55.00'], u'paymentrequest_0_shiptocountrycode': [u'RU'], u'payerid': [u'3PMMXLXMPWBRC'], u'ack': [u'Success'], u'taxamt': [u'0.00'], u'token': [u'EC-915576968K751545E'], u'paymentrequest_0_taxamt': [u'0.00'], u'itemamt': [u'55.00'], u'paymentrequest_0_shippingamt': [u'0.00'], """ order = create_order_from_paypal_for_review(nvp) response = HttpResponseRedirect("/#!/order/confirm") response.set_cookie("order_type", "express") response.set_cookie("order", json.dumps(order)) return response