コード例 #1
0
    def charge_customer_profile(self, paymentProfileId, amount, ref_id,
                                invoice_number):

        # create a customer payment profile
        profileToCharge = apicontractsv1.customerProfilePaymentType()
        profileToCharge.customerProfileId = str(
            self.instance.authorizenet_customer_profile_id)
        profileToCharge.paymentProfile = apicontractsv1.paymentProfile()
        profileToCharge.paymentProfile.paymentProfileId = paymentProfileId

        order = apicontractsv1.orderType()
        order.invoiceNumber = str(invoice_number)

        transactionrequest = apicontractsv1.transactionRequestType()
        transactionrequest.transactionType = "authCaptureTransaction"
        transactionrequest.amount = amount
        transactionrequest.profile = profileToCharge
        transactionrequest.order = order

        createtransactionrequest = apicontractsv1.createTransactionRequest()
        createtransactionrequest.merchantAuthentication = self.merchantAuth
        createtransactionrequest.refId = str(ref_id)

        createtransactionrequest.transactionRequest = transactionrequest
        controller = createTransactionController(createtransactionrequest)
        controller.setenvironment(self.post_url)
        controller.execute()

        response = controller.getresponse()

        return Transaction(response)
コード例 #2
0
ファイル: apitestbase.py プロジェクト: akankaria/sdk-python
    def setUp(self):
        utility.helper.setpropertyfile('anet_python_sdk_properties.ini')

        self.amount = str(round(random.random() * 100, 2))

        self.merchantAuthentication = apicontractsv1.merchantAuthenticationType(
        )
        self.merchantAuthentication.name = utility.helper.getproperty(
            'api.login.id')
        self.merchantAuthentication.transactionKey = utility.helper.getproperty(
            'transaction.key')
        self.ref_id = 'Sample'

        self.dateOne = datetime.date(2020, 8, 30)
        self.interval = CTD_ANON()
        self.interval.length = 1
        self.interval.unit = 'months'
        self.paymentScheduleOne = apicontractsv1.paymentScheduleType()
        self.paymentScheduleOne.interval = self.interval
        self.paymentScheduleOne.startDate = self.dateOne
        self.paymentScheduleOne.totalOccurrences = 12
        self.paymentScheduleOne.trialOccurrences = 1

        self.creditCardOne = apicontractsv1.creditCardType()
        self.creditCardOne.cardNumber = "4111111111111111"
        self.creditCardOne.expirationDate = "2020-12"

        self.payment = apicontractsv1.paymentType()
        self.payment.creditCard = self.creditCardOne

        self.customerOne = apicontractsv1.nameAndAddressType()
        self.customerOne.firstName = "John"
        self.customerOne.lastName = "Smith"

        self.customerData = apicontractsv1.customerDataType()
        self.customerData.id = "99999456654"

        self.subscriptionOne = apicontractsv1.ARBSubscriptionType()
        self.subscriptionOne.paymentSchedule = self.paymentScheduleOne
        self.subscriptionOne.amount = Decimal(
            str(round(random.random() * 100, 2)))
        self.subscriptionOne.trialAmount = Decimal('0.03')
        self.subscriptionOne.payment = self.payment
        self.subscriptionOne.billTo = self.customerOne

        self.order = apicontractsv1.orderType()
        self.order.invoiceNumber = "INV-21345"
        self.order.description = "Product description"

        self.billTo = apicontractsv1.customerAddressType()
        self.billTo.firstName = "Ellen"
        self.billTo.lastName = "Johnson"
        self.billTo.company = "Souveniropolis"
        self.billTo.address = "14 Main St"
        self.billTo.city = "Seattle"
        self.billTo.state = "WA"
        self.billTo.zip = "98122"
        self.billTo.country = "USA"
コード例 #3
0
    def create_order_type(self):
        """
        Create Authorize.Net OrderType to add invoice and descriptions to the transaction
        """
        order = apicontractsv1.orderType()
        order.invoiceNumber = str(self.invoice.pk)
        order.description = self.get_transaction_id()

        return order
コード例 #4
0
ファイル: apitestbase.py プロジェクト: fxjeane/sdk-python
 def setUp(self):
     utility.helper.setpropertyfile('anet_python_sdk_properties.ini')
     
     self.amount = str(round(random.random()*100, 2))
    
     self.merchantAuthentication = apicontractsv1.merchantAuthenticationType()       
     self.merchantAuthentication.name = helper.getproperty('api_login_id')
     self.merchantAuthentication.transactionKey = helper.getproperty('transaction_key')
     self.ref_id = 'Sample'
     
     self.dateOne = datetime.date(2020, 8, 30)
     self.interval = CTD_ANON()
     self.interval.length = 1
     self.interval.unit = 'months'
     self.paymentScheduleOne = apicontractsv1.paymentScheduleType()
     self.paymentScheduleOne.interval = self.interval
     self.paymentScheduleOne.startDate = self.dateOne
     self.paymentScheduleOne.totalOccurrences = 12
     self.paymentScheduleOne.trialOccurrences = 1
     
     self.creditCardOne = apicontractsv1.creditCardType()
     self.creditCardOne.cardNumber = "4111111111111111"
     self.creditCardOne.expirationDate = "2020-12"
     
     self.payment = apicontractsv1.paymentType()
     self.payment.creditCard = self.creditCardOne
     
     self.customerOne = apicontractsv1.nameAndAddressType()
     self.customerOne.firstName = "John"
     self.customerOne.lastName = "Smith"
     
     self.customerData = apicontractsv1.customerDataType()
     self.customerData.id = "99999456654"
     
     self.subscriptionOne = apicontractsv1.ARBSubscriptionType()
     self.subscriptionOne.paymentSchedule = self.paymentScheduleOne
     self.subscriptionOne.amount = Decimal(self.amount)
     self.subscriptionOne.trialAmount = Decimal ('0.03')
     self.subscriptionOne.payment = self.payment
     self.subscriptionOne.billTo = self.customerOne
     
     self.order = apicontractsv1.orderType()
     self.order.invoiceNumber = "INV-21345"
     self.order.description = "Product description"
     
     self.billTo = apicontractsv1.customerAddressType()
     self.billTo.firstName = "Ellen"
     self.billTo.lastName = "Johnson"
     self.billTo.company = "Souveniropolis"
     self.billTo.address = "14 Main St"
     self.billTo.city = "Seattle"
     self.billTo.state = "WA"
     self.billTo.zip = "98122"
     self.billTo.country = "USA"
    
 
     
コード例 #5
0
    def _create_transaction_request_for_profile(self, transaction,
                                                customer_profile,
                                                payment_profile):

        """ Create an authorize.net transaction request object to a
        customer id

        :param transaction: A Silver transaction with a AuthorizeNet payment method.
        :param customer_profile: The authorize.net customer profile ID
        :param payment_profile: The authorize.net customer payment profile ID
        :return: An authorize.net TransactionRequest

        """

        profile_to_charge                                 = apicontractsv1.customerProfilePaymentType()
        profile_to_charge.customerProfileId               = customer_profile
        profile_to_charge.paymentProfile                  = apicontractsv1.paymentProfile()
        profile_to_charge.paymentProfile.paymentProfileId = payment_profile

        payment            = apicontractsv1.paymentType()
        payment.profile    = profile_to_charge

        # Create order information
        order               = apicontractsv1.orderType()
        order.invoiceNumber = transaction.document.series
        order.description   = "\n".join(map(str, transaction.document.entries))

        # Set the customer's identifying information
        customerData       = apicontractsv1.customerDataType()
        customerData.type  = "individual"
        customerData.id    = transaction.customer.id # TODO: right id field?
        customerData.email = transaction.customer.email

        settings = self._create_transaction_settings()

        _tx_request                     = apicontractsv1.transactionRequestType()
        _tx_request.transactionType     = "authCaptureTransaction"
        _tx_request.amount              = transaction.amount
        _tx_request.payment             = payment
        _tx_request.order               = order
        # _tx_request.billTo              = customerAddress
        _tx_request.customer            = customerData
        _tx_request.transactionSettings = settings
        # _tx_request.lineItems         = line_items

        _request = apicontractsv1.createTransactionRequest()
        _request.merchantAuthentication = self.merchantAuth

        _request.refId = self.merchantId
        _request.transactionRequest = _tx_request

        return _request
