示例#1
0
    def purchase(self, money, credit_card, options=None):
        """Using Eway payment gateway , charge the given
        credit card for specified money"""
        if not options:
            options = {}
        if not self.validate_card(credit_card):
            raise InvalidCard("Invalid Card")
        self.add_creditcard(credit_card)
        self.add_address(options)
        
        customer_id = self.client.create_hosted_customer(self.hosted_customer)
        pymt_response = self.client.process_payment(customer_id, 
                                                    money, 
                                                    options.get("invoice", 'test'),
                                                    options.get("description", 'test'))
        
        if not hasattr(pymt_response, "ewayTrxnStatus"):
            transaction_was_unsuccessful.send(sender=self,
                                              type="purchase",
                                              response=pymt_response)
            return {"status": "FAILURE", "response": pymt_response}

        if pymt_response.ewayTrxnStatus == "False":
            transaction_was_unsuccessful.send(sender=self,
                                              type="purchase",
                                              response=pymt_response)
            return {"status": "FAILURE", "response": pymt_response}

        transaction_was_successful.send(sender=self,
                                        type="purchase",
                                        response=pymt_response)
        return {"status": "SUCCESS", "response": pymt_response}
示例#2
0
    def recurring_cancel(self, rebill_customer_id, rebill_id):
        """
            Recurring Payment Cancelation (http://www.eway.com.au/developers/api/recurring)

            Input Parameters:
                - rebill_customer_id,
                - rebill_id  ( Output of recurring method)

            Output Dict:
                status : 'SUCCESS' or 'FAILURE'
                response : Rebill/Recurring Cancelation Response from eWay Web service.
        """
        rebillDeleteClient = RebillEwayClient(
            customer_id=self.customer_id,
            username=self.eway_username,
            password=self.eway_password,
            url=self.rebill_url,
        )

        '''
            # Delete Rebill Event, using customer create rebill detail.
        '''
        delete_rebill_response = rebillDeleteClient.delete_rebill_event(rebill_customer_id, rebill_id)

        # Handler error in delete_rebill_customer response
        if delete_rebill_response.ErrorSeverity:
            transaction_was_unsuccessful.send(sender=self,
                                              type="recurringDeleteRebill",
                                              response=delete_rebill_response)
            return {"status": "FAILURE", "response": delete_rebill_response}

        transaction_was_successful.send(sender=self,
                                        type="recurring",
                                        response=delete_rebill_response)
        return {"status": "SUCCESS", "response": delete_rebill_response}
示例#3
0
    def recurring_cancel(self, rebill_customer_id, rebill_id):
        """
            Recurring Payment Cancelation (http://www.eway.com.au/developers/api/recurring)

            Input Parameters:
                - rebill_customer_id,
                - rebill_id  ( Output of recurring method)

            Output Dict:
                status : 'SUCCESS' or 'FAILURE'
                response : Rebill/Recurring Cancelation Response from eWay Web service.
        """
        rebillDeleteClient = RebillEwayClient(
            customer_id=self.customer_id,
            username=self.eway_username,
            password=self.eway_password,
            url=self.rebill_url,
        )

        """
            # Delete Rebill Event, using customer create rebill detail.
        """
        delete_rebill_response = rebillDeleteClient.delete_rebill_event(rebill_customer_id, rebill_id)

        # Handler error in delete_rebill_customer response
        if delete_rebill_response.ErrorSeverity:
            transaction_was_unsuccessful.send(sender=self,
                                              type="recurringDeleteRebill",
                                              response=delete_rebill_response)
            return {"status": "FAILURE", "response": delete_rebill_response}

        transaction_was_successful.send(sender=self,
                                        type="recurring",
                                        response=delete_rebill_response)
        return {"status": "SUCCESS", "response": delete_rebill_response}
示例#4
0
 def store(self, credit_card, options=None):
     if isinstance(credit_card, CreditCard):
         if not self.validate_card(credit_card):
             raise InvalidCard("Invalid Card")
         payment_method = PaymentMethod.create(
             credit_card.number, credit_card.verification_value,
             credit_card.month, credit_card.year)
     else:
         # Using the token which has to be retained
         payment_method = PaymentMethod.find(credit_card)
         if payment_method.errors:
             transaction_was_unsuccessful.send(sender=self,
                                               type="store",
                                               response=payment_method)
             return {'status': 'FAILURE', 'response': payment_method}
     response = payment_method.retain()
     if response.errors:
         transaction_was_unsuccessful.send(sender=self,
                                           type="store",
                                           response=response)
         return {'status': 'FAILURE', 'response': response}
     transaction_was_successful.send(sender=self,
                                     type="store",
                                     response=response)
     return {'status': 'SUCCESS', 'response': response}
示例#5
0
 def purchase(self, amount, credit_card, options=None):
     card = credit_card
     if isinstance(credit_card, CreditCard):
         if not self.validate_card(credit_card):
             raise InvalidCard("Invalid Card")
         card = {
             'number': credit_card.number,
             'exp_month': credit_card.month,
             'exp_year': credit_card.year,
             'cvc': credit_card.verification_value
         }
     try:
         response = self.stripe.Charge.create(
             amount=int(amount * 100),
             currency=self.default_currency.lower(),
             card=card)
     except self.stripe.CardError as error:
         transaction_was_unsuccessful.send(sender=self,
                                           type="purchase",
                                           response=error)
         return {'status': 'FAILURE', 'response': error}
     transaction_was_successful.send(sender=self,
                                     type="purchase",
                                     response=response)
     return {'status': 'SUCCESS', 'response': response}
示例#6
0
    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 as 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}
        return {"status": response.ack.upper(), "response": response}
