2

我试图process在我的设置中调用一个函数,但它给了我这个错误:

Could not import the name: payusaepay.views.process

以下是我的看法:

# coding: utf-8
from decimal import Decimal, ROUND_UP, ROUND_DOWN
import re, time, math, random, hashlib
import urlparse, urllib, httplib, urllib2, pycurl

from django.conf import settings
from utils import logger

def trunc(f, n):
    '''Truncates/pads a float f to n decimal places without rounding'''
    return ('%.*f' % (n + 1, f))[:-1]

class Transaction(object):
    """USAePay Transaction Class"""

    VALID_COMMANDS = set('sale credit void preauth postauth check checkcredit'.split())

    VALID_REQUEST_KEYS = [
        'UMamount',
        'UMauthCode',    # required if running postauth transaction.
        'UMcard',    # the entire amount that will be charged to the customers card 
        'UMexpir',    # expiration date 4 digits no /
        'UMbillamount',
        'UMamount',    # the entire amount that will be charged to the customers card 
        'UMinvoice',    # invoice number.  must be unique.  limited to 10 digits.  use orderid if you need longer. 
        'UMorderid',    # invoice number.  must be unique.  limited to 10 digits.  use orderid if you need longer. 
        'UMponum',    # Purchase Order Number
        'UMtax',    # Tax
        'UMnontaxable',    # Order is non taxable. True -> 'Y', False -> do not specify this key
        'UMtip',    # Tip
        'UMshipping',    # Shipping charge
        'UMdiscount',    # Discount amount (ie gift certificate or coupon code)
        'UMsubtotal',    # if subtotal is set, then 
        'UMcurrency',    # Currency of $amount
        'UMname',    # name of card holder
        'UMstreet',    # street address
        'UMzip',    # zip code
        'UMdescription',    # description of charge
        'UMcomments',    # Addit
        'UMcvv2',    # cvv2 result
        'UMclerk',
        'UMbillzip',
        'UMshipstreet',
        'UMxid',
        'UMip',    # Tip
        'UMcheckimageback',    # Check back, you need to encode it with base64
        'UMtestmode',    # test transaction but don't process 
        'UMcheckimagefront',    # Check front, you need to encode it with base64
        'UMrecurring',    # (obsolete,  see the addcustomer)
        'UMdukpt',    # DUK/PT for PIN Debit
        'UMbillsourcekey', # True -> 'yes', False -> not specify this field
        'UMshipzip',
        'UMbillcity',
        'UMbillstate',
        'UMcardauth',
        'UMshipstate',
        'UMwebsite',
        'UMallowPartialAuth',    #set to 'Yes' if a partial authorization (less than the full $amount)  will be accepted
        'UMbillphone',
        'UMepcCode',
        'UMdlstate',    # drivers license issuing state
        'UMterminal',    # The type of terminal being used:  Optons are  POS - cash register, StandAlone - self service terminal,  Unattended - ie gas pump, Unkown  (Default:  Unknown)
        'UMschedule',    # 
        'UMbillstreet2',
        'UMbillcompany',
        'UMignoreDuplicate',    # prevent the system from detecti
        'UMrestaurant_table',    #
        'UMshipfname',
        'UMmicr',
        'UMaccounttype',    # Checking or Savings
        'UMsoftware',    # Allows developers to ident
        'UMaccount',    # bank account numbertimuryan
        'UMbillstreet',
        'UMstart',    #  When to start the
        'UMrefNum',    # refer
        'UMchecknum',    # Check Number
        'UMcustemail',    # customers email add
        'UMmagsupport',    # Support for mag stripe reader:   yes, no, contactless, unknown  (default is unknown unless magstripe has been sent)
        'UMauxonus',
        'UMcontactless',    # Support for mag stripe reader:   yes, no, contactless, unknown  (default is unknown unless magstripe has been sent)
        'UMshiplname',
        'UMsession',
        'UMeci',    # manually specify loc
        'UMbilllname',
        'UMaddcustomer',    # (obsolete,  see the addcustomer)
        'UMsignature',    # Signature Capture data
        'UMnumleft',    #  The number of times to 
        'UMrouting',    # bank routing number
        'UMisRecurring', # True -> 'Y', False -> do not specify this key
        'UMbillamount',
        'UMshipcountry',
        'UMbillcountry',
        'UMbillfname',
        'UMcustid',    # Alpha-numeric id that uniquely identifies the customer.
        'UMdigitalGoods',    #digital goods indicator (ecommerce)
        'UMtermtype',    # The type of terminal being used:  Optons are  POS - cash register, StandAlone - self service terminal,  Unattended - ie gas pump, Unkown  (Default:  Unknown)
        'UMmagstripe',    # mag stripe data.  can be either Track 1, Track2  or  Both  (Required if card,exp,name,street and zip aren't filled in)
        'UMcardpresent',    # Must be set to '1' if processing a card present transaction  (Default is false)
        'UMshipstreet2',
        'UMbilltax',
        'UMshipcompany',
        'UMcheckformat',    # Override default check record format
        'UMexpire',    #  When to stop running transactions. Default is to run forever.  If both end and num
        'UMfax',
        'UMcustreceipt',    # send customer a receipt
        'UMemail',    # customers email add
        'UMshipphone',
        'UMcustreceiptname',    # name
        'UMdlnum',    # drivers license number (required if not using ssn)
        'UMpares',    # 
        'UMcavv',
        'UMshipcity',
        'UMssn',    # social security number
        'UMticketedEvent',    # ID of Event when
    ]
    VALID_CUSTOM_KEY_PATTERN = re.compile('UMcustom[\d+]')

    _line_nums = '|'.join(str(i) for i in range(1, 21))
    VALID_GOODS_KEYS_PATTERN = re.compile('UMline[%s][sku|name|description|cost|qty|taxable|prodRefNum]' % _line_nums)

    class GoodsDescriptionError(Exception):
        pass

    class UnknownCommand(Exception):
        pass

    class DataError(Exception):
        pass

    class ResponseError(Exception):
        pass

    def __init__(self, UMkey = settings.USAEPAY_API_KEY,
            UMpin = None,
            gatewayurl = None,
            usesandbox = settings.USAEPAY_USE_SANDBOX, 
            ignoresslcerterrors = settings.USAEPAY_IGNORE_SSL_CERT_ERRORS,
            cabundle = settings.CABUNDLE,
            usaepay_rsa_key = settings.USAEPAY_RSA_KEY,
            UMtestmode = settings.USAEPAY_TEST_MODE):
        self.gatewayurl = gatewayurl
        self.usesandbox = usesandbox
        self.UMkey = UMkey
        self.UMpin = str(UMpin).strip() if UMpin else None
        self.ignoresslcerterrors = ignoresslcerterrors
        self.cabundle = cabundle
        self.usaepay_rsa_key=usaepay_rsa_key
        self.UMtestmode = UMtestmode

    def get_gateway_url(self, usesandbox = False):
        if self.usesandbox or usesandbox:
            return "https://sandbox.usaepay.com/gate"
        elif self.gatewayurl:
            return self.gatewayurl
        else:
            return "https://www.usaepay.com/gate"

    def check_command(self, command):
        if command not in self.VALID_COMMANDS:
            raise self.UnknownCommand(command)

    def check_data(self, command, data):
        """"
        Verify that all required data has been set
        """

        for key in data:
            contains = key in self.VALID_REQUEST_KEYS or self.VALID_CUSTOM_KEY_PATTERN.match(key) or \
                self.VALID_GOODS_KEYS_PATTERN.match(key)
            if not contains:
                raise self.DataError("Unknown key %s" % key)

        if command in ('check', 'checkcredit'):
            if not 'account' in data:
                raise self.DataError("Account Number is required")
            if not 'routing' in data:
                raise self.DataError("Routing Number is required")

    def prepair_data(self, command, initial_data, goods_lines):
        # Goods descriptions:
        # list ot dict(sku='', name='', description='', cost=0.0, qty=0, taxable='', prodRefNum=0)

        data = initial_data.copy()
        data['UMkey'] = self.UMkey

        if 'UMcheckimagefront' in data or 'UMcheckimageback' in data:
            data['UMcheckimageencoding'] = 'base64'

        if self.UMtestmode:
            data.setdefault('UMtestmode', self.UMtestmode)

        for index, line in enumerate(goods_lines, 1):
            for key in line:
                data['UMline%s%s' % (index, key)] = line[key]

        # Create hash if pin has been set.
        if self.UMpin:
            # generate random seed value
            seed = trunc(time.time(), 4) + trunc(random.random(), 10)[2:]
            # assemble prehash data
            prehash = ':'.join( (command, self.UMpin, str(data['UMamount']), str(data['UMinvoice']), seed) )
            # sha224 hash
            data['UMhash'] = 's/' + seed + '/' + hashlib.sha1(prehash).hexdigest()

        return data

    def process(self, command, initial_data, goods_lines = [], usesandbox = False):
        """
        Send transaction correspond to 'command' name to the USAePay Gateway and parse response
        goods_lines - list with good item descriptions
        """

        data = self.prepair_data(command, initial_data, goods_lines)
        gatewayurl = self.get_gateway_url(usesandbox)

        self.check_command(command)
        self.check_data(command, initial_data)

        # Post data to Gateway
        response=self.http_post(gatewayurl, data)

        if response.status != 200:
            raise self.ResponseError('Wrong response status %s', response.status)

        # decode response content
        result = urlparse.parse_qs(response.content)
        logger.debug('Decoded response: %s', result)

        # Check response errors
        if not 'UMversion' in result:
            raise self.ResponseError('UMversion is missed in the response')
        if not 'UMstatus' in result:
            raise self.ResponseError('UMstatus is missed in the response')

        error_description = tuple(result.get(key, None) for key in 'UMerrorcode UMerror UMcustnum'.split())
        if any(error_description):
            raise self.ResponseError('Errors : %s %s %s' % error_description)

        if not result['UMresult'] == ['A']:
            raise self.ResponseError('Wrong response status %s' % result['UMresult'])

        return result

    def http_post(self, url, data):
        'Post request to payment server via stream'

        data = urllib.urlencode(data)
        logger.debug('stream post request: %s', data)

        headers = {
            "Content-type": "application/x-www-form-urlencoded",
            "Content-length": len(data)
        }
        conn = httplib.HTTPSConnection("sandbox.usaepay.com", 443, self.usaepay_rsa_key, self.cabundle, False, 45)
        conn.request("POST", "/gate.php", data, headers)
        response = conn.getresponse()
        response.content = response.read()
        logger.debug('stream post response: status=%s %s', response.status, response.content)

        return response

在设置中

SHOP_HANDLER_PAYMENT = "payusaepay.views.process"
4

1 回答 1

0

因为process不是视图方法,它是Transaction类的方法,所以你可以有一个实例Transaction来调用process方法。

于 2013-01-30T11:06:29.773 回答