コード例 #6
0
ファイル: authnet.py プロジェクト: jazkarta/jazkarta.shop
def createTransactionRequest(cart,
                             refId,
                             opaque_data,
                             contact_info,
                             transactionType='authCaptureTransaction'):

    # Get Authorize.net API credentials
    merchantAuth = _getMerchantAuth()

    # Get payment info
    payment = _getPayment(opaque_data)

    # Create order information
    order = apicontractsv1.orderType()
    order.description = refId

    # Set the customer's Bill To address
    customerAddress = apicontractsv1.customerAddressType()
    customerAddress.firstName = contact_info.get(
        'first_name', contact_info.get('name_on_card', ''))
    customerAddress.lastName = contact_info.get('last_name', '')
    customerAddress.address = contact_info['address']
    customerAddress.city = contact_info['city']
    customerAddress.state = contact_info['state']
    customerAddress.zip = contact_info['zip']
    customerAddress.country = contact_info['country']
    customerAddress.phoneNumber = contact_info['phone']

    # Set the customer's identifying information
    customerData = apicontractsv1.customerDataType()
    customerData.type = "individual"
    customerData.email = contact_info['email']

    # @@@ shipping

    # Add values for transaction settings
    duplicateWindowSetting = apicontractsv1.settingType()
    duplicateWindowSetting.settingName = "duplicateWindow"
    duplicateWindowSetting.settingValue = "600"
    settings = apicontractsv1.ArrayOfSetting()
    settings.setting.append(duplicateWindowSetting)

    # Create a transactionRequestType object and add the previous objects to it
    transactionrequest = apicontractsv1.transactionRequestType()
    transactionrequest.transactionType = transactionType
    transactionrequest.amount = six.text_type(cart.amount)
    transactionrequest.order = order
    transactionrequest.payment = payment
    transactionrequest.billTo = customerAddress
    transactionrequest.customer = customerData
    transactionrequest.transactionSettings = settings
    transactionrequest.lineItems = _getLineItems(cart)

    # Assemble the complete transaction request
    createtransactionrequest = apicontractsv1.createTransactionRequest()
    createtransactionrequest.merchantAuthentication = merchantAuth
    createtransactionrequest.transactionRequest = transactionrequest

    with enhanced_authnet_logging():
        controller = createTransactionController(createtransactionrequest)
        if config.IN_PRODUCTION:
            controller.setenvironment(constants.PRODUCTION)
        controller.execute()
        response = controller.getresponse()

    logger.info('createTransactionController response: {}'.format(
        response.__repr__()))
    defaultMsg = 'Your card could not be processed.'
    if controller._httpResponse:
        logger.info('Authorize.net response: {}'.format(
            controller._httpResponse))
    if response.messages.resultCode == 'Ok':
        if response.transactionResponse.responseCode != 1:  # Approved
            raise PaymentProcessingException(defaultMsg)
        return response
    else:
        raise PaymentProcessingException(response.messages.message[0].text
                                         or defaultMsg)
コード例 #7
0
ファイル: authnet.py プロジェクト: jazkarta/jazkarta.shop
def ARBCreateSubscriptionRequest(cart, refId, opaque_data, contact_info,
                                 months):

    # Get Authorize.net API credentials
    merchantAuth = _getMerchantAuth()

    # Setting payment schedule
    paymentschedule = apicontractsv1.paymentScheduleType()
    paymentschedule.interval = apicontractsv1.paymentScheduleTypeInterval()
    paymentschedule.interval.length = 1
    paymentschedule.interval.unit = apicontractsv1.ARBSubscriptionUnitEnum.months
    paymentschedule.startDate = date.today()
    paymentschedule.totalOccurrences = months

    # Get payment info
    payment = _getPayment(opaque_data)

    # Create order information
    order = apicontractsv1.orderType()
    order.description = refId

    # Setting billing information
    billto = apicontractsv1.nameAndAddressType()
    billto.firstName = contact_info['first_name']
    billto.lastName = contact_info['last_name']
    billto.address = contact_info['address']
    billto.city = contact_info['city']
    billto.state = contact_info['state']
    billto.zip = contact_info['zip']
    billto.country = contact_info['country']
    billto.phoneNumber = contact_info['phone']

    # Set the customer's identifying information
    customerData = apicontractsv1.customerType()
    customerData.type = "individual"
    customerData.email = contact_info['email']
    customerData.phoneNumber = contact_info['phone']

    # Setting subscription details
    subscription = apicontractsv1.ARBSubscriptionType()
    subscription.paymentSchedule = paymentschedule
    subscription.amount = six.text_type(cart.amount)
    subscription.order = order
    subscription.customer = customerData
    subscription.billTo = billto
    subscription.payment = payment

    # Creating the request
    request = apicontractsv1.ARBCreateSubscriptionRequest()
    request.merchantAuthentication = merchantAuth
    request.subscription = subscription

    with enhanced_authnet_logging():
        controller = ARBCreateSubscriptionController(request)
        if config.IN_PRODUCTION:
            controller.setenvironment(constants.PRODUCTION)
        controller.execute()
        response = controller.getresponse()

    logger.info('ARBCreateSubscriptionController response: {}'.format(
        response.__repr__()))
    if response.messages.resultCode == 'Ok':
        return response
    else:
        raise PaymentProcessingException(response.messages.message[0].text)
コード例 #8
0
ファイル: authnet.py プロジェクト: jazkarta/jazkarta.shop
def createTransactionRequest(
        cart, refId, opaque_data, contact_info,
        transactionType='authCaptureTransaction'):

    # Get Authorize.net API credentials
    merchantAuth = _getMerchantAuth()

    # Get payment info
    payment = _getPayment(opaque_data)

    # Create order information
    order = apicontractsv1.orderType()
    order.description = refId

    # Set the customer's Bill To address
    customerAddress = apicontractsv1.customerAddressType()
    customerAddress.firstName = contact_info.get(
        'first_name', contact_info.get('name_on_card', ''))
    customerAddress.lastName = contact_info.get('last_name', '')
    customerAddress.address = contact_info['address']
    customerAddress.city = contact_info['city']
    customerAddress.state = contact_info['state']
    customerAddress.zip = contact_info['zip']
    customerAddress.country = contact_info['country']
    customerAddress.phoneNumber = contact_info['phone']

    # Set the customer's identifying information
    customerData = apicontractsv1.customerDataType()
    customerData.type = "individual"
    customerData.email = contact_info['email']

    # @@@ shipping

    # Add values for transaction settings
    duplicateWindowSetting = apicontractsv1.settingType()
    duplicateWindowSetting.settingName = "duplicateWindow"
    duplicateWindowSetting.settingValue = "600"
    settings = apicontractsv1.ArrayOfSetting()
    settings.setting.append(duplicateWindowSetting)

    # Create a transactionRequestType object and add the previous objects to it
    transactionrequest = apicontractsv1.transactionRequestType()
    transactionrequest.transactionType = transactionType
    transactionrequest.amount = str(cart.amount)
    transactionrequest.order = order
    transactionrequest.payment = payment
    transactionrequest.billTo = customerAddress
    transactionrequest.customer = customerData
    transactionrequest.transactionSettings = settings
    transactionrequest.lineItems = _getLineItems(cart)

    # Assemble the complete transaction request
    createtransactionrequest = apicontractsv1.createTransactionRequest()
    createtransactionrequest.merchantAuthentication = merchantAuth
    createtransactionrequest.transactionRequest = transactionrequest

    # Create the controller and get response
    createtransactioncontroller = createTransactionController(
        createtransactionrequest)
    if config.IN_PRODUCTION:
        createtransactioncontroller.setenvironment(constants.PRODUCTION)
    createtransactioncontroller.execute()

    response = createtransactioncontroller.getresponse()
    if response.messages.resultCode == 'Ok':
        if response.transactionResponse.responseCode != 1:  # Approved
            raise PaymentProcessingException(
                'Your card could not be processed.')
        return response
    else:
        raise PaymentProcessingException(response.messages.message[0].text)
コード例 #9
0
    def get_transaction_parameters(self, basket, request=None, use_client_side_checkout=True, **kwargs):
        """
            Create a new AuthorizeNet payment form token.

            Visit following links for more information and detail
            https://developer.authorize.net/api/reference/#accept-suite-get-an-accept-payment-page
            https://developer.authorize.net/api/reference/features/accept_hosted.html (redirection method)

        Arguments:
            basket (Basket): The basket of products being purchased.
            request (Request, optional): A Request object which is used to construct AuthorizeNet's `return_url`.
            use_client_side_checkout (bool, optional): This value is not used.
            **kwargs: Additional parameters; not used by this method.

        Returns:
            dict: AuthorizeNet-specific parameters required to complete a transaction. Must contain a URL
                to which users can be directed in order to approve a newly created payment.

        Raises:
            GatewayError: Indicates a general error or unexpected behavior on the part of AuthorizeNet which prevented
                a payment from being created.
        """

        merchant_auth = apicontractsv1.merchantAuthenticationType()
        merchant_auth.name = self.merchant_auth_name
        merchant_auth.transactionKey = self.transaction_key

        settings = self.get_authorizenet_payment_settings(basket)
        order = apicontractsv1.orderType()
        order.invoiceNumber = basket.order_number

        transaction_request = apicontractsv1.transactionRequestType()
        transaction_request.transactionType = AUTH_CAPTURE_TRANSACTION_TYPE
        transaction_request.amount = unicode(basket.total_incl_tax)
        transaction_request.order = order

        line_items_list = self.get_authorizenet_lineitems(basket)
        payment_page_request = apicontractsv1.getHostedPaymentPageRequest()
        payment_page_request.merchantAuthentication = merchant_auth
        payment_page_request.transactionRequest = transaction_request
        payment_page_request.hostedPaymentSettings = settings
        transaction_request.lineItems = line_items_list

        payment_page_controller = getHostedPaymentPageController(payment_page_request)
        payment_page_controller.execute()

        payment_page_response = payment_page_controller.getresponse()
        authorize_form_token = None

        if payment_page_response is not None:
            if payment_page_response.messages.resultCode == apicontractsv1.messageTypeEnum.Ok:
                logger.info(
                    "%s [%d].",
                    "Successfully got hosted payment page for basket",
                    basket.id,
                    exc_info=True
                )
                if payment_page_response.messages is not None:
                    logger.info('Message Code : %s', payment_page_response.messages.message[0]['code'].text)
                    logger.info('Message Text : %s', payment_page_response.messages.message[0]['text'].text)
                authorize_form_token = str(payment_page_response.token)

            else:
                logger.error('Failed to get AuthorizeNet payment token.')
                if payment_page_response.messages is not None:
                    logger.error(
                        '\nCode:%s \nText:%s',
                        payment_page_response.messages.message[0]['code'].text,
                        payment_page_response.messages.message[0]['text'].text
                    )
                raise GatewayError(payment_page_response.messages.message[0]['text'].text)
        else:
            logger.error(
                "%s [%d].",
                "Failed to create AuthorizeNet payment for basket",
                basket.id,
                exc_info=True
            )
            raise GatewayError('AuthorizeNet payment creation failure: unable to get AuthorizeNet form token')

        parameters = {
            'payment_page_url': self.autorizenet_redirect_url,
            'token': authorize_form_token
        }
        return parameters