示例#7
0
 def authorize(self, money, credit_card, options=None):
     card = credit_card
     currency = self.default_currency.lower()
     if options and options.get('currency', False):
         currency = options.pop('currency')
     if isinstance(credit_card, CreditCard):
         if not self.validate_card(credit_card):
             raise InvalidCard("Invalid Card")
         card = {
             'number': credit_card.number,
             'exp_month': credit_card.month,
             'exp_year': credit_card.year,
             'cvc': credit_card.verification_value
         }
     try:
         response = self.stripe.Charge.create(amount=int(money * 100),
                                              currency=currency,
                                              card=card,
                                              capture=False,
                                              api_key=self.api_key)
         transaction_was_successful.send(sender=self,
                                         transaction_type="authorize",
                                         response=response)
         return {'status': "SUCCESS", "response": response}
     except self.stripe.CardError as error:
         transaction_was_unsuccessful.send(sender=self,
                                           transaction_type="purchase",
                                           response=error)
         return {'status': 'FAILURE', 'response': error}
示例#8
0
    def purchase(self, money, credit_card, options=None):
        """One go authorize and capture transaction"""
        self._validate(credit_card)

        params = self.client.factory.create('ns0:multi_sale_params')
        params['payment_method'] = {}
        params['payment_method']['card_data'] = {}
        params['payment_method']['card_data']['card_number'] = credit_card.number
        params['payment_method']['card_data']['card_code'] = credit_card.verification_value
        params['payment_method']['card_data']['expiration_month'] = credit_card.month
        params['payment_method']['card_data']['expiration_year'] = credit_card.year
        params['payment_method']['card_data']['name_on_card'] = '%s %s' % (credit_card.first_name, credit_card.last_name)
        params['capture_later'] = False

        customer = options['customer']
        params['customer']['name'] = customer.name
        params['customer']['email'] = customer.email
        params['customer']['ip'] = customer.ip_address
        params['customer']['address']['street_house'] = customer.address.street_house
        params['customer']['address']['city'] = customer.address.city
        if customer.address.state:
            params['customer']['address']['state'] = customer.address.state
        params['customer']['address']['zip'] = customer.address.zip_code
        params['customer']['address']['country_code'] = customer.address.country_code

        params['amount'] = money
        params['currency_code'] = self.default_currency

        product = options['product']
        params['product'] = {}
        params['product']['description'] = product

        res = self.client.service.multiSale(params)

        transaction = PaylaneTransaction()
        transaction.amount = money
        transaction.customer_name = customer.name
        transaction.customer_email = customer.email
        transaction.product = product

        status = None
        response = None
        transaction.success = hasattr(res, 'OK')
        transaction.save()

        if hasattr(res, 'OK'):
            status = 'SUCCESS'
            response = {'transaction': transaction}
            transaction_was_successful.send(sender=self, type='purchase', response=response)
        else:
            status = 'FAILURE'
            response = {'error': PaylaneError(getattr(res.ERROR, 'error_number'),
                                    getattr(res.ERROR, 'error_description'),
                                    getattr(res.ERROR, 'processor_error_number', ''),
                                    getattr(res.ERROR, 'processor_error_description', '')),
                        'transaction': transaction
                        }
            transaction_was_unsuccessful.send(sender=self, type='purchase', response=response)

        return {'status': status, 'response': response}
示例#9
0
 def purchase(self, money, credit_card, options=None):
     options = options or {}
     params = {}
     params.update({
         'account_id':
         options.pop("account_id",
                     self.we_pay_settings.get("ACCOUNT_ID", "")),
         'short_description':
         options.pop("description", ""),
         'amount':
         money,
     })
     if credit_card and not isinstance(credit_card, CreditCard):
         params["payment_method_id"] = credit_card
         params["payment_method_type"] = "credit_card"
     token = options.pop("access_token",
                         self.we_pay_settings["ACCESS_TOKEN"])
     params.update(options)
     try:
         response = self.we_pay.call('/checkout/create',
                                     params,
                                     token=token)
     except WePayError, error:
         transaction_was_unsuccessful.send(sender=self,
                                           type="purchase",
                                           response=error)
         return {'status': 'FAILURE', 'response': error}
示例#10
0
 def purchase(self, amount, credit_card, options=None):
     card = credit_card
     if isinstance(credit_card, CreditCard):
         if not self.validate_card(credit_card):
             raise InvalidCard("Invalid Card")
         card = {
             'number': credit_card.number,
             'exp_month': credit_card.month,
             'exp_year': credit_card.year,
             'cvc': credit_card.verification_value
             }
     try:
         response = self.stripe.Charge.create(
             amount=int(amount * 100),
             currency=self.default_currency.lower(),
             card=card)
     except self.stripe.CardError as error:
         transaction_was_unsuccessful.send(sender=self,
                                           type="purchase",
                                           response=error)
         return {'status': 'FAILURE', 'response': error}
     transaction_was_successful.send(sender=self,
                                     type="purchase",
                                     response=response)
     return {'status': 'SUCCESS', 'response': response}
示例#11
0
 def store(self, credit_card, options=None):
     if isinstance(credit_card, CreditCard):
         if not self.validate_card(credit_card):
             raise InvalidCard("Invalid Card")
         payment_method = PaymentMethod.create(credit_card.number, 
                                                     credit_card.verification_value, 
                                                     credit_card.month, credit_card.year)
     else:
         # Using the token which has to be retained
         payment_method = PaymentMethod.find(credit_card)
         if payment_method.errors:
             transaction_was_unsuccessful.send(sender=self, 
                                               type="store",
                                               response=payment_method)
             return {'status': 'FAILURE', 'response': payment_method}
     response = payment_method.retain()
     if response.errors:
         transaction_was_unsuccessful.send(sender=self, 
                                           type="store",
                                           response=response)
         return {'status': 'FAILURE', 'response': response}
     transaction_was_successful.send(sender=self, 
                                     type="store",
                                     response=response)
     return {'status': 'SUCCESS', 'response': response}
示例#12
0
 def authorizenet_notify_handler(self, request):
     response_from_authorize_net = self.verify_response(request)
     if not response_from_authorize_net:
         return HttpResponseForbidden()
     post_data = request.POST.copy()
     result = post_data["x_response_reason_text"]
     if request.POST['x_response_code'] == '1':
         transaction_was_successful.send(sender=self,
                                         type="sale",
                                         response=post_data)
         redirect_url = "%s?%s" % (
             request.build_absolute_uri(
                 reverse("authorize_net_success_handler")),
             urllib.urlencode({
                 "response": result,
                 "transaction_id": request.POST["x_trans_id"]
             }))
         return render_to_response(
             "billing/authorize_net_relay_snippet.html",
             {"redirect_url": redirect_url})
     redirect_url = "%s?%s" % (request.build_absolute_uri(
         reverse("authorize_net_failure_handler")),
                               urllib.urlencode({"response": result}))
     transaction_was_unsuccessful.send(sender=self,
                                       type="sale",
                                       response=post_data)
     return render_to_response("billing/authorize_net_relay_snippet.html",
                               {"redirect_url": redirect_url})
示例#13
0
 def store(self, credit_card, options=None):
     options = options or {}
     if not self.validate_card(credit_card):
         raise InvalidCard("Invalid Card")
     token = options.pop("access_token", self.we_pay_settings["ACCESS_TOKEN"])
     try:
         response = self.we_pay.call('/credit_card/create', {
                 'client_id': self.we_pay_settings["CLIENT_ID"],
                 'user_name': credit_card.name,
                 'email': options.pop("customer")["email"],
                 'cc_number': credit_card.number,
                 'cvv': credit_card.verification_value,
                 'expiration_month': credit_card.month,
                 'expiration_year': credit_card.year,
                 'address': options.pop("billing_address")
                 }, token=token)
     except WePayError as error:
         transaction_was_unsuccessful.send(sender=self,
                                           type="store",
                                           response=error)
         return {'status': 'FAILURE', 'response': error}
     transaction_was_successful.send(sender=self,
                                     type="store",
                                     response=response)
     return {'status': 'SUCCESS', 'response': response}
示例#14
0
    def purchase(self, money, credit_card, options=None):
        """One go authorize and capture transaction"""
        self._validate(credit_card)

        params = self.client.factory.create('ns0:multi_sale_params')
        params['payment_method'] = {}
        params['payment_method']['card_data'] = {}
        params['payment_method']['card_data']['card_number'] = credit_card.number
        params['payment_method']['card_data']['card_code'] = credit_card.verification_value
        params['payment_method']['card_data']['expiration_month'] = credit_card.month
        params['payment_method']['card_data']['expiration_year'] = credit_card.year
        params['payment_method']['card_data']['name_on_card'] = '%s %s' % (credit_card.first_name, credit_card.last_name)
        params['capture_later'] = False

        customer = options['customer']
        params['customer']['name'] = customer.name
        params['customer']['email'] = customer.email
        params['customer']['ip'] = customer.ip_address
        params['customer']['address']['street_house'] = customer.address.street_house
        params['customer']['address']['city'] = customer.address.city
        if customer.address.state:
            params['customer']['address']['state'] = customer.address.state
        params['customer']['address']['zip'] = customer.address.zip_code
        params['customer']['address']['country_code'] = customer.address.country_code

        params['amount'] = money
        params['currency_code'] = self.default_currency

        product = options['product']
        params['product'] = {}
        params['product']['description'] = product

        res = self.client.service.multiSale(params)

        transaction = PaylaneTransaction()
        transaction.amount = money
        transaction.customer_name = customer.name
        transaction.customer_email = customer.email
        transaction.product = product

        status = None
        response = None
        transaction.success = hasattr(res, 'OK')
        transaction.save()

        if hasattr(res, 'OK'):
            status = 'SUCCESS'
            response = {'transaction': transaction}
            transaction_was_successful.send(sender=self, type='purchase', response=response)
        else:
            status = 'FAILURE'
            response = {'error': PaylaneError(getattr(res.ERROR, 'error_number'),
                                    getattr(res.ERROR, 'error_description'),
                                    getattr(res.ERROR, 'processor_error_number', ''),
                                    getattr(res.ERROR, 'processor_error_description', '')),
                        'transaction': transaction
                        }
            transaction_was_unsuccessful.send(sender=self, type='purchase', response=response)

        return {'status': status, 'response': response}
示例#15
0
    def fps_ipn_handler(self, request):
        uri = request.build_absolute_uri()
        parsed_url = urlparse.urlparse(uri)
        resp = self.fps_connection.verify_signature("%s://%s%s" %(parsed_url.scheme, 
                                                                  parsed_url.netloc, 
                                                                  parsed_url.path),
                                                    request.raw_post_data)
        if not resp[0].VerificationStatus == "Success":
            return HttpResponseForbidden()

        data = dict(map(lambda x: x.split("="), request.raw_post_data.split("&")))
        for (key, val) in data.iteritems():
            data[key] = urllib.unquote_plus(val)
        if AmazonFPSResponse.objects.filter(transactionId=data["transactionId"]).count():
            resp = AmazonFPSResponse.objects.get(transactionId=data["transactionId"])
        else:
            resp = AmazonFPSResponse()
        for (key, val) in data.iteritems():
            attr_exists = hasattr(resp, key)
            if attr_exists and not callable(getattr(resp, key, None)):
                if key == "transactionDate":
                    val = datetime.datetime(*time.localtime(float(val))[:6])
                setattr(resp, key, val)
        resp.save()
        if resp.statusCode == "Success":
            transaction_was_successful.send(sender=self.__class__, 
                                            type=data["operation"], 
                                            response=resp)
        else:
            if not "Pending" in resp.statusCode:
                transaction_was_unsuccessful.send(sender=self.__class__, 
                                                  type=data["operation"], 
                                                  response=resp)
        # Return a HttpResponse to prevent django from complaining
        return HttpResponse(resp.statusCode)