コード例 #10
0
ファイル: __init__.py プロジェクト: vonq/saleor
def authorize(
    payment_information: PaymentData,
    config: GatewayConfig,
    user_id: Optional[int] = None,
) -> GatewayResponse:
    """Based on AcceptSuite create-an-accept-payment-transaction example.

    https://github.com/AuthorizeNet/sample-code-python/blob/master/AcceptSuite/create-an-accept-payment-transaction.py
    """
    kind = TransactionKind.CAPTURE if config.auto_capture else TransactionKind.AUTH
    merchant_auth = _get_merchant_auth(config.connection_params)

    # The Saleor token is the authorize.net "opaque data"
    opaque_data = apicontractsv1.opaqueDataType()
    opaque_data.dataDescriptor = "COMMON.ACCEPT.INAPP.PAYMENT"
    opaque_data.dataValue = payment_information.token

    payment_one = apicontractsv1.paymentType()
    payment_one.opaqueData = opaque_data

    order = apicontractsv1.orderType()
    order.invoiceNumber = payment_information.order_id
    order.description = payment_information.graphql_payment_id

    # An auth.net "profile" id is the id generated by auth.net.
    # It is not the Saleor user id.
    customer_id = (payment_information.customer_id
                   if payment_information.reuse_source else None)

    customer_data = apicontractsv1.customerDataType()
    customer_data.type = "individual"
    if user_id:
        customer_data.id = str(user_id)
    customer_data.email = payment_information.customer_email

    transaction_request = apicontractsv1.transactionRequestType()
    transaction_request.transactionType = ("authCaptureTransaction"
                                           if config.auto_capture else
                                           "authOnlyTransaction")
    transaction_request.amount = payment_information.amount
    transaction_request.currencyCode = payment_information.currency
    transaction_request.order = order
    transaction_request.payment = payment_one
    transaction_request.customer = customer_data

    if payment_information.reuse_source and customer_id is None:
        profile = apicontractsv1.customerProfilePaymentType()
        profile.createProfile = True
        transaction_request.profile = profile

    if payment_information.billing:
        customer_address = apicontractsv1.customerAddressType()
        customer_address.firstName = payment_information.billing.first_name
        customer_address.lastName = payment_information.billing.last_name
        customer_address.company = payment_information.billing.company_name
        # authorize.net support says we should not attempt submitting street_address_2
        customer_address.address = payment_information.billing.street_address_1
        customer_address.city = payment_information.billing.city
        customer_address.state = payment_information.billing.country_area
        customer_address.zip = payment_information.billing.postal_code
        customer_address.country = payment_information.billing.country
        transaction_request.billTo = customer_address

    create_transaction_request = apicontractsv1.createTransactionRequest()
    create_transaction_request.merchantAuthentication = merchant_auth
    create_transaction_request.refId = str(payment_information.payment_id)
    create_transaction_request.transactionRequest = transaction_request

    response = _make_request(create_transaction_request,
                             config.connection_params)

    (
        success,
        error,
        transaction_id,
        transaction_response,
        raw_response,
    ) = _handle_authorize_net_response(response)
    psp_reference = None
    if transaction_id:
        psp_reference = transaction_id
    elif payment_information.token:
        transaction_id = payment_information.token

    if hasattr(response, "profileResponse") and hasattr(
            response.profileResponse, "customerProfileId"):
        customer_id = response.profileResponse.customerProfileId

    payment_method_info = _authorize_net_account_to_payment_method_info(
        transaction_response)

    return GatewayResponse(
        is_success=success,
        action_required=False,
        transaction_id=transaction_id,
        amount=payment_information.amount,
        currency=payment_information.currency,
        error=error,
        payment_method_info=payment_method_info,
        kind=kind,
        raw_response=raw_response,
        customer_id=customer_id,
        psp_reference=str(psp_reference) if psp_reference else None,
    )
コード例 #11
0
def create_an_accept_payment_transaction(amount):

    # Create a merchantAuthenticationType object with authentication details
    # retrieved from the constants file
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = constants.apiLoginId
    merchantAuth.transactionKey = constants.transactionKey

    # Set the transaction's refId
    refId = "ref {}".format(time.time())

    # Create the payment object for a payment nonce
    opaqueData = apicontractsv1.opaqueDataType()
    opaqueData.dataDescriptor = "COMMON.ACCEPT.INAPP.PAYMENT"
    opaqueData.dataValue = "119eyJjb2RlIjoiNTBfMl8wNjAwMDUyN0JEODE4RjQxOUEyRjhGQkIxMkY0MzdGQjAxQUIwRTY2NjhFNEFCN0VENzE4NTUwMjlGRUU0M0JFMENERUIwQzM2M0ExOUEwMDAzNzlGRDNFMjBCODJEMDFCQjkyNEJDIiwidG9rZW4iOiI5NDkwMjMyMTAyOTQwOTk5NDA0NjAzIiwidiI6IjEuMSJ9"

    # Add the payment data to a paymentType object
    paymentOne = apicontractsv1.paymentType()
    paymentOne.opaqueData = opaqueData

    # Create order information
    order = apicontractsv1.orderType()
    order.invoiceNumber = "10101"
    order.description = "Golf Shirts"

    # Set the customer's Bill To address
    customerAddress = apicontractsv1.customerAddressType()
    customerAddress.firstName = "Ellen"
    customerAddress.lastName = "Johnson"
    customerAddress.company = "Souveniropolis"
    customerAddress.address = "14 Main Street"
    customerAddress.city = "Pecan Springs"
    customerAddress.state = "TX"
    customerAddress.zip = "44628"
    customerAddress.country = "USA"

    # Set the customer's identifying information
    customerData = apicontractsv1.customerDataType()
    customerData.type = "individual"
    customerData.id = "99999456654"
    customerData.email = "*****@*****.**"

    # Add values for transaction settings
    duplicateWindowSetting = apicontractsv1.settingType()
    duplicateWindowSetting.settingName = "duplicateWindow"
    duplicateWindowSetting.settingValue = "600"
    settings = apicontractsv1.ArrayOfSetting()
    settings.setting.append(duplicateWindowSetting)

    # Create a transactionRequestType object and add the previous objects to it
    transactionrequest = apicontractsv1.transactionRequestType()
    transactionrequest.transactionType = "authCaptureTransaction"
    transactionrequest.amount = amount
    transactionrequest.order = order
    transactionrequest.payment = paymentOne
    transactionrequest.billTo = customerAddress
    transactionrequest.customer = customerData
    transactionrequest.transactionSettings = settings

    # Assemble the complete transaction request
    createtransactionrequest = apicontractsv1.createTransactionRequest()
    createtransactionrequest.merchantAuthentication = merchantAuth
    createtransactionrequest.refId = refId
    createtransactionrequest.transactionRequest = transactionrequest

    # Create the controller and get response
    createtransactioncontroller = createTransactionController(
        createtransactionrequest)
    createtransactioncontroller.execute()

    response = createtransactioncontroller.getresponse()

    if response is not None:
        # Check to see if the API request was successfully received and acted upon
        if response.messages.resultCode == "Ok":
            # Since the API request was successful, look for a transaction response
            # and parse it to display the results of authorizing the card
            if hasattr(response.transactionResponse, 'messages') == True:
                print(
                    'Successfully created transaction with Transaction ID: %s'
                    % response.transactionResponse.transId)
                print('Transaction Response Code: %s' %
                      response.transactionResponse.responseCode)
                print('Message Code: %s' %
                      response.transactionResponse.messages.message[0].code)
                print('Auth Code: %s' % response.transactionResponse.authCode)
                print('Description: %s' % response.transactionResponse.
                      messages.message[0].description)
            else:
                print('Failed Transaction.')
                if hasattr(response.transactionResponse, 'errors') == True:
                    print('Error Code:  %s' % str(response.transactionResponse.
                                                  errors.error[0].errorCode))
                    print(
                        'Error Message: %s' %
                        response.transactionResponse.errors.error[0].errorText)
        # Or, print errors if the API request wasn't successful
        else:
            print('Failed Transaction.')
            if hasattr(response, 'transactionResponse') == True and hasattr(
                    response.transactionResponse, 'errors') == True:
                print('Error Code: %s' % str(
                    response.transactionResponse.errors.error[0].errorCode))
                print('Error Message: %s' %
                      response.transactionResponse.errors.error[0].errorText)
            else:
                print('Error Code: %s' %
                      response.messages.message[0]['code'].text)
                print('Error Message: %s' %
                      response.messages.message[0]['text'].text)
    else:
        print('Null Response.')

    return response