示例#16
0
    def authorize(self, money, credit_card, options=None):
        """Authorization for a future capture transaction"""
        # TODO: Need to add check for trnAmount 
        # For Beanstream Canada and TD Visa & MasterCard merchant accounts this value may be $0 or $1 or more. 
        # For all other scenarios, this value must be $0.50 or greater.
        options = options or {}
        order_number = options.get("order_number") if options else None
        card = self.convert_cc(credit_card)
        txn = self.beangw.preauth(money, card, None, order_number)
        billing_address = options.get("billing_address")
        if billing_address:
            txn.params.update({"ordName": billing_address["name"],
                               "ordEmailAddress": billing_address["email"],
                               "ordPhoneNumber": billing_address["phone"],
                               "ordAddress1": billing_address["address1"],
                               "ordAddress2": billing_address.get("address2", ""),
                               "ordCity": billing_address["city"],
                               "ordProvince": billing_address["state"],
                               "ordCountry": billing_address["country"]})
        if options and "order_number" in options:
            txn.order_number = options.get("order_number");

        txn.validate()
        resp = self._parse_resp(txn.commit())
        if resp["status"] == "SUCCESS":
            transaction_was_successful.send(sender=self,
                                            type="authorize",
                                            response=resp["response"])
        else:
            transaction_was_unsuccessful.send(sender=self,
                                              type="authorize",
                                              response=resp["response"])
        return resp
示例#17
0
    def store(self, credit_card, options=None):
        """Store the credit card and user profile information
        on the gateway for future use"""
        card = self.convert_cc(credit_card)
        billing_address = options.get("billing_address")
        txn = self.beangw.create_payment_profile(card, billing_address)

        resp = txn.commit()

        status = "FAILURE"
        response = None
        if resp.approved() or resp.resp["responseCode"] == ["17"]:
            status = "SUCCESS" 
        else:
            response = resp

        if status == "SUCCESS":
            transaction_was_successful.send(sender=self,
                                            type="recurring",
                                            response=response)
        else:
            transaction_was_unsuccessful.send(sender=self,
                                              type="recurring",
                                              response=response)
        return {"status": status, "response": response}
示例#18
0
 def authorizenet_notify_handler(self, request):
     response_from_authorize_net = self.verify_response(request)
     if not response_from_authorize_net:
         print "LOG WARN: Returning HttpResponseForbidden, the response was not from Authorize.Net. MD5 checksum mismatch. Make sure MD5_HASH in Django settings matches the MD5 key set on the Authorize.Net server"
         return HttpResponseForbidden() # FIXED BUG; was return HttpResponseForbidden
     result = request.POST["x_response_reason_text"]
     extra_data = request.POST.get('x_extra_data', '{}')
     import json
     extra_data = json.loads(extra_data)
     if request.POST['x_response_code'] == '1':
         transaction_was_successful.send(sender=self,
                                          request=request)
         redirect_url = "%s?%s" % (request.build_absolute_uri(reverse("authorize_net_success_handler")),
                                  urllib.urlencode(dict({"response": result,
                                                    "transaction_id": request.POST["x_trans_id"]}.items() + extra_data.items())))
         return render_to_response("billing/authorize_net_relay_snippet.html",
                                   {"redirect_url": redirect_url})
     print "WARN: Authorize.Net transaction rejected. x_response_code=%s, x_response_reason_code=%s" % (request.POST['x_response_code'], request.POST['x_response_reason_code'])
      # Check http://www.authorize.net/support/merchant/Transaction_Response/Response_Reason_Codes_and_Response_Reason_Text.htm for codes
     redirect_url = "%s?%s" % (request.build_absolute_uri(reverse("donations_add")),
                              urllib.urlencode(dict({"response": result}.items() + extra_data.items())))
     transaction_was_unsuccessful.send(sender=self,
                                       request=request)
     return render_to_response("billing/authorize_net_relay_snippet.html",
                               {"redirect_url": redirect_url})
示例#19
0
    def purchase(self, money, credit_card, options=None):
        """Using Eway payment gateway , charge the given
        credit card for specified money"""
        if not options:
            options = {}
        if not self.validate_card(credit_card):
            raise InvalidCard("Invalid Card")
        self.add_creditcard(credit_card)
        self.add_address(options)

        customer_id = self.client.create_hosted_customer(self.hosted_customer)
        if self.test_mode:
            customer_id = getattr(settings, 'EWAY_TEST_CUSTOMER_ID')
        pymt_response = self.client.process_payment(
            customer_id, money, options.get("invoice", 'test'),
            options.get("description", 'test'))

        if not hasattr(pymt_response, "ewayTrxnStatus"):
            transaction_was_unsuccessful.send(sender=self,
                                              type="purchase",
                                              response=pymt_response)
            return {"status": "FAILURE", "response": pymt_response}

        if pymt_response.ewayTrxnStatus == "False":
            transaction_was_unsuccessful.send(sender=self,
                                              type="purchase",
                                              response=pymt_response)
            return {"status": "FAILURE", "response": pymt_response}

        transaction_was_successful.send(sender=self,
                                        type="purchase",
                                        response=pymt_response)
        return {"status": "SUCCESS", "response": pymt_response}
示例#20
0
    def store(self, credit_card, options=None):
        """Store the credit card and user profile information
        on the gateway for future use"""
        card = self.convert_cc(credit_card)
        billing_address = options.get("billing_address")
        txn = self.beangw.create_payment_profile(card, billing_address)

        resp = txn.commit()

        status = "FAILURE"
        response = None
        if resp.approved() or resp.resp["responseCode"] == ["17"]:
            status = "SUCCESS"
        else:
            response = resp

        if status == "SUCCESS":
            transaction_was_successful.send(sender=self,
                                            type="recurring",
                                            response=response)
        else:
            transaction_was_unsuccessful.send(sender=self,
                                              type="recurring",
                                              response=response)
        return {"status": status, "response": response}
示例#21
0
 def authorize(self, money, credit_card, options=None):
     card = credit_card
     if isinstance(credit_card, CreditCard):
         if not self.validate_card(credit_card):
             raise InvalidCard("Invalid Card")
         card = {
             'number': credit_card.number,
             'exp_month': credit_card.month,
             'exp_year': credit_card.year,
             'cvc': credit_card.verification_value
             }
     try:
         token = self.stripe.Token.create(
             card=card,
             amount=money * 100
         )
         transaction_was_successful.send(sender=self,
                                         type="authorize",
                                         response=token)
         return {'status': "SUCCESS", "response": token}
     except self.stripe.InvalidRequestError, error:
         transaction_was_unsuccessful.send(sender=self,
                                           type="authorize",
                                           response=error)
         return {"status": "FAILURE", "response": error}
示例#22
0
    def purchase(self, money, credit_card, options=None):
        """One go authorize and capture transaction"""
        options = options or {}
        txn = None
        order_number = options.get("order_number") if options else None

        if credit_card:
            card = self.convert_cc(credit_card)
            txn = self.beangw.purchase(money, card, None, order_number)
            billing_address = options.get("billing_address")
            if billing_address:
                txn.params.update({"ordName": billing_address["name"],
                                   "ordEmailAddress": billing_address["email"],
                                   "ordPhoneNumber": billing_address["phone"],
                                   "ordAddress1": billing_address["address1"],
                                   "ordAddress2": billing_address.get("address2", ""),
                                   "ordCity": billing_address["city"],
                                   "ordProvince": billing_address["state"],
                                   "ordCountry": billing_address["country"]})
        elif options.get("customer_code"):
            customer_code = options.get("customer_code", None)
            txn = self.beangw.purchase_with_payment_profile(money, customer_code, order_number)

        txn.validate()
        resp = self._parse_resp(txn.commit())
        if resp["status"] == "SUCCESS":
            transaction_was_successful.send(sender=self,
                                            type="purchase",
                                            response=resp["response"])
        else:
            transaction_was_unsuccessful.send(sender=self,
                                              type="purchase",
                                              response=resp["response"])
        return resp
示例#23
0
 def recurring(self, credit_card, options=None):
     card = credit_card
     if isinstance(credit_card, CreditCard):
         if not self.validate_card(credit_card):
             raise InvalidCard("Invalid Card")
         card = {
             'number': credit_card.number,
             'exp_month': credit_card.month,
             'exp_year': credit_card.year,
             'cvc': credit_card.verification_value
             }
     try:
         plan_id = options['plan_id']
         self.stripe.Plan.retrieve(options['plan_id'])
         try:
             response = self.stripe.Customer.create(
                 card=card,
                 plan=plan_id
             )
             transaction_was_successful.send(sender=self,
                                             type="recurring",
                                             response=response)
             return {"status": "SUCCESS", "response": response}
         except self.stripe.CardError, error:
             transaction_was_unsuccessful.send(sender=self,
                                               type="recurring",
                                               response=error)
             return {"status": "FAILURE", "response": error}
     except self.stripe.InvalidRequestError, error:
         transaction_was_unsuccessful.send(sender=self,
                                           type="recurring",
                                           response=error)
         return {"status": "FAILURE", "response": error}
示例#24
0
 def recurring(self, credit_card, options=None):
     card = credit_card
     if isinstance(credit_card, CreditCard):
         if not self.validate_card(credit_card):
             raise InvalidCard("Invalid Card")
         card = {
             'number': credit_card.number,
             'exp_month': credit_card.month,
             'exp_year': credit_card.year,
             'cvc': credit_card.verification_value
         }
     try:
         plan_id = options['plan_id']
         self.stripe.Plan.retrieve(options['plan_id'])
         try:
             response = self.stripe.Customer.create(card=card, plan=plan_id)
             transaction_was_successful.send(sender=self,
                                             type="recurring",
                                             response=response)
             return {"status": "SUCCESS", "response": response}
         except self.stripe.CardError, error:
             transaction_was_unsuccessful.send(sender=self,
                                               type="recurring",
                                               response=error)
             return {"status": "FAILURE", "response": error}
     except self.stripe.InvalidRequestError, error:
         transaction_was_unsuccessful.send(sender=self,
                                           type="recurring",
                                           response=error)
         return {"status": "FAILURE", "response": error}
示例#25
0
    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 as 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}
        return {"status": response.ack.upper(), "response": response}
示例#26
0
 def authorize(self, money, credit_card, options=None):
     card = credit_card
     if isinstance(credit_card, CreditCard):
         if not self.validate_card(credit_card):
             raise InvalidCard("Invalid Card")
         card = {
             'number': credit_card.number,
             'exp_month': credit_card.month,
             'exp_year': credit_card.year,
             'cvc': credit_card.verification_value
         }
     try:
         token = self.stripe.Token.create(
             card=card,
             amount=int(money * 100),
         )
         transaction_was_successful.send(sender=self,
                                         type="authorize",
                                         response=token)
         return {'status': "SUCCESS", "response": token}
     except self.stripe.InvalidRequestError, error:
         transaction_was_unsuccessful.send(sender=self,
                                           type="authorize",
                                           response=error)
         return {"status": "FAILURE", "response": error}
示例#27
0
 def unstore(self, identification, options=None):
     options = options or {}
     resp = self._chargebee_request("post", "/subscriptions/%s/cancel" % identification, data=options)
     if 200 <= resp.status_code < 300:
         transaction_was_successful.send(sender=self, type="void", response=resp.json)
         return {"status": "SUCCESS", "response": resp.json}
     transaction_was_unsuccessful.send(sender=self, type="void", response=resp.json)
     return {"status": "FAILURE", "response": resp.json}
示例#28
0
 def _failure(self, type, message, response, response_code=None):
     transaction_was_unsuccessful.send(self, type=type, response=response, response_code=response_code)
     retval = {"status": "FAILURE",
               "message": message,
               "response": response,
               }
     if response_code is not None:
         retval['response_code'] = response_code
     return retval
 def braintree_notify_handler(self, request):
     fpath = request.get_full_path()
     query_string = fpath.split("?", 1)[1]
     result = braintree.TransparentRedirect.confirm(query_string)
     if result.is_success:
         transaction_was_successful.send(sender=self, type="sale", response=result)
         return self.braintree_success_handler(request, result)
     transaction_was_unsuccessful.send(sender=self, type="sale", response=result)
     return self.braintree_failure_handler(request, result)