コード例 #12
0
def authnet_charge(request):
	# data refs
	data = request.data
	card = request.card
	reference_doc = request.reference_doc

	# Create the payment data for a credit card
	credit_card = apicontractsv1.creditCardType()
	credit_card.cardNumber = request.card.number
	credit_card.expirationDate = request.card.expiration_date
	credit_card.cardCode = request.card.code

	# Add the payment data to a paymentType object
	payment = apicontractsv1.paymentType()
	payment.creditCard = credit_card

	# determin company name to attach to customer address record
	customer_name = None
	if reference_doc.doctype == "Quotation" and frappe.db.exists("Customer", reference_doc.party_name):
		# sanity test, only fetch customer record from party_name
		customer_name = reference_doc.party_name
	else:
		customer_name = reference_doc.customer

	name_parts = card.holder_name.split(None, 1)
	customer_address = apicontractsv1.customerAddressType()
	customer_address.firstName = name_parts[0] or data.payer_name
	customer_address.lastName = name_parts[1] if len(name_parts) > 1 else ""
	customer_address.email = card.holder_email or data.payer_email

	# setting billing address details
	if frappe.db.exists("Address", reference_doc.customer_address):
		address = frappe.get_doc("Address", reference_doc.customer_address)
		customer_address.address = (address.address_line1 or "")[:60]
		customer_address.city = (address.city or "")[:40]
		customer_address.state = (address.state or "")[:40]
		customer_address.zip = (address.pincode or "")[:20]
		customer_address.country = (address.country or "")[:60]


	# record company name when not an individual
	customer_type = frappe.db.get_value("Customer", customer_name, "customer_type")
	if customer_type != "Individual":
		customer_address.company = reference_doc.customer_name

	# Create order information
	order = apicontractsv1.orderType()
	order.invoiceNumber = reference_doc.name

	# build the array of line items
	line_items = apicontractsv1.ArrayOfLineItem()

	for item in reference_doc.get("items"):
		# setup individual line items
		line_item = apicontractsv1.lineItemType()
		line_item.itemId = item.item_code
		line_item.name = item.item_name[:30]
		line_item.description = item.item_name
		line_item.quantity = item.qty
		line_item.unitPrice = cstr(item.rate)

		line_items.lineItem.append(line_item)

	# Adjust duplicate window to avoid duplicate window issues on declines
	duplicateWindowSetting = apicontractsv1.settingType()
	duplicateWindowSetting.settingName = "duplicateWindow"
	# seconds before an identical transaction can be submitted
	duplicateWindowSetting.settingValue = "10"
	settings = apicontractsv1.ArrayOfSetting()
	settings.setting.append(duplicateWindowSetting)

	# Create a transactionRequestType object and add the previous objects to it.
	transaction_request = apicontractsv1.transactionRequestType()
	transaction_request.transactionType = "authCaptureTransaction"
	transaction_request.amount = data.amount
	transaction_request.payment = payment
	transaction_request.order = order
	transaction_request.billTo = customer_address
	transaction_request.lineItems = line_items
	transaction_request.transactionSettings = settings

	# Assemble the complete transaction request
	create_transaction_request = apicontractsv1.createTransactionRequest()
	create_transaction_request.merchantAuthentication = request.merchant_auth
	create_transaction_request.transactionRequest = transaction_request
	create_transaction_request.refId = reference_doc.name

	# Create the controller
	createtransactioncontroller = createTransactionController(create_transaction_request)
	if not frappe.db.get_single_value("Authorizenet Settings", "sandbox_mode"):
		createtransactioncontroller.setenvironment(constants.PRODUCTION)
	createtransactioncontroller.execute()

	return createtransactioncontroller.getresponse()
コード例 #13
0
def charge_credit_card(amount):
    """
    Charge a credit card
    """

    # Create a merchantAuthenticationType object with authentication details
    # retrieved from the constants file
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = CONSTANTS.apiLoginId
    merchantAuth.transactionKey = CONSTANTS.transactionKey

    # Create the payment data for a credit card
    creditCard = apicontractsv1.creditCardType()
    card_types = ['visa', 'discover', 'mastercard', 'jcb']
    creditCard.cardNumber = fake.credit_card_number(
        card_type=random.choice(card_types))
    creditCard.expirationDate = fake.credit_card_expire()
    creditCard.cardCode = fake.credit_card_security_code()

    # Add the payment data to a paymentType object
    payment = apicontractsv1.paymentType()
    payment.creditCard = creditCard

    # Create order information
    order = apicontractsv1.orderType()
    order.invoiceNumber = str(random.randint(1000, 3000))
    order.description = fake.bs()

    # Set the customer's Bill To address
    customerAddress = apicontractsv1.customerAddressType()
    customerAddress.firstName = fake.first_name()
    customerAddress.lastName = fake.last_name()
    customerAddress.company = fake.bs()
    customerAddress.address = fake.street_address()
    customerAddress.city = fake.city()
    customerAddress.state = fake.address().split()[-1].split()[0]
    customerAddress.zip = fake.postalcode_in_state()
    customerAddress.country = fake.country()
    customerAddress.phoneNumber = fake.phone_number()

    # Set the customer's identifying information
    customerData = apicontractsv1.customerDataType()
    customerData.type = "individual"
    customerData.id = fake.upc_e()
    customerData.email = fake.email()

    # Add values for transaction settings
    duplicateWindowSetting = apicontractsv1.settingType()
    duplicateWindowSetting.settingName = "duplicateWindow"
    duplicateWindowSetting.settingValue = "600"
    settings = apicontractsv1.ArrayOfSetting()
    settings.setting.append(duplicateWindowSetting)

    # setup individual line items
    line_item_1 = apicontractsv1.lineItemType()
    line_item_1.itemId = "12345"
    line_item_1.name = "first"
    line_item_1.description = fake.catch_phrase()
    line_item_1.quantity = "2"
    line_item_1.unitPrice = "12.95"
    line_item_2 = apicontractsv1.lineItemType()
    line_item_2.itemId = "67890"
    line_item_2.name = "second"
    line_item_2.description = fake.catch_phrase()
    line_item_2.quantity = "3"
    line_item_2.unitPrice = "7.95"
    line_item_3 = apicontractsv1.lineItemType()
    line_item_3.itemId = "ID num goes here"
    line_item_3.name = "third"
    line_item_3.description = fake.catch_phrase()
    line_item_3.quantity = "12"
    line_item_3.unitPrice = "100.00"

    # build the array of line items
    line_items = apicontractsv1.ArrayOfLineItem()
    line_items.lineItem.append(line_item_1)
    line_items.lineItem.append(line_item_2)
    line_items.lineItem.append(line_item_3)

    # Create a transactionRequestType object and add the previous objects to it.
    transactionrequest = apicontractsv1.transactionRequestType()
    transactionrequest.transactionType = "authCaptureTransaction"
    transactionrequest.amount = amount
    transactionrequest.payment = payment
    transactionrequest.order = order
    transactionrequest.billTo = customerAddress
    transactionrequest.customer = customerData
    transactionrequest.transactionSettings = settings
    transactionrequest.lineItems = line_items

    # Assemble the complete transaction request
    createtransactionrequest = apicontractsv1.createTransactionRequest()
    createtransactionrequest.merchantAuthentication = merchantAuth
    createtransactionrequest.refId = "1234-3432"
    createtransactionrequest.transactionRequest = transactionrequest
    # Create the controller
    createtransactioncontroller = createTransactionController(
        createtransactionrequest)
    createtransactioncontroller.execute()

    response = createtransactioncontroller.getresponse()

    if response is not None:
        # Check to see if the API request was successfully received and acted upon
        if response.messages.resultCode == "Ok":
            # Since the API request was successful, look for a transaction response
            # and parse it to display the results of authorizing the card
            if hasattr(response.transactionResponse, 'messages') is True:
                print(
                    'Successfully created transaction with Transaction ID: %s'
                    % response.transactionResponse.transId)
                print('Transaction Response Code: %s' %
                      response.transactionResponse.responseCode)
                print('Message Code: %s' %
                      response.transactionResponse.messages.message[0].code)
                print('Description: %s' % response.transactionResponse.
                      messages.message[0].description)
            else:
                print('Failed Transaction.')
                if hasattr(response.transactionResponse, 'errors') is True:
                    print('Error Code:  %s' % str(response.transactionResponse.
                                                  errors.error[0].errorCode))
                    print(
                        'Error message: %s' %
                        response.transactionResponse.errors.error[0].errorText)
        # Or, print errors if the API request wasn't successful
        else:
            print('Failed Transaction.')
            if hasattr(response, 'transactionResponse') is True and hasattr(
                    response.transactionResponse, 'errors') is True:
                print('Error Code: %s' % str(
                    response.transactionResponse.errors.error[0].errorCode))
                print('Error message: %s' %
                      response.transactionResponse.errors.error[0].errorText)
            else:
                print('Error Code: %s' %
                      response.messages.message[0]['code'].text)
                print('Error message: %s' %
                      response.messages.message[0]['text'].text)
    else:
        print('Null Response.')

    return response