示例#30
0
    def bill_recurring(self, amount, authorization, description):
        """ Debit a recurring transaction payment, eg. monthly subscription.
        
            Use the result of recurring() as the paylane_recurring parameter.
            If this transaction is successful, use it's response as input for the
            next bill_recurring() call.
        """
        processing_date = datetime.datetime.today().strftime("%Y-%m-%d")
        res = self.client.service.resale(
            id_sale=authorization.sale_authorization_id,
            amount=amount,
            currency=self.default_currency,
            description=description,
            processing_date=processing_date,
            resale_by_authorization=authorization)

        previous_transaction = authorization.transaction

        transaction = PaylaneTransaction()
        transaction.amount = previous_transaction.amount
        transaction.customer_name = previous_transaction.customer_name
        transaction.customer_email = previous_transaction.customer_email
        transaction.product = previous_transaction.product

        status = None
        response = None
        transaction.success = hasattr(res, 'OK')
        transaction.save()
        if hasattr(res, 'OK'):
            status = 'SUCCESS'
            authz = PaylaneAuthorization()
            authz.sale_authorization_id = authorization.sale_authorization_id
            authz.transaction = transaction
            authz.save()
            response = {'transaction': transaction, 'authorization': authz}
            transaction_was_successful.send(sender=self,
                                            type='bill_recurring',
                                            response=response)

        else:
            status = 'FAILURE'
            response = {
                'error':
                PaylaneError(
                    getattr(res.ERROR, 'error_number'),
                    getattr(res.ERROR, 'error_description'),
                    getattr(res.ERROR, 'processor_error_number', ''),
                    getattr(res.ERROR, 'processor_error_description', '')),
                'transaction':
                transaction
            }
            transaction_was_unsuccessful.send(sender=self,
                                              type='bill_recurring',
                                              response=response)

        return {'status': status, 'response': response}
示例#31
0
 def credit(self, money, identification, options=None):
     """Refund a previously 'settled' transaction"""
     order_number = options.get("order_number") if options else None
     txn = self.beangw.return_purchase(identification, money, order_number)
     resp = self._parse_resp(txn.commit())
     if resp["status"] == "SUCCESS":
         transaction_was_successful.send(sender=self, type="credit", response=resp["response"])
     else:
         transaction_was_unsuccessful.send(sender=self, type="credit", response=resp["response"])
     return resp
示例#32
0
 def capture(self, money, authorization, options=None):
     """Capture funds from a previously authorized transaction"""
     order_number = options.get("order_number") if options else None
     txn = self.beangw.preauth_completion(authorization, money, order_number)
     resp = self._parse_resp(txn.commit())
     if resp["status"] == "SUCCESS":
         transaction_was_successful.send(sender=self, type="capture", response=resp["response"])
     else:
         transaction_was_unsuccessful.send(sender=self, type="capture", response=resp["response"])
     return resp
示例#33
0
    def unauthorize(self, money, authorization, options=None):
        """Cancel a previously authorized transaction"""
        txn = self.beangw.cancel_preauth(authorization)

        resp = self._parse_resp(txn.commit())
        if resp["status"] == "SUCCESS":
            transaction_was_successful.send(sender=self, type="unauthorize", response=resp["response"])
        else:
            transaction_was_unsuccessful.send(sender=self, type="unauthorize", response=resp["response"])
        return resp
示例#34
0
 def void(self, identification, options=None):
     """Null/Blank/Delete a previous transaction"""
     """Right now this only handles VOID_PURCHASE"""
     txn = self.beangw.void_purchase(identification["txnid"], identification["amount"])
     resp = self._parse_resp(txn.commit())
     if resp["status"] == "SUCCESS":
         transaction_was_successful.send(sender=self, type="void", response=resp["response"])
     else:
         transaction_was_unsuccessful.send(sender=self, type="void", response=resp["response"])
     return resp
示例#35
0
 def handle_response(self, response, type):
     response_code = response.status_code
     xml = self._parse_xml(response.text)
     result = xml_to_dict(xml)
     if result['Request']['Response'] == 'DECLINED':
         transaction_was_unsuccessful.send(self, type=type, 
             response=response, response_code=response_code)
     else:
         transaction_was_successful.send(self, type=type, 
             response=response, response_code=response_code)
     return result
示例#36
0
 def capture(self, money, authorization, options=None):
     options = options or {}
     resp = self._chargebee_request(
         "post",
         "/invoices/charge",
         data={"subscription_id": authorization, "amount": money, "description": options.get("description")},
     )
     if 200 <= resp.status_code < 300:
         transaction_was_successful.send(sender=self, type="capture", response=resp.json)
         return {"status": "SUCCESS", "response": resp.json}
     transaction_was_unsuccessful.send(sender=self, type="capture", response=resp.json)
     return {"status": "FAILURE", "response": resp.json}
示例#37
0
 def void(self, identification, options=None):
     trans = Transaction.find(identification)
     if not trans.errors:
         new_trans = trans.void()
         transaction_was_successful.send(sender=self,
                                         type="void",
                                         response=trans)
         return {'status': "SUCCESS", "response": new_trans}
     transaction_was_unsuccessful.send(sender=self,
                                       type="void",
                                       response=trans)
     return {"status": "FAILURE", "response": trans}
示例#38
0
 def credit(self, money, identification, options=None):
     trans = Transaction.find(identification)
     if not trans.errors:
         new_trans = trans.reverse(money)
         transaction_was_successful.send(sender=self,
                                         type="credit",
                                         response=trans)
         return {'status': "SUCCESS", "response": new_trans}
     transaction_was_unsuccessful.send(sender=self,
                                       type="credit",
                                       response=trans)
     return {"status": "FAILURE", "response": trans}