コード例 #14
0
def charge_credit_card(amount):
    """
    Charge a credit card
    """

    # Create a merchantAuthenticationType object with authentication details
    # retrieved from the constants file
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = CONSTANTS.apiLoginId
    merchantAuth.transactionKey = CONSTANTS.transactionKey

    # Create the payment data for a credit card
    creditCard = apicontractsv1.creditCardType()
    creditCard.cardNumber = input("Credit card number please! ")
    creditCard.expirationDate = input("Expiration date (year-mo): ")
    creditCard.cardCode = input("CVV Code")

    # Add the payment data to a paymentType object
    payment = apicontractsv1.paymentType()
    payment.creditCard = creditCard

    # Create order information
    order = apicontractsv1.orderType()
    order.invoiceNumber = input("Invoice Number: ")
    order.description = input("Order description: ")

    # Set the customer's Bill To address
    customerAddress = apicontractsv1.customerAddressType()
    customerAddress.firstName = input("Customer first name: ")
    customerAddress.lastName = input("Customer last name: ")
    customerAddress.company = input("Customer company: ")
    customerAddress.address = input("Customer address: ")
    customerAddress.city = input("City: ")
    customerAddress.state = input("State: ")
    customerAddress.zip = input("Zip code: ")
    customerAddress.country = input("Country; ")

    # Set the customer's identifying information
    customerData = apicontractsv1.customerDataType()
    customerData.type = "individual"
    customerData.id = "99999456654"
    customerData.email = input("Customer email: ")

    # Add values for transaction settings
    duplicateWindowSetting = apicontractsv1.settingType()
    duplicateWindowSetting.settingName = "duplicateWindow"
    duplicateWindowSetting.settingValue = "600"
    settings = apicontractsv1.ArrayOfSetting()
    settings.setting.append(duplicateWindowSetting)

    # setup individual line items
    line_item_1 = apicontractsv1.lineItemType()
    line_item_1.itemId = "12345"
    line_item_1.name = "first"
    line_item_1.description = "Here's the first line item"
    line_item_1.quantity = int(input("How many do you want? "))
    line_item_1.unitPrice = line_item_1.quantity
    # print("That will cost " + line_item_1.quantity)

    # build the array of line items
    line_items = apicontractsv1.ArrayOfLineItem()
    line_items.lineItem.append(line_item_1)

    # Create a transactionRequestType object and add the previous objects to it.
    transactionrequest = apicontractsv1.transactionRequestType()
    transactionrequest.transactionType = "authCaptureTransaction"
    transactionrequest.amount = amount
    transactionrequest.payment = payment
    transactionrequest.order = order
    transactionrequest.billTo = customerAddress
    transactionrequest.customer = customerData
    transactionrequest.transactionSettings = settings
    transactionrequest.lineItems = line_items

    # Assemble the complete transaction request
    createtransactionrequest = apicontractsv1.createTransactionRequest()
    createtransactionrequest.merchantAuthentication = merchantAuth
    createtransactionrequest.refId = "MerchantID-0001"
    createtransactionrequest.transactionRequest = transactionrequest
    # Create the controller
    createtransactioncontroller = createTransactionController(
        createtransactionrequest)
    createtransactioncontroller.execute()

    response = createtransactioncontroller.getresponse()

    print("Thank you for shopping!")

    if response is not None:
        # Check to see if the API request was successfully received and acted upon
        if response.messages.resultCode == "Ok":
            # Since the API request was successful, look for a transaction response
            # and parse it to display the results of authorizing the card
            if hasattr(response.transactionResponse, 'messages') is True:
                print(
                    'Successfully created transaction with Transaction ID: %s'
                    % response.transactionResponse.transId)
                print('Transaction Response Code: %s' %
                      response.transactionResponse.responseCode)
                print('Message Code: %s' %
                      response.transactionResponse.messages.message[0].code)
                print('Description: %s' % response.transactionResponse.
                      messages.message[0].description)
            else:
                print('Failed Transaction.')
                if hasattr(response.transactionResponse, 'errors') is True:
                    print('Error Code:  %s' % str(response.transactionResponse.
                                                  errors.error[0].errorCode))
                    print(
                        'Error message: %s' %
                        response.transactionResponse.errors.error[0].errorText)
        # Or, print errors if the API request wasn't successful
        else:
            print('Failed Transaction.')
            if hasattr(response, 'transactionResponse') is True and hasattr(
                    response.transactionResponse, 'errors') is True:
                print('Error Code: %s' % str(
                    response.transactionResponse.errors.error[0].errorCode))
                print('Error message: %s' %
                      response.transactionResponse.errors.error[0].errorText)
            else:
                print('Error Code: %s' %
                      response.messages.message[0]['code'].text)
                print('Error message: %s' %
                      response.messages.message[0]['text'].text)
    else:
        print('Null Response.')

    return response
コード例 #15
0
def create_an_accept_transaction(amount):

    # Create a merchantAuthenticationType object with authentication details
    # retrieved from the constants file
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = constants.apiLoginId
    merchantAuth.transactionKey = constants.transactionKey
    
    # Set the transaction's refId
    refId = "ref {}".format(time.time())

    # Create the payment object for a payment nonce
    opaqueData = apicontractsv1.opaqueDataType()
    opaqueData.dataDescriptor = "COMMON.ACCEPT.INAPP.PAYMENT"
    opaqueData.dataValue = "119eyJjb2RlIjoiNTBfMl8wNjAwMDUyN0JEODE4RjQxOUEyRjhGQkIxMkY0MzdGQjAxQUIwRTY2NjhFNEFCN0VENzE4NTUwMjlGRUU0M0JFMENERUIwQzM2M0ExOUEwMDAzNzlGRDNFMjBCODJEMDFCQjkyNEJDIiwidG9rZW4iOiI5NDkwMjMyMTAyOTQwOTk5NDA0NjAzIiwidiI6IjEuMSJ9"

    # Add the payment data to a paymentType object
    paymentOne = apicontractsv1.paymentType()
    paymentOne.opaqueData = opaqueData
    
    # Create order information
    order = apicontractsv1.orderType()
    order.invoiceNumber = "10101"
    order.description = "Golf Shirts"
    
    # Set the customer's Bill To address
    customerAddress = apicontractsv1.customerAddressType()
    customerAddress.firstName = "Ellen"
    customerAddress.lastName = "Johnson"
    customerAddress.company = "Souveniropolis"
    customerAddress.address = "14 Main Street"
    customerAddress.city = "Pecan Springs"
    customerAddress.state = "TX"
    customerAddress.zip = "44628"
    customerAddress.country = "USA"
    
    # Set the customer's identifying information
    customerData = apicontractsv1.customerDataType()
    customerData.type = "individual"
    customerData.id = "99999456654"
    customerData.email = "*****@*****.**"
    
    # Add values for transaction settings
    duplicateWindowSetting = apicontractsv1.settingType()
    duplicateWindowSetting.settingName = "duplicateWindow"
    duplicateWindowSetting.settingValue = "600"
    settings = apicontractsv1.ArrayOfSetting()
    settings.setting.append(duplicateWindowSetting)

    # Create a transactionRequestType object and add the previous objects to it
    transactionrequest = apicontractsv1.transactionRequestType()
    transactionrequest.transactionType = "authCaptureTransaction"
    transactionrequest.amount = amount
    transactionrequest.order = order
    transactionrequest.payment = paymentOne
    transactionrequest.billTo = customerAddress
    transactionrequest.customer = customerData
    transactionrequest.transactionSettings = settings

    # Assemble the complete transaction request
    createtransactionrequest = apicontractsv1.createTransactionRequest()
    createtransactionrequest.merchantAuthentication = merchantAuth
    createtransactionrequest.refId = refId
    createtransactionrequest.transactionRequest = transactionrequest
    
    # Create the controller and get response
    createtransactioncontroller = createTransactionController(createtransactionrequest)
    createtransactioncontroller.execute()

    response = createtransactioncontroller.getresponse()

    if response is not None:
        # Check to see if the API request was successfully received and acted upon
        if response.messages.resultCode == "Ok":
            # Since the API request was successful, look for a transaction response
            # and parse it to display the results of authorizing the card
            if hasattr(response.transactionResponse, 'messages') == True:
                print ('Successfully created transaction with Transaction ID: %s' % response.transactionResponse.transId)
                print ('Transaction Response Code: %s' % response.transactionResponse.responseCode)
                print ('Message Code: %s' % response.transactionResponse.messages.message[0].code)
                print ('Auth Code: %s' % response.transactionResponse.authCode)
                print ('Description: %s' % response.transactionResponse.messages.message[0].description)
            else:
                print ('Failed Transaction.')
                if hasattr(response.transactionResponse, 'errors') == True:
                    print ('Error Code:  %s' % str(response.transactionResponse.errors.error[0].errorCode))
                    print ('Error Message: %s' % response.transactionResponse.errors.error[0].errorText)
        # Or, print errors if the API request wasn't successful
        else:
            print ('Failed Transaction.')
            if hasattr(response, 'transactionResponse') == True and hasattr(response.transactionResponse, 'errors') == True:
                print ('Error Code: %s' % str(response.transactionResponse.errors.error[0].errorCode))
                print ('Error Message: %s' % response.transactionResponse.errors.error[0].errorText)
            else:
                print ('Error Code: %s' % response.messages.message[0]['code'].text)
                print ('Error Message: %s' % response.messages.message[0]['text'].text)
    else:
        print ('Null Response.')

    return response
コード例 #16
0
    def execute_payment(self, request, payment):
        """
        Charge a credit card
        """

        # Create a merchantAuthenticationType object with authentication details
        merchantAuth = apicontractsv1.merchantAuthenticationType()
        merchantAuth.name = self.settings.apiLoginID
        merchantAuth.transactionKey = self.settings.transactionKey

        # Create the payment data for a credit card
        creditCard = apicontractsv1.creditCardType()
        creditCard.cardNumber = request.session[
            'payment_authorizenet_cardNumber']
        creditCard.expirationDate = request.session[
            'payment_authorizenet_cardExpiration']
        creditCard.cardCode = request.session['payment_authorizenet_cardCode']

        # Add the payment data to a paymentType object
        paymentData = apicontractsv1.paymentType()
        paymentData.creditCard = creditCard

        # Create order information
        order = apicontractsv1.orderType()
        order.invoiceNumber = payment.order.code
        # invoiceNumber must be <= 20 char
        order.description = self.settings.purchaseDescription
        # Presumably, description will show in bank statements

        # Set the customer's Bill To address
        customerAddress = apicontractsv1.customerAddressType()
        customerAddress.firstName = request.session[
            'payment_authorizenet_firstName']
        customerAddress.lastName = request.session[
            'payment_authorizenet_lastName']
        # customerAddress.company = "Reebok"
        customerAddress.address = request.session[
            'payment_authorizenet_address']
        customerAddress.city = request.session['payment_authorizenet_city']
        customerAddress.state = request.session['payment_authorizenet_state']
        customerAddress.zip = request.session['payment_authorizenet_zip']
        # customerAddress.country = "USA"

        # Set the customer's identifying information
        # customerData = apicontractsv1.customerDataType()
        # customerData.type = "individual"
        # customerData.id = "99999456654"
        # customerData.email = "*****@*****.**"

        # Add values for transaction settings
        duplicateWindowSetting = apicontractsv1.settingType()
        duplicateWindowSetting.settingName = "duplicateWindow"
        # Set duplicateWindow to 10min. Subsequent identical transactions will be rejected.
        # https://developer.authorize.net/api/reference/features/payment_transactions.html#Transaction_Settings
        duplicateWindowSetting.settingValue = "10"
        # set windowSetting to 1 for development. TODO: do this in test mode
        # duplicateWindowSetting.settingValue = "1"
        settings = apicontractsv1.ArrayOfSetting()
        settings.setting.append(duplicateWindowSetting)

        # Create a transactionRequestType object and add the previous objects to it.
        transactionrequest = apicontractsv1.transactionRequestType()
        transactionrequest.transactionType = "authCaptureTransaction"
        transactionrequest.amount = payment.amount
        transactionrequest.payment = paymentData
        transactionrequest.order = order
        transactionrequest.billTo = customerAddress
        # transactionrequest.customer = customerData
        transactionrequest.transactionSettings = settings
        # transactionrequest.lineItems = line_items

        # Assemble the complete transaction request
        createtransactionrequest = apicontractsv1.createTransactionRequest()
        createtransactionrequest.merchantAuthentication = merchantAuth
        # Send Payment ID to help track request.
        # TCP should handle this but checking it is important for security
        createtransactionrequest.refId = str(payment.id)
        createtransactionrequest.transactionRequest = transactionrequest
        # Create the controller
        createtransactioncontroller = createTransactionController(
            createtransactionrequest)
        # BooleanField is not deserializing properly
        # this might be a bug in pretix or perhaps django-hierarkey
        if self.settings.get('productionEnabled', as_type=bool):
            createtransactioncontroller.setenvironment(constants.PRODUCTION)
        createtransactioncontroller.execute()

        response = createtransactioncontroller.getresponse()

        responseCodes = enum.IntEnum('responseCodes', [
            ('Approved', 1),
            ('Declined', 2),
            ('Error', 3),
            ('Held_for_Review', 4),
        ])

        def log_messages(request,
                         transId,
                         messagelist,
                         action='authorizenet.payment.message'):
            for message in messagelist:
                payment.order.log_action(
                    action,
                    data={
                        'transId':
                        transId or 0,
                        'resultCode':
                        message.code.text,
                        # for some reason the response.messages.message is missing the .text member
                        'description':
                        message.description.text if hasattr(
                            message, 'description') else message['text'].text,
                    })

        def log_errors(request,
                       transId,
                       errorlist,
                       action='authorizenet.payment.error'):
            for error in errorlist:
                payment.order.log_action(action,
                                         data={
                                             'transId': transId or 0,
                                             'errorCode': error.errorCode.text,
                                             'errorText': error.errorText.text,
                                         })

        def show_messages(request, messagelist, level=messages.INFO):
            for message in messagelist:
                messages.add_message(request, level, message.description.text)

        def show_errors(request,
                        errorlist,
                        level=messages.ERROR,
                        message_text=None):
            for error in errorlist:
                messages.add_message(request, level, error.errorText.text)

        if response is not None:
            try:
                transId = int(response.transactionResponse.transId)
            except AttributeError:
                transId = 0
            # Check to see if the API request was successfully received and acted upon
            # if response.messages.resultCode == 'Ok':
            if hasattr(response, 'transactionResponse') and hasattr(
                    response.transactionResponse, 'responseCode'):
                if response.transactionResponse.responseCode == responseCodes.Approved:
                    messagelist = response.transactionResponse.messages.message
                    payment.info = {'id': response.transactionResponse.transId}
                    log_messages(request,
                                 transId,
                                 messagelist,
                                 action='authorizenet.payment.approved')
                    show_messages(
                        request,
                        response.transactionResponse.messages.message,
                        level=messages.SUCCESS)
                    payment.confirm()

                elif response.transactionResponse.responseCode == responseCodes.Declined:
                    log_errors(request,
                               transId,
                               response.transactionResponse.errors.error,
                               action='authorizenet.payment.decline')
                    show_errors(request,
                                response.transactionResponse.errors.error)
                    payment.fail({
                        'reason':
                        response.transactionResponse.errors.error[0].errorText.
                        text,
                        'transId':
                        response.transactionResponse.transId.text
                    })
                # Error response handling
                # elif response.transactionResponse.responseCode == responseCodes.Error:
                elif response.transactionResponse.responseCode == responseCodes.Error:
                    # If the resultCode is not 'Ok', there's something wrong with the API request
                    # errors.error is the list
                    log_errors(request, transId,
                               response.transactionResponse.errors.error)
                    show_errors(request,
                                response.transactionResponse.errors.error)
                    payment.fail(
                        info={
                            'error':
                            response.transactionResponse.errors.error[0].
                            errorText.text
                        })
                    raise PaymentException('Transaction Declined')

                # we don't use hold for review
                elif response.transactionResponse.responseCode == responseCodes.Held_for_Review:
                    log_messages(request, transId,
                                 response.transactionResponse.messages.message)
                    show_messages(
                        request, response.transactionResponse.messages.message)

            # Or, maybe log errors if the API request wasn't successful
            else:
                # no transactionResponse or no responseCode
                payment.fail(
                    info={
                        'error': 'API request failed. No Transaction Response'
                    })
                # messages is django system for showing info to the user
                # message is the variable containing the message
                # import pdb; pdb.set_trace()
                log_messages(request,
                             transId,
                             response.messages.message,
                             action='authorizenet.payment.failure')

                messages.error(request,
                               'API request error, please try again later')
                # no messages or errors
                # raise PaymentException("Failed Transaction with no error or message")

        else:
            payment.order.log_action('authorizenet.payment.fail')
            payment.fail(
                {'error': 'could not contact gateway, response was None'})
            raise PaymentException(
                'Could not contact API gateway, please try again later')
コード例 #17
0
def charge_credit_card(data, card_number, expiration_date, card_code):
    """
	Charge a credit card
	"""
    data = json.loads(data)
    data = frappe._dict(data)

    # Create Integration Request
    integration_request = create_request_log(data, "Host", "Authorizenet")

    # Authenticate with Authorizenet
    merchant_auth = apicontractsv1.merchantAuthenticationType()
    merchant_auth.name = frappe.db.get_single_value("Authorizenet Settings",
                                                    "api_login_id")
    merchant_auth.transactionKey = get_decrypted_password(
        'Authorizenet Settings',
        'Authorizenet Settings',
        fieldname='api_transaction_key',
        raise_exception=False)

    # Create the payment data for a credit card
    credit_card = apicontractsv1.creditCardType()
    credit_card.cardNumber = card_number
    credit_card.expirationDate = expiration_date
    credit_card.cardCode = card_code

    # Add the payment data to a paymentType object
    payment = apicontractsv1.paymentType()
    payment.creditCard = credit_card

    pr = frappe.get_doc(data.reference_doctype, data.reference_docname)
    reference_doc = frappe.get_doc(pr.reference_doctype,
                                   pr.reference_name).as_dict()

    customer_address = apicontractsv1.customerAddressType()
    customer_address.firstName = data.payer_name
    customer_address.email = data.payer_email
    customer_address.address = reference_doc.customer_address[:60]

    # Create order information
    order = apicontractsv1.orderType()
    order.invoiceNumber = reference_doc.name

    # build the array of line items
    line_items = apicontractsv1.ArrayOfLineItem()

    for item in reference_doc.get("items"):
        # setup individual line items
        line_item = apicontractsv1.lineItemType()
        line_item.itemId = item.item_code
        line_item.name = item.item_name[:30]
        line_item.description = item.item_name
        line_item.quantity = item.qty
        line_item.unitPrice = cstr(item.rate)

        line_items.lineItem.append(line_item)

    # Create a transactionRequestType object and add the previous objects to it.
    transaction_request = apicontractsv1.transactionRequestType()
    transaction_request.transactionType = "authCaptureTransaction"
    transaction_request.amount = data.amount
    transaction_request.payment = payment
    transaction_request.order = order
    transaction_request.billTo = customer_address
    transaction_request.lineItems = line_items

    # Assemble the complete transaction request
    create_transaction_request = apicontractsv1.createTransactionRequest()
    create_transaction_request.merchantAuthentication = merchant_auth
    create_transaction_request.transactionRequest = transaction_request

    # Create the controller
    createtransactioncontroller = createTransactionController(
        create_transaction_request)
    if not frappe.db.get_single_value("Authorizenet Settings", "sandbox_mode"):
        createtransactioncontroller.setenvironment(constants.PRODUCTION)
    createtransactioncontroller.execute()

    response = createtransactioncontroller.getresponse()

    status = "Failed"
    if response is not None:
        # Check to see if the API request was successfully received and acted upon
        if response.messages.resultCode == "Ok" and hasattr(
                response.transactionResponse, 'messages') is True:
            status = "Completed"

    if status != "Failed":
        try:
            pr.run_method("on_payment_authorized", status)
        except Exception as ex:
            raise ex

    response_dict = to_dict(response)
    integration_request.update_status(data, status)
    description = "Something went wrong while trying to complete the transaction. Please try again."

    if status == "Completed":
        description = response_dict.get("transactionResponse").get(
            "messages").get("message").get("description")
    elif status == "Failed":
        description = error_text = response_dict.get(
            "transactionResponse").get("errors").get("error").get("errorText")
        integration_request.error = error_text
        integration_request.save(ignore_permissions=True)

    return frappe._dict({"status": status, "description": description})
コード例 #18
0
    def _create_transaction_request(self, transaction):
        """ Create an authorize.net transaction request object from
        whatever silver is passing over.

        :param transaction: A Silver transaction with a AuthorizeNet payment method.
        :return: An authorize.net TransactionRequest

        """
        logger.info("creating transaction request")

        payment            = apicontractsv1.paymentType()
        payment.creditCard = self._create_credit_card(transaction.payment_method.customer)

        # Create order information
        order               = apicontractsv1.orderType()
        order.invoiceNumber = "%s-%d" % (transaction.document.series, transaction.document.number)
        if len(transaction.document.entries) > 0:
            issue_date = transaction.document.issue_date.strftime("%m/%d/%Y")
            dsc = issue_date + "  " + "\n".join(map(str, transaction.document.entries))
        else:
            dsc = ""

        if len(dsc) > 80:
            dsc = dsc[0:80]

        # Construct line items

        if len(transaction.document.entries) > 0:
            line_items = apicontractsv1.ArrayOfLineItem()
            for e in transaction.document.entries:
                line_items.lineItem.append(self._create_entry_line_item(e))
        else:
            line_items = False

        order.description   = dsc

        # Set the customer's identifying information
        customerData       = apicontractsv1.customerDataType()
        customerData.type  = "individual"
        customerData.id    = str(transaction.customer.id)
        customerData.email = transaction.customer.email

        settings = self._create_transaction_settings()

        _tx_request                     = apicontractsv1.transactionRequestType()
        _tx_request.transactionType     = "authCaptureTransaction"
        _tx_request.amount              = transaction.amount
        _tx_request.payment             = payment
        _tx_request.order               = order
        _tx_request.billTo              = self._create_bill_to(transaction.customer)
        _tx_request.customer            = customerData
        _tx_request.transactionSettings = settings

        if line_items:
            _tx_request.lineItems = line_items

        _request = apicontractsv1.createTransactionRequest()
        _request.merchantAuthentication = self.merchantAuth

        _request.refId = self.merchantId
        _request.transactionRequest = _tx_request

        return _request
コード例 #19
0
def charge_credit_card():
    #try:
    # Create a merchantAuthenticationType object with authentication details
    # retrieved from the constants file
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = CONSTANTS.apiLoginId
    merchantAuth.transactionKey = CONSTANTS.transactionKey

    # Create the payment data for a credit card
    creditCard = apicontractsv1.creditCardType()
    creditCard.cardNumber = "4111111111111111"
    creditCard.expirationDate = "2020-12"
    creditCard.cardCode = cardCode

    # Add the payment data to a paymentType object
    payment = apicontractsv1.paymentType()
    payment.creditCard = creditCard

    # Create order information
    order = apicontractsv1.orderType()
    order.invoiceNumber = "110011"
    order.description = "Lost a Bet"

    # Set the customer's Bill To address
    fullname1 = f.get('/Users/' + loser, 'name')

    customerAddress = apicontractsv1.customerAddressType()
    customerAddress.firstName = "John"
    customerAddress.lastName = "Doe"
    customerAddress.company = "Souveniropolis"
    customerAddress.address1 = "14 Main Street"
    customerAddress.city1 = "Pecan Springs"
    customerAddress.state1 = "TX"
    customerAddress.zip1 = "44628"
    customerAddress.country1 = "USA"

    # Add values for transaction settings
    duplicateWindowSetting = apicontractsv1.settingType()
    duplicateWindowSetting.settingName = "duplicateWindow"
    duplicateWindowSetting.settingValue = "600"
    settings = apicontractsv1.ArrayOfSetting()
    settings.setting.append(duplicateWindowSetting)

    customerData = apicontractsv1.customerDataType()
    customerData.type = "individual"
    customerData.id = "99999456657"
    customerData.email = "*****@*****.**"

    # Create a transactionRequestType object and add the previous objects to it.
    #charged
    transactionrequest = apicontractsv1.transactionRequestType()
    transactionrequest.transactionType = "authCaptureTransaction"
    transactionrequest.amount = amount
    transactionrequest.payment = payment
    transactionrequest.order = order
    transactionrequest.billTo = customerAddress
    transactionrequest.customer = customerData
    transactionrequest.transactionSettings = settings

    # Assemble the complete transaction request
    createtransactionrequest = apicontractsv1.createTransactionRequest()
    createtransactionrequest.merchantAuthentication = merchantAuth
    #createtransactionrequest.refId = "MerchantID-0001"
    createtransactionrequest.transactionRequest = transactionrequest
    # Create the controller
    createtransactioncontroller = createTransactionController(
        createtransactionrequest)
    createtransactioncontroller.execute()

    response = createtransactioncontroller.getresponse()

    if response is not None:
        # Check to see if the API request was successfully received and acted upon
        if response.messages.resultCode == "Ok":
            # Since the API request was successful, look for a transaction response
            # and parse it to display the results of authorizing the card
            if hasattr(response.transactionResponse, 'messages') is True:
                print(
                    'Successfully created transaction with Transaction ID: %s'
                    % response.transactionResponse.transId)
                print('Transaction Response Code: %s' %
                      response.transactionResponse.responseCode)
                print('Message Code: %s' %
                      response.transactionResponse.messages.message[0].code)
                print('Description: %s' % response.transactionResponse.
                      messages.message[0].description)
            else:
                print('Failed Transaction.')
                if hasattr(response.transactionResponse, 'errors') is True:
                    print('Error Code:  %s' % str(response.transactionResponse.
                                                  errors.error[0].errorCode))
                    print(
                        'Error message: %s' %
                        response.transactionResponse.errors.error[0].errorText)
        # Or, print errors if the API request wasn't successful
        else:
            print('Failed Transaction.')
            if hasattr(response, 'transactionResponse') is True and hasattr(
                    response.transactionResponse, 'errors') is True:
                print('Error Code: %s' % str(
                    response.transactionResponse.errors.error[0].errorCode))
                print('Error message: %s' %
                      response.transactionResponse.errors.error[0].errorText)
            else:
                print('Error Code: %s' %
                      response.messages.message[0]['code'].text)
                print('Error message: %s' %
                      response.messages.message[0]['text'].text)
    else:
        print('Null Response.')

    return response
コード例 #20
0
ファイル: authnet.py プロジェクト: jazkarta/jazkarta.shop
def ARBCreateSubscriptionRequest(
        cart, refId, opaque_data, contact_info, months):

    # Get Authorize.net API credentials
    merchantAuth = _getMerchantAuth()

    # Setting payment schedule
    paymentschedule = apicontractsv1.paymentScheduleType()
    paymentschedule.interval = apicontractsv1.paymentScheduleTypeInterval()
    paymentschedule.interval.length = 1
    paymentschedule.interval.unit = apicontractsv1.ARBSubscriptionUnitEnum.months
    paymentschedule.startDate = date.today()
    paymentschedule.totalOccurrences = months

    # Get payment info
    payment = _getPayment(opaque_data)

    # Create order information
    order = apicontractsv1.orderType()
    order.description = refId

    # Setting billing information
    billto = apicontractsv1.nameAndAddressType()
    billto.firstName = contact_info['first_name']
    billto.lastName = contact_info['last_name']
    billto.address = contact_info['address']
    billto.city = contact_info['city']
    billto.state = contact_info['state']
    billto.zip = contact_info['zip']
    billto.country = contact_info['country']
    billto.phoneNumber = contact_info['phone']

    # Set the customer's identifying information
    customerData = apicontractsv1.customerType()
    customerData.type = "individual"
    customerData.email = contact_info['email']
    customerData.phoneNumber = contact_info['phone']

    # Setting subscription details
    subscription = apicontractsv1.ARBSubscriptionType()
    subscription.paymentSchedule = paymentschedule
    subscription.amount = str(cart.amount)
    subscription.order = order
    subscription.customer = customerData
    subscription.billTo = billto
    subscription.payment = payment

    # Creating the request
    request = apicontractsv1.ARBCreateSubscriptionRequest()
    request.merchantAuthentication = merchantAuth
    request.subscription = subscription

    # Creating and executing the controller
    controller = ARBCreateSubscriptionController(request)
    if config.IN_PRODUCTION:
        controller.setenvironment(constants.PRODUCTION)
    controller.execute()

    # Getting the response
    response = controller.getresponse()
    if response.messages.resultCode == 'Ok':
        return response
    else:
        raise PaymentProcessingException(response.messages.message[0].text)
コード例 #21
0
def charge_credit_card(amount):
    """
    Charge a credit card
    """

    # Create a merchantAuthenticationType object with authentication details
    # retrieved from the constants file
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = CONSTANTS.apiLoginId
    merchantAuth.transactionKey = CONSTANTS.transactionKey

    # Create the payment data for a credit card
    creditCard = apicontractsv1.creditCardType()
    creditCard.cardNumber = "4111111111111111"
    creditCard.expirationDate = "2020-12"
    creditCard.cardCode = "123"

    # Add the payment data to a paymentType object
    payment = apicontractsv1.paymentType()
    payment.creditCard = creditCard

    # Create order information
    order = apicontractsv1.orderType()
    order.invoiceNumber = "10101"
    order.description = "Golf Shirts"

    # Set the customer's Bill To address
    customerAddress = apicontractsv1.customerAddressType()
    customerAddress.firstName = "Ellen"
    customerAddress.lastName = "Johnson"
    customerAddress.company = "Souveniropolis"
    customerAddress.address = "14 Main Street"
    customerAddress.city = "Pecan Springs"
    customerAddress.state = "TX"
    customerAddress.zip = "44628"
    customerAddress.country = "USA"

    # Set the customer's identifying information
    customerData = apicontractsv1.customerDataType()
    customerData.type = "individual"
    customerData.id = "99999456654"
    customerData.email = "*****@*****.**"

    # Add values for transaction settings
    duplicateWindowSetting = apicontractsv1.settingType()
    duplicateWindowSetting.settingName = "duplicateWindow"
    duplicateWindowSetting.settingValue = "600"
    settings = apicontractsv1.ArrayOfSetting()
    settings.setting.append(duplicateWindowSetting)

    # setup individual line items
    line_item_1 = apicontractsv1.lineItemType()
    line_item_1.itemId = "12345"
    line_item_1.name = "first"
    line_item_1.description = "Here's the first line item"
    line_item_1.quantity = "2"
    line_item_1.unitPrice = "12.95"
    line_item_2 = apicontractsv1.lineItemType()
    line_item_2.itemId = "67890"
    line_item_2.name = "second"
    line_item_2.description = "Here's the second line item"
    line_item_2.quantity = "3"
    line_item_2.unitPrice = "7.95"

    # build the array of line items
    line_items = apicontractsv1.ArrayOfLineItem()
    line_items.lineItem.append(line_item_1)
    line_items.lineItem.append(line_item_2)

    # Create a transactionRequestType object and add the previous objects to it.
    transactionrequest = apicontractsv1.transactionRequestType()
    transactionrequest.transactionType = "authCaptureTransaction"
    transactionrequest.amount = amount
    transactionrequest.payment = payment
    transactionrequest.order = order
    transactionrequest.billTo = customerAddress
    transactionrequest.customer = customerData
    transactionrequest.transactionSettings = settings
    transactionrequest.lineItems = line_items

    # Assemble the complete transaction request
    createtransactionrequest = apicontractsv1.createTransactionRequest()
    createtransactionrequest.merchantAuthentication = merchantAuth
    createtransactionrequest.refId = "MerchantID-0001"
    createtransactionrequest.transactionRequest = transactionrequest
    # Create the controller
    createtransactioncontroller = createTransactionController(
        createtransactionrequest)
    createtransactioncontroller.execute()

    response = createtransactioncontroller.getresponse()

    if response is not None:
        # Check to see if the API request was successfully received and acted upon
        if response.messages.resultCode == "Ok":
            # Since the API request was successful, look for a transaction response
            # and parse it to display the results of authorizing the card
            if hasattr(response.transactionResponse, 'messages') is True:
                print(
                    'Successfully created transaction with Transaction ID: %s'
                    % response.transactionResponse.transId)
                print('Transaction Response Code: %s' %
                      response.transactionResponse.responseCode)
                print('Message Code: %s' %
                      response.transactionResponse.messages.message[0].code)
                print('Description: %s' % response.transactionResponse.
                      messages.message[0].description)
            else:
                print('Failed Transaction.')
                if hasattr(response.transactionResponse, 'errors') is True:
                    print('Error Code:  %s' % str(response.transactionResponse.
                                                  errors.error[0].errorCode))
                    print(
                        'Error message: %s' %
                        response.transactionResponse.errors.error[0].errorText)
        # Or, print errors if the API request wasn't successful
        else:
            print('Failed Transaction.')
            if hasattr(response, 'transactionResponse') is True and hasattr(
                    response.transactionResponse, 'errors') is True:
                print('Error Code: %s' % str(
                    response.transactionResponse.errors.error[0].errorCode))
                print('Error message: %s' %
                      response.transactionResponse.errors.error[0].errorText)
            else:
                print('Error Code: %s' %
                      response.messages.message[0]['code'].text)
                print('Error message: %s' %
                      response.messages.message[0]['text'].text)
    else:
        print('Null Response.')

    return response
コード例 #22
0
ファイル: charge.py プロジェクト: slymon99/medhacks2018
def charge_credit_card(amount, cardNumber, expirationDate, cardCode):
    """
    Charge a credit card
    """

    # Create a merchantAuthenticationType object with authentication details
    # retrieved from the constants file
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = "3d6s5NbHM6"
    merchantAuth.transactionKey = "6CH2sU7Mr5272KkT"

    # Create the payment data for a credit card
    creditCard = apicontractsv1.creditCardType()
    creditCard.cardNumber = cardNumber
    creditCard.expirationDate = expirationDate
    creditCard.cardCode = cardCode

    # Add the payment data to a paymentType object
    payment = apicontractsv1.paymentType()
    payment.creditCard = creditCard

    # Create order information
    order = apicontractsv1.orderType()
    order.invoiceNumber = "10104"
    order.description = "Nutrition plan subscription"

    # Add values for transaction settings
    duplicateWindowSetting = apicontractsv1.settingType()
    duplicateWindowSetting.settingName = "duplicateWindow"
    duplicateWindowSetting.settingValue = "600"
    settings = apicontractsv1.ArrayOfSetting()
    settings.setting.append(duplicateWindowSetting)

    # Create a transactionRequestType object and add the previous objects to it.
    transactionrequest = apicontractsv1.transactionRequestType()
    transactionrequest.transactionType = "authCaptureTransaction"
    transactionrequest.amount = amount
    transactionrequest.payment = payment
    # transactionrequest.transactionSettings = settings

    # Assemble the complete transaction request
    createtransactionrequest = apicontractsv1.createTransactionRequest()
    createtransactionrequest.merchantAuthentication = merchantAuth
    createtransactionrequest.refId = "MerchantID-0001"
    createtransactionrequest.transactionRequest = transactionrequest
    # Create the controller
    createtransactioncontroller = createTransactionController(
        createtransactionrequest)
    createtransactioncontroller.execute()

    response = createtransactioncontroller.getresponse()

    if response is not None:
        # Check to see if the API request was successfully received and acted upon
        if response.messages.resultCode == "Ok":
            # Since the API request was successful, look for a transaction response
            # and parse it to display the results of authorizing the card
            if hasattr(response.transactionResponse, 'messages') is True:
                print(
                    'Successfully created transaction with Transaction ID: %s'
                    % response.transactionResponse.transId)
                print('Transaction Response Code: %s' %
                      response.transactionResponse.responseCode)
                print('Message Code: %s' %
                      response.transactionResponse.messages.message[0].code)
                print('Description: %s' % response.transactionResponse.
                      messages.message[0].description)
                return "Success"
            else:
                print('Failed Transaction.')
                if hasattr(response.transactionResponse, 'errors') is True:
                    print('Error Code:  %s' % str(response.transactionResponse.
                                                  errors.error[0].errorCode))
                    print(
                        'Error message: %s' %
                        response.transactionResponse.errors.error[0].errorText)
                return "Fail"
        # Or, print errors if the API request wasn't successful
        else:
            print('Failed Transaction.')

            if hasattr(response, 'transactionResponse') is True and hasattr(
                    response.transactionResponse, 'errors') is True:
                print('Error Code: %s' % str(
                    response.transactionResponse.errors.error[0].errorCode))
                print('Error message: %s' %
                      response.transactionResponse.errors.error[0].errorText)
            else:
                print('Error Code: %s' %
                      response.messages.message[0]['code'].text)
                print('Error message: %s' %
                      response.messages.message[0]['text'].text)
            return "Fail"
    else:
        print('Null Response.')
        return "Fail"

    return response