示例#39
0
 def credit(self, money, identification, options=None):
     trans = Transaction.find(identification)
     if not trans.errors:
         new_trans = trans.reverse(money)
         transaction_was_successful.send(sender=self, 
                                         type="credit",
                                         response=trans)
         return{'status': "SUCCESS", "response": new_trans}
     transaction_was_unsuccessful.send(sender=self, 
                                       type="credit",
                                       response=trans)
     return{"status": "FAILURE", "response": trans}
示例#40
0
 def void(self, identification, options=None):
     trans = Transaction.find(identification)
     if not trans.errors:
         new_trans = trans.void()
         transaction_was_successful.send(sender=self, 
                                         type="void",
                                         response=trans)
         return{'status': "SUCCESS", "response": new_trans}
     transaction_was_unsuccessful.send(sender=self, 
                                       type="void",
                                       response=trans)
     return{"status": "FAILURE", "response": trans}
示例#41
0
 def _failure(self, type, message, response, response_code=None):
     transaction_was_unsuccessful.send(self,
                                       type=type,
                                       response=response,
                                       response_code=response_code)
     retval = {
         "status": "FAILURE",
         "message": message,
         "response": response,
     }
     if response_code is not None:
         retval['response_code'] = response_code
     return retval
示例#42
0
 def capture(self, money, authorization, options = None):
     options = options or {}
     params = {
         'checkout_id': authorization,
         }
     token = options.pop("access_token", self.we_pay_settings["ACCESS_TOKEN"])
     try:
         response = self.we_pay.call('/checkout/capture', params, token=token)
     except WePayError, error:
         transaction_was_unsuccessful.send(sender=self,
                                           type="capture",
                                           response=error)
         return {'status': 'FAILURE', 'response': error}
示例#43
0
 def credit(self, identification, money=None, options=None):
     try:
         charge = self.stripe.Charge.retrieve(identification)
         response = charge.refund(amount=money)
         transaction_was_successful.send(sender=self,
                                         type="credit",
                                         response=response)
         return {"status": "SUCCESS", "response": response}
     except self.stripe.InvalidRequestError, error:
         transaction_was_unsuccessful.send(sender=self,
                                           type="credit",
                                           response=error)
         return {"status": "FAILURE", "error": error}
示例#44
0
 def unstore(self, identification, options=None):
     try:
         customer = self.stripe.Customer.retrieve(identification)
         response = customer.delete()
         transaction_was_successful.send(sender=self,
                                           type="unstore",
                                           response=response)
         return {"status": "SUCCESS", "response": response}
     except self.stripe.InvalidRequestError, error:
         transaction_was_unsuccessful.send(sender=self,
                                           type="unstore",
                                           response=error)
         return {"status": "FAILURE", "response": error}
 def braintree_notify_handler(self, request):
     fpath = request.get_full_path()
     query_string = fpath.split("?", 1)[1]
     result = braintree.TransparentRedirect.confirm(query_string)
     if result.is_success:
         transaction_was_successful.send(sender=self,
                                         type="sale",
                                         response=result)
         return self.braintree_success_handler(request, result)
     transaction_was_unsuccessful.send(sender=self,
                                       type="sale",
                                       response=result)
     return self.braintree_failure_handler(request, result)
示例#46
0
 def unstore(self, identification, options=None):
     try:
         customer = self.stripe.Customer.retrieve(identification)
         response = customer.delete()
         transaction_was_successful.send(sender=self,
                                         type="unstore",
                                         response=response)
         return {"status": "SUCCESS", "response": response}
     except self.stripe.InvalidRequestError, error:
         transaction_was_unsuccessful.send(sender=self,
                                           type="unstore",
                                           response=error)
         return {"status": "FAILURE", "response": error}
示例#47
0
 def credit(self, identification, money=None, options=None):
     try:
         charge = self.stripe.Charge.retrieve(identification)
         response = charge.refund(amount=money)
         transaction_was_successful.send(sender=self,
                                         type="credit",
                                         response=response)
         return {"status": "SUCCESS", "response": response}
     except self.stripe.InvalidRequestError, error:
         transaction_was_unsuccessful.send(sender=self,
                                           type="credit",
                                           response=error)
         return {"status": "FAILURE", "error": error}
示例#48
0
    def notify_handler(self, request):
        post_data = request.POST.copy()
        data = {}

        resp_fields = {
            'instId': 'installation_id',
            'compName': 'company_name',
            'cartId': 'cart_id',
            'desc': 'description',
            'amount': 'amount',
            'currency': 'currency',
            'authMode': 'auth_mode',
            'testMode': 'test_mode',
            'transId': 'transaction_id',
            'transStatus': 'transaction_status',
            'transTime': 'transaction_time',
            'authAmount': 'auth_amount',
            'authCurrency': 'auth_currency',
            'authAmountString': 'auth_amount_string',
            'rawAuthMessage': 'raw_auth_message',
            'rawAuthCode': 'raw_auth_code',
            'name': 'name',
            'address': 'address',
            'postcode': 'post_code',
            'country': 'country_code',
            'countryString': 'country',
            'tel': 'phone',
            'fax': 'fax',
            'email': 'email',
            'futurePayId': 'future_pay_id',
            'cardType': 'card_type',
            'ipAddress': 'ip_address',
        }

        for (key, val) in resp_fields.iteritems():
            data[val] = post_data.get(key, '')

        try:
            resp = WorldPayResponse.objects.create(**data)
            # TODO: Make the type more generic
            transaction_was_successful.send(sender=self.__class__,
                                            type="purchase",
                                            response=resp)
            status = "SUCCESS"
        except:
            transaction_was_unsuccessful.send(sender=self.__class__,
                                              type="purchase",
                                              response=post_data)
            status = "FAILURE"

        return HttpResponse(status)
示例#49
0
    def unauthorize(self, money, authorization, options=None):
        """Cancel a previously authorized transaction"""
        txn = Adjustment(self.beangw, Adjustment.PREAUTH_COMPLETION, authorization, money)

        resp = self._parse_resp(txn.commit())
        if resp["status"] == "SUCCESS":
            transaction_was_successful.send(sender=self,
                                            type="unauthorize",
                                            response=resp["response"])
        else:
            transaction_was_unsuccessful.send(sender=self,
                                              type="unauthorize",
                                              response=resp["response"])
        return resp
示例#50
0
 def credit(self, money, identification, options=None):
     """Refund a previously 'settled' transaction"""
     order_number = options.get("order_number") if options else None
     txn = self.beangw.return_purchase(identification, money, order_number)
     resp = self._parse_resp(txn.commit())
     if resp["status"] == "SUCCESS":
         transaction_was_successful.send(sender=self,
                                         type="credit",
                                         response=resp["response"])
     else:
         transaction_was_unsuccessful.send(sender=self,
                                           type="credit",
                                           response=resp["response"])
     return resp
示例#51
0
 def capture(self, money, identification, options=None):
     try:
         charge = self.stripe.Charge.retrieve(identification,
                                              api_key=self.api_key)
         response = charge.capture(amount=int(money * 100))
         transaction_was_successful.send(sender=self,
                                         transaction_type="capture",
                                         response=response)
         return {'status': "SUCCESS", "response": response}
     except self.stripe.InvalidRequestError as error:
         transaction_was_unsuccessful.send(sender=self,
                                           transaction_type="capture",
                                           response=error)
         return {"status": "FAILURE", "response": error}
示例#52
0
 def purchase(self, money, address, options = None):
     options = options or {}
     txns = self.get_transactions_by_address(address)
     received = self.get_txns_sum(txns)
     response = [txn.__dict__ for txn in txns]
     if received == money:
         transaction_was_successful.send(sender=self,
                                         type="purchase",
                                         response=response)
         return {'status': 'SUCCESS', 'response': response}
     transaction_was_unsuccessful.send(sender=self,
                                       type="purchase",
                                       response=response)
     return {'status': 'FAILURE', 'response': response}
示例#53
0
    def unauthorize(self, money, authorization, options=None):
        """Cancel a previously authorized transaction"""
        txn = self.beangw.cancel_preauth(authorization)

        resp = self._parse_resp(txn.commit())
        if resp["status"] == "SUCCESS":
            transaction_was_successful.send(sender=self,
                                            type="unauthorize",
                                            response=resp["response"])
        else:
            transaction_was_unsuccessful.send(sender=self,
                                              type="unauthorize",
                                              response=resp["response"])
        return resp
示例#54
0
 def unstore(self, identification, options = None):
     options = options or {}
     resp = self._chargebee_request('post',
                                    "/subscriptions/%s/cancel" % identification,
                                    data = options)
     if 200 <= resp.status_code < 300:
         transaction_was_successful.send(sender=self,
                                         type="void",
                                         response=resp.json())
         return {'status': 'SUCCESS', 'response': resp.json()}
     transaction_was_unsuccessful.send(sender=self,
                                       type="void",
                                       response=resp.json())
     return {'status': 'FAILURE', 'response': resp.json()}
示例#55
0
 def void(self, identification, options = None): 
     options = options or {}
     params = {
         'checkout_id': identification,
         'cancel_reason': options.pop("description", "")
         }
     token = options.pop("access_token", self.we_pay_settings["ACCESS_TOKEN"])
     try:
         response = self.we_pay.call('/checkout/cancel', params, token=token)
     except WePayError, error:
         transaction_was_unsuccessful.send(sender=self,
                                           type="void",
                                           response=error)
         return {'status': 'FAILURE', 'response': error}
示例#56
0
 def capture(self, money, authorization, options=None):
     try:
         response = self.stripe.Charge.create(
             amount=money * 100,
             card=authorization,
             currency=self.default_currency.lower())
         transaction_was_successful.send(sender=self,
                                         type="capture",
                                         response=response)
         return {'status': "SUCCESS", "response": response}
     except self.stripe.InvalidRequestError, error:
         transaction_was_unsuccessful.send(sender=self,
                                           type="capture",
                                           response=error)
         return {"status": "FAILURE", "response": error}
示例#57
0
 def void(self, identification, options=None):
     """Null/Blank/Delete a previous transaction"""
     """Right now this only handles VOID_PURCHASE"""
     txn = self.beangw.void_purchase(identification["txnid"],
                                     identification["amount"])
     resp = self._parse_resp(txn.commit())
     if resp["status"] == "SUCCESS":
         transaction_was_successful.send(sender=self,
                                         type="void",
                                         response=resp["response"])
     else:
         transaction_was_unsuccessful.send(sender=self,
                                           type="void",
                                           response=resp["response"])
     return resp
示例#58
0
    def unauthorize(self, money, authorization, options=None):
        """Cancel a previously authorized transaction"""
        txn = Adjustment(self.beangw, Adjustment.PREAUTH_COMPLETION,
                         authorization, money)

        resp = self._parse_resp(txn.commit())
        if resp["status"] == "SUCCESS":
            transaction_was_successful.send(sender=self,
                                            type="unauthorize",
                                            response=resp["response"])
        else:
            transaction_was_unsuccessful.send(sender=self,
                                              type="unauthorize",
                                              response=resp["response"])
        return resp
示例#59
0
 def capture(self, money, authorization, options=None):
     """Capture funds from a previously authorized transaction"""
     order_number = options.get("order_number") if options else None
     txn = self.beangw.preauth_completion(authorization, money,
                                          order_number)
     resp = self._parse_resp(txn.commit())
     if resp["status"] == "SUCCESS":
         transaction_was_successful.send(sender=self,
                                         type="capture",
                                         response=resp["response"])
     else:
         transaction_was_unsuccessful.send(sender=self,
                                           type="capture",
                                           response=resp["response"])
     return resp