Coder Social home page Coder Social logo

sdk-python's Introduction

Authorize.Net Python SDK

Travis CI Status Coverage Status Scrutinizer Code Quality PyPI

Requirements

  • For Python 2, Python 2.7 or greater
  • For Python 3, Python 3.4 or later
  • OpenSSL 1.0.2 or greater
  • An Authorize.Net account (see Registration & Configuration section below)

Note: Our goal is ensuring this SDK is compatible with Python 2.7+, 3.4+ and PyPy, but at the moment we're primarily testing against Python 2.7.

Contribution

  • If you need information or clarification about Authorize.Net features, create an issue with your question. You can also search the Authorize.Net developer community for discussions related to your question.
  • Before creating pull requests, please read the contributors guide.

TLS 1.2

The Authorize.Net APIs only support connections using the TLS 1.2 security protocol. Make sure to upgrade all required components to support TLS 1.2. Keep these components up to date to mitigate the risk of new security flaws.

Installation

To install the AuthorizeNet Python SDK:

pip install authorizenet

Registration & Configuration

Use of this SDK and the Authorize.Net APIs requires having an account on the Authorize.Net system. You can find these details in the Settings section. If you don't currently have a production Authorize.Net account, sign up for a sandbox account.

Authentication

To authenticate with the Authorize.Net API, use your account's API Login ID and Transaction Key. If you don't have these credentials, obtain them from the Merchant Interface. For production accounts, the Merchant Interface is located at (https://account.authorize.net/), and for sandbox accounts, at (https://sandbox.authorize.net).

After you have your credentials, load them into the appropriate variables in your code. The below sample code shows how to set the credentials as part of the API request.

To set your API credentials for an API request:

	merchantAuth = apicontractsv1.merchantAuthenticationType()
	merchantAuth.name = 'YOUR_API_LOGIN_ID'
	merchantAuth.transactionKey = 'YOUR_TRANSACTION_KEY'

Never include your API Login ID and Transaction Key directly in a file in a publicly accessible portion of your website. As a best practice, define the API Login ID and Transaction Key in a constants file, and reference those constants in your code.

Switching between the sandbox environment and the production environment

Authorize.Net maintains a complete sandbox environment for testing and development purposes. The sandbox environment is an exact replica of our production environment, with simulated transaction authorization and settlement. By default, this SDK is configured to use the sandbox environment. To switch to the production environment, use the setenvironment method on the controller before executing. For example:

# For PRODUCTION use
	createtransactioncontroller.setenvironment(constants.PRODUCTION)

API credentials are different for each environment, so be sure to switch to the appropriate credentials when switching environments.

Enable Logging in the SDK

Python SDK uses the logger 'authorizenet.sdk'. By default, the logger in the SDK is not configured to write output. You can configure the logger in your code to start seeing logs from the SDK.

A sample logger configuration is given as below:

	import logging
	logger = logging.getLogger('authorizenet.sdk')
	handler = logging.FileHandler('anetSdk.log')  
	formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
	handler.setFormatter(formatter)
	logger.addHandler(handler)
	logger.setLevel(logging.DEBUG)
	logger.debug('Logger set up for Authorizenet Python SDK complete')

SDK Usage Examples and Sample Code

When using this SDK, downloading the Authorize.Net sample code repository is recommended.

The repository contains comprehensive sample code for common uses of the Authorize.Net API.

The API Reference contains details and examples of the structure and formatting of the Authorize.Net API.

Use the examples in the API Reference to determine which methods and information to include in an API request using this SDK.

Create a Chase Pay Transaction

Use this method to authorize and capture a payment using a tokenized credit card number issued by Chase Pay. Chase Pay transactions are only available to merchants using the Paymentech processor.

The following information is required in the request:

  • The payment token,
  • The expiration date,
  • The cryptogram received from the token provider,
  • The tokenRequestorName,
  • The tokenRequestorId, and
  • The tokenRequestorEci.

When using the SDK to submit Chase Pay transactions, consider the following points:

  • tokenRequesterName must be populated with ”CHASE_PAY”
  • tokenRequestorId must be populated with the Token Requestor ID provided by Chase Pay services for each transaction during consumer checkout
  • tokenRequesterEci must be populated with the ECI Indicator provided by Chase Pay services for each transaction during consumer checkout

Building & Testing the SDK

Requirements

  • python 2.7
  • pyxb 1.2.5

Run the following to get pyxb and nosetests:

  • pip install pyxb==1.2.5
  • pip install nose
  • pip install lxml

Running the SDK Tests

  • Tests available are: unit tests, mock tests, sample code
  • use nosetests to run all unittests

>nosetests

Testing Guide

For additional help in testing your own code, Authorize.Net maintains a comprehensive testing guide that includes test credit card numbers to use and special triggers to generate certain responses from the sandbox environment.

Transaction Hash Upgrade

Authorize.Net is phasing out the MD5 based transHash element in favor of the SHA-512 based transHashSHA2. The setting in the Merchant Interface which controlled the MD5 Hash option is no longer available, and the transHash element will stop returning values at a later date to be determined. For information on how to use transHashSHA2, see the [Transaction Hash Upgrade Guide] (https://developer.authorize.net/support/hash_upgrade/).

License

This repository is distributed under a proprietary license. See the provided LICENSE.txt file.

sdk-python's People

Contributors

adavidw avatar agarwal-akshay avatar akankaria avatar anuragg29 avatar ashtru avatar brianmc avatar eechien avatar egodolja avatar gnongsie avatar katterisharath avatar kikmak42 avatar lilithmm avatar namanbansal avatar ramittal avatar ravishankar54 avatar saikatbasu01 avatar sapbasu15 avatar snavinch avatar stvsmth avatar sudhirkumar2018 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sdk-python's Issues

API always uses sandbox

There seems to be a bug on the python SDK. It is hardcoded to always use the sandbox. The issue can bee seen on the APIOperationBase(APIOperationBaseInterface) class on the execute method.

I have fixed the issue on my fork by just changing it to PRODUCTION. The way the code is set right now, there is no way to override this behavior.

Cheers

Access denied. You do not have permissions to call the Transaction Details API.

So I'm working on getting used to the python API for Authorize.Net, however I seem to be running into the following issues with the API-

Code: E00011
Text: Access denied. You do not have permissions to call the Transaction Details API.

And all the logs will tell me is this,

2018-09-20 11:54:51,750 authorizenet.sdk DEBUG    performing custom validation..
2018-09-20 11:54:51,750 authorizenet.sdk DEBUG    Executing http post to url: https://apitest.authorize.net/xml/v1/request.api
2018-09-20 11:54:51,750 authorizenet.sdk DEBUG    building request..
2018-09-20 11:54:52,337 authorizenet.sdk ERROR    Create Document Exception: <class 'pyxb.exceptions_.IncompleteElementContentError'>, (<authorizenet.apicontractsv1.CTD_ANON_70 object at 0x7fb5ee5c3080>, <pyxb.utils.fac.Configuration object at 0x7fb5ee5c3128>, None, None)

And I don't know how to get more information.

Multiple Accepting Headers

I'm using the python-SDK in an AWS Lambda function and I noticed the following in my logs:

[WARNING] 2018-09-17T19:53:00.466Z 47785214-bab3-11e8-a21c-b3b49941b23e Multiple accepting paths for <class 'authorizenet.apicontractsv1.CTD_ANON_39'>

This same type of message is shown in the log for each api call, except the CTD_ANON_## appears to change based on the type of API call I'm making. Could you provide any insight into what this warning means?

Thanks!

MixedContentError: Invalid non-element content

Hi,

We used this SDK in a live environment, We got following error while performs an operation to create customer profiles since all things are well in the form. So, I did not understand why it will give error. Please reply as soon as possible.

Other things I want to know why you have applied you own _XSDLocation in the SDK and Current SDK in Beta development status. So, When It will be ready or stable.

File "/usr/local/lib/python2.7/dist-packages/pyxb/binding/basis.py", line 2094, in init
self.extend(args, _from_xml=from_xml, _location=location)
File "/usr/local/lib/python2.7/dist-packages/pyxb/binding/basis.py", line 2579, in extend
[ self.append(_v, **kw) for _v in value_list ]
File "/usr/local/lib/python2.7/dist-packages/pyxb/binding/basis.py", line 2506, in append
self._appendWildcardElement(value)
File "/usr/local/lib/python2.7/dist-packages/pyxb/binding/basis.py", line 2572, in _appendWildcardElement
raise pyxb.MixedContentError(self, value)
MixedContentError: Invalid non-element content

Import error with pip 9.0.2

Importing the authorizenet library fails with pip 9.0.2:

  File "/srv/wing/.env/local/lib/python2.7/site-packages/authorizenet/apicontrollers.py", line 9, in <module>
    from authorizenet import apicontrollersbase    
  File "/srv/wing/.env/local/lib/python2.7/site-packages/authorizenet/apicontrollersbase.py", line 11, in <module>
    from pip._vendor import requests
  File "/srv/wing/.env/local/lib/python2.7/site-packages/pip/__init__.py", line 45, in <module>
    from pip.vcs import git, mercurial, subversion, bazaar  # noqa
  File "/srv/wing/.env/local/lib/python2.7/site-packages/pip/vcs/mercurial.py", line 9, in <module>
    from pip.download import path_to_url
  File "/srv/wing/.env/local/lib/python2.7/site-packages/pip/download.py", line 40, in <module>
    from pip._vendor import requests, six
  File "/srv/wing/.env/local/lib/python2.7/site-packages/pip/_vendor/requests/__init__.py", line 98, in <module>
    from . import packages
  File "/srv/wing/.env/local/lib/python2.7/site-packages/pip/_vendor/requests/packages.py", line 12, in <module>
    sys.modules['pip._vendor.requests.packages.' + mod] = sys.modules["pip._vendor." + mod]
KeyError: 'pip._vendor.urllib3.contrib'

Pip 9.0.2 was literally released a couple hours ago as I write this, and it seems like pip changed its vendored packages around, including upgrading requests and explicitly vendoring urllib3 (see this commit).

However, this isn't a pip problem, this is a problem with using pip's vendored version of requests instead of an explicit dependency.

Content handling error

Hello,

There's a couple of changes that I've noted are needed for Python 3.5 support, specifically in relation to how meta-classes are handled, as well as the various print() requirements. In addition to this, a couple constants need to be made into binary fields, not huge stuff.

The main issue I'm running into is that the current version here doesn't support the new 'entryMode' field on the transactionResponse. Having enabled the production XSD and rebuilding it, it appears that pyxb or the class is breaking on an error with accountType.

I also noted that this system swallows exceptions, leading to situations where our systems were finishing a transaction and not aborting, as our try-excepts were not tripping thanks to the logging being sent to logging.debug, rather than sending up an exception.

Any chance these could be looked into? My branch is fairly hacked up, and likely will break py 2.x support.

Thanks!
Alexander Blair

IncompleteElementContentError when getting transaction details without access

I checked that API returns:

E00011 : Access denied. You do not have permissions to call the Transaction Details API.

But SDK raise an error:

/home/vagrant/proj/whauthorize/models.pyc in get_transaction_details(self, trans_id)
    158     def get_transaction_details(self, trans_id):
    159         transactionDetailsRequest = apicontractsv1.getTransactionDetailsRequest()
    160         transactionDetailsRequest.merchantAuthentication = self.get_merchant()
    161         transactionDetailsRequest.transId = trans_id
    162         controller = apicontrollers.getTransactionDetailsController(transactionDetailsRequest)
    163         if not settings.AUTHORIZE_TEST:
    164             controller.setenvironment(constants.PRODUCTION)
--> 165         controller.execute()
    166
    167         return controller.getresponse()

/home/vagrant/.venv/local/lib/python2.7/site-packages/authorizenet/apicontrollersbase.pyc in execute(self)
    151                 self._response = apicontractsv1.CreateFromDocument(self._httpResponse)
    152                 #objectify code
--> 153                 xmlResponse= self._response.toxml(encoding=constants.xml_encoding, element_name=self.getrequesttype())
    154                 xmlResponse = xmlResponse.replace(constants.nsNamespace1, b'')
    155                 xmlResponse = xmlResponse.replace(constants.nsNamespace2, b'')

/home/vagrant/.venv/local/lib/python2.7/site-packages/pyxb/binding/basis.pyc in toxml(self, encoding, bds, root_only, element_name)
    553         to XML anyway.
    554         """
--> 555         dom = self.toDOM(bds, element_name=element_name)
    556         if root_only:
    557             dom = dom.documentElement

/home/vagrant/.venv/local/lib/python2.7/site-packages/pyxb/binding/basis.pyc in toDOM(self, bds, parent, element_name)
    525         if need_xsi_type:
    526             bds.addAttribute(element, XSI.type, self._ExpandedName)
--> 527         self._toDOM_csc(bds, element)
    528         bds.finalize()
    529         return bds.document()

/home/vagrant/.venv/local/lib/python2.7/site-packages/pyxb/binding/basis.pyc in _toDOM_csc(self, dom_support, parent)
   2659         else:
   2660             if pyxb.GlobalValidationConfig.forDocument:
-> 2661                 order = self._validatedChildren()
   2662             else:
   2663                 order = self.__childrenForDOM()

/home/vagrant/.venv/local/lib/python2.7/site-packages/pyxb/binding/basis.pyc in _validatedChildren(self)
   2186             return []
   2187         self._resetAutomaton()
-> 2188         return self.__automatonConfiguration.sequencedChildren()
   2189
   2190     def _symbolSet (self):

/home/vagrant/.venv/local/lib/python2.7/site-packages/pyxb/binding/content.pyc in sequencedChildren(self)
    636                 break
    637             cfg = selected_xit.apply(cfg)
--> 638         cfg = self._diagnoseIncompleteContent(symbols, symbol_set)
    639         if symbol_set:
    640             raise pyxb.UnprocessedElementContentError(self.__instance, cfg, symbols, symbol_set)

/home/vagrant/.venv/local/lib/python2.7/site-packages/pyxb/binding/content.pyc in _diagnoseIncompleteContent(self, symbols, symbol_set)
    491             cfg = cfg.superConfiguration
    492         if not cfg.isAccepting():
--> 493             raise pyxb.IncompleteElementContentError(self.__instance, cfg, symbols, symbol_set)
    494         return cfg
    495

IncompleteElementContentError: (<authorizenet.apicontractsv1.CTD_ANON_71 object at 0x7f23e111d3d0>, <pyxb.utils.fac.Configuration object at 0x7f23e111d350>, [<pyxb.binding.basis.Elem
entContent object at 0x7f23e111d890>], {})

Errors in documentation - Authorize.Net Accept Hosted

https://developer.authorize.net/api/reference/features/accept_hosted.html
Under Hosted Form Parameter Settings
hostedPaymentReturnOptions parameters are specified as:

{"showReceipt" : "true", "url":"https://mysite.com/receipt", "urlText": "Continue", "cancelUrl": "https://mysite.com/cancel", cancelUrlText: "This request was cancelled."}

but need to be:

{"showReceipt" : true, "url":"https://mysite.com/receipt", "urlText": "Continue", "cancelUrl": "https://mysite.com/cancel", "cancelUrlText": "This request was cancelled."}

This probably applies to other languages but I post here as I'm working with python.

As a side note, is there any python related documentation as to how to implement the Accept Hosted form as a lightbox popup? Or even non-python specific documentation?

Pip install issues

Hello,

I am new to python . I am trying to install gTTS . currently using pip install throws this error below. Please advice how should i go about it.

Pip version : 18.1
Python version : 3.7.2

Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x000002F7E0FC2668>, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/gtts/
Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x000002F7E0FC2208>, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/gtts/
Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x000002F7E0FC23C8>, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/gtts/
Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x000002F7E0FC21D0>, 'Connection to pypi.org timed out. (connect timeout=15)')': /simple/gtts/
Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x000002F7E0FE1048>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')': /simple/gtts/
Could not find a version that satisfies the requirement gTTS (from versions: )
No matching distribution found for gTTS

Also, i have tried to check the network pulls using :
import pip._vendor.requests as requests
response_certifi = requests.get("https://pypi.python.org", verify=True)
print (response_certifi)
error message :
AttributeError: module 'pip._vendor.requests' has no attribute 'Session'

Tests not passing

Running the simple "Hello World" example from the readme fails, with no response returned, using my sandbox credentials. This matches what I am seeing in my own transaction unit tests. What's more, when I clone the repo separately, the tests also fail. This seems to coincide with the TLS 1.2 update to the Sandbox environment.

I am working on a Django 1.7.7 project, with Python 2.7.10 and OpenSSL 1.0.2l (latest). This all matches what I am seeing here: https://community.developer.authorize.net/t5/The-Authorize-Net-Developer-Blog/Request-for-Comments-API-Best-Practices/ba-p/53668?utm_campaign=Merchant%20TLS%20Notice.html&utm_medium=email&utm_source=Eloqua

I notice that the sample-code-python repo build is also failing (as well as tests). Is this my environment, or the library code? Is there anything else I need to do re: the upgrade?
https://community.developer.authorize.net/t5/The-Authorize-Net-Developer-Blog/TLS-1-1-and-1-0-Disabled-in-Sandbox-on-April-30-2017-Updated/ba-p/57726

Cannot disable logging

Looks like the logging info is writing to a file called anetsdk.log by default. I need to disable this log, as all messages are being handled by exceptions, and the log file is causing issues with permissions on every server that my software is being deployed to.

Any ideas on how to disable this via configuration?

Leading 0's In Zip Codes Being Eaten

Hey guys. It looks like you guys convert a zip code string that we give you into an int. Problem is that zip codes can start with a 0. And because you guys convert the string to an int, the 0 is getting dropped.

Because of this, some of our users are unable to make payments; their card gets declined for having the wrong address.

AttributeError: no such child: {AnetApi/xml/v1/schema/AnetApiSchema.xsd}profileResponse

I'm currently trying to have it make a customer profile on a transaction creation.

It is telling me that the child does not exist, I'm pretty tired by this point, I posted on Stackoverflow, I also posted on the developer thread, either no one replies, or no one has any idea why this isn't working.

Any help?

The following code I am using is

merchantAuth.name = app_config.AUTHORIZE_KEYS['apiLoginId']
merchantAuth.transactionKey = app_config.AUTHORIZE_KEYS['transactionKey']
# Create the payment object for a payment nonce
opaqueData = apicontractsv1.opaqueDataType()
opaqueData.dataDescriptor = request.form['dataDesc']
opaqueData.dataValue = request.form['dataValue']

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

# Create order information
order = apicontractsv1.orderType()
order.invoiceNumber = "invoice_%s" % user.id
order.description = "Awesome"
# Set the customer's identifying information
customerData = apicontractsv1.customerDataType()
customerData.type = "individual"
customerData.id = "cus_%s" % user.id
customerData.email = email
# Giving the credit card info
# Setting billing information
billto = apicontractsv1.nameAndAddressType()
billto.firstName = request.form['firstName']
billto.lastName = request.form['lastName']
billto.address = address1
billto.city = city
billto.state = state
billto.zip = zipcode
billto.country = country
item = request.form['item']
if item == 'dollar':
    amount = "3.00"
if item == "monthly":
    amount = "5.00"
    length = 1
if item == "annual":
    amount = "50.00"
    length = 12
# Create order information
order = apicontractsv1.orderType()
order.invoiceNumber = "invoice_%s" % user.id
order.description = "Awesomeness"

# # Set the customer's Bill To address
customerAddress = apicontractsv1.customerAddressType()
customerAddress.firstName = request.form['firstName']
customerAddress.lastName = request.form['lastName']
customerAddress.address = address1
customerAddress.city = city
customerAddress.state = state
customerAddress.zip = zipcode
customerAddress.country = country

# Create customer profile on transaction
createcustomerprofile = apicontractsv1.customerProfilePaymentType()
createcustomerprofile.createProfile = True

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

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

# Create the controller
createtransactioncontroller = createTransactionController(createtransactionrequest)
createtransactioncontroller.setenvironment(app_config.AUTH_NET_ENVIRONMENT)
createtransactioncontroller.execute()

The problem is when I try and parse the response, it tells me that it does not have a profileResponse, but the documenation shows that it should, also the schema does, it prints this things fin

 'messages': {'transId':'%s' % response.transactionResponse.transId,
 'responseCode':'%s' % response.transactionResponse.responseCode,
 'auth_code':'%s' % response.transactionResponse.messages.message[0].code,
                                                    'Description':'%s' % response.transactionResponse.messages.message[0].description,
                                                    

so I know it processes the transaction but it does not create the customer in the CIM, this causes the error

print(response.profileResponse.customerProfileId)
print(response.profileResponse.customerPaymentProfileIdList)

Error extracting transaction details when invalid characters present

There is a certain transaction in which the customer apparently included invalid characters in the address. When I run the Python script to download transaction details, it crashes, and I get the following traceback:

File "my_script.py", line 348, in
download_transaction_details('8386560251')
File "my_script.py", line 181, in download_transaction_details
transactionDetailsController.execute()
File "/Users/gpetty/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/authorizenet/apicontrollersbase.py", line 149, in execute
domResponse = xml.dom.minidom.parseString(self._httpResponse)
File "/Applications/Canopy.app/appdata/canopy-1.3.0.1715.macosx-x86_64/Canopy.app/Contents/lib/python2.7/xml/dom/minidom.py", line 1928, in parseString
return expatbuilder.parseString(string)
File "/Applications/Canopy.app/appdata/canopy-1.3.0.1715.macosx-x86_64/Canopy.app/Contents/lib/python2.7/xml/dom/expatbuilder.py", line 940, in parseString
return builder.parseString(string)
File "/Applications/Canopy.app/appdata/canopy-1.3.0.1715.macosx-x86_64/Canopy.app/Contents/lib/python2.7/xml/dom/expatbuilder.py", line 223, in parseString
parser.Parse(string, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1734-1735: ordinal not in range(128)

Will it be possible for the maintainers of this SDK to modify the code to handle such cases more gracefully -- e.g., by substituting '?' for invalid characters?

transaction 'tax' attribute changed or missing?

This line worked a few weeks ago (with version 1.0.9):
tax = transactionDetailsResponse.transaction.tax

Now (v. 1.0.11), it generates the following error:
File "src/lxml/lxml.objectify.pyx", line 229, in lxml.objectify.ObjectifiedElement.getattr (src/lxml/lxml.objectify.c:3835)
File "src/lxml/lxml.objectify.pyx", line 450, in lxml.objectify._lookupChildOrRaise (src/lxml/lxml.objectify.c:6539)
AttributeError: no such child: {AnetApi/xml/v1/schema/AnetApiSchema.xsd}tax

Other attributes of transactionDetailsResponse.transaction appear to still be present. The API guide still shows the following attributes as being valid:

  • tax Contains information about any taxes.

** amount Amount of the tax.

** name Name of the tax.

** description Description of the tax.

ARBSubscriptionType issue with Python 3.8

When updating from Python 3.7 => 3.8, I've started to receive the following complaint from Authorize.net / PyXB:

TypeError: function takes 3 arguments plus optional tzinfo (8 given)
  File "authorizenet/apicontrollersbase.py", line 134, in execute
    xmlRequest = self.buildrequest()
  File "authorizenet/apicontrollersbase.py", line 105, in buildrequest
    xmlRequest = self._request.toxml(encoding=constants.xml_encoding, element_name=self.getrequesttype())
  File "pyxb/binding/basis.py", line 555, in toxml
    dom = self.toDOM(bds, element_name=element_name)
  File "pyxb/binding/basis.py", line 527, in toDOM
    self._toDOM_csc(bds, element)
  File "pyxb/binding/basis.py", line 2675, in _toDOM_csc
    content.elementDeclaration.toDOM(dom_support, parent, content.value)
  File "pyxb/binding/content.py", line 1101, in toDOM
    value._toDOM_csc(dom_support, element)
  File "pyxb/binding/basis.py", line 2675, in _toDOM_csc
    content.elementDeclaration.toDOM(dom_support, parent, content.value)
  File "pyxb/binding/content.py", line 1101, in toDOM
    value._toDOM_csc(dom_support, element)
  File "pyxb/binding/basis.py", line 2675, in _toDOM_csc
    content.elementDeclaration.toDOM(dom_support, parent, content.value)
  File "pyxb/binding/content.py", line 1101, in toDOM
    value._toDOM_csc(dom_support, element)
  File "pyxb/binding/basis.py", line 1119, in _toDOM_csc
    dom_support.appendTextChild(self, parent)
  File "pyxb/utils/domutils.py", line 584, in appendTextChild
    return parent.appendChild(self.document().createTextNode(self.valueAsText(text)))
  File "pyxb/utils/domutils.py", line 402, in valueAsText
    return value.xsdLiteral()
  File "pyxb/binding/basis.py", line 992, in xsdLiteral
    return self.XsdLiteral(self)
  File "pyxb/binding/datatypes.py", line 738, in XsdLiteral
    value += datetime.timedelta(minutes=cls.__MinutesPerHalfDay)
  File "pyxb/binding/datatypes.py", line 662, in __new__
    raise TypeError('function takes %d arguments plus optional tzinfo (%d given)' % (len(cls._ValidFields), len(args)))

It seems to be related to the paymentScheduleType.startDate property. I've tried setting it to a pyxb date, a python datetime.date, and a string. None of these work. And if I roll back to Python 3.7, the issue goes away. Any thoughts or suggestions? Is this a mistake on my end?

UnicodeEncodeError on getTransactionListRequest

I'm making a request to get a TransactionList from a batchId but am encountering a UnicodeEncodeError:
{UnicodeEncodeError}'ascii' codec can't encode characters in position 6631-6632: ordinal not in range(128)
It's erroring on line 162, of apicontrollersbase.py:
domResponse = xml.dom.minidom.parseString(self._httpResponse)
self._httpResponse contains character u'\xe9'. So I was able to pass a unicode character to create a transaction but am not able to get that information back.

Get Customer Profile Transaction List - 'getTransactionListForCustomerResponse' not defined

As per documentation I was trying to use the Get Customer Profile Transaction List endpoint. After looking over the 'apicontractsv1' file here on github it appears that 'getTransactionListForCustomerResponse' is not defined. I'm unable to use the SDK to access the endpoint.

Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\Parker\Documents\projects\whatever\what\payment\auth_net.py", line 122, in get_customer_profile_transactions controller.execute() File "C:\Users\Parker\Documents\projects\whatever\venv\lib\site-packages\authorizenet\apicontrollersbase.py", line 161, in execute if type(self.getresponseclass()) != type(self._mainObject): File "C:\Users\Parker\Documents\projects\whatever\venv\lib\site-packages\authorizenet\apicontrollers.py", line 709, in getresponseclass return apicontractsv1.getTransactionListForCustomerResponse() AttributeError: module 'authorizenet.apicontractsv1' has no attribute 'getTransactionListForCustomerResponse'

Question: Deprecated transHash Field

According to MD5 Hash End of Life & Signature Key Replacement, the MD5 hash in the transHash field is being phased out and will be removed from responses soon.

I see that transHash and transHashSHA2 are referenced a few places in the apicontractsv1.py module:

./authorizenet/apicontractsv1.py:8009:    # Element {AnetApi/xml/v1/schema/AnetApiSchema.xsd}transHash uses Python identifier transHash
./authorizenet/apicontractsv1.py:8010:    __transHash = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(Namespace, 'transHash'), 'transHash', '__AnetApixmlv1schemaAnetApiSchema_xsd_transactionResponse_AnetApixmlv1schemaAnetApiSchema_xsdtransHash', False, pyxb.utils.utility.Location('https://apitest.authorize.net/xml/v1/schema/AnetApiSchema.xsd', 2542, 6), )                    
./authorizenet/apicontractsv1.py:8013:    transHash = property(__transHash.value, __transHash.set, None, None)
./authorizenet/apicontractsv1.py:8107:    # Element {AnetApi/xml/v1/schema/AnetApiSchema.xsd}transHashSha2 uses Python identifier transHashSha2
./authorizenet/apicontractsv1.py:8108:    __transHashSha2 = pyxb.binding.content.ElementDeclaration(pyxb.namespace.ExpandedName(Namespace, 'transHashSha2'), 'transHashSha2', '__AnetApixmlv1schemaAnetApiSchema_xsd_transactionResponse_AnetApixmlv1schemaAnetApiSchema_xsdtransHashSha2', False, pyxb.utils.utility.Location('https://apitest.authorize.net/xml/v1/schema/AnetApiSchema.xsd', 2648, 6), )
./authorizenet/apicontractsv1.py:8111:    transHashSha2 = property(__transHashSha2.value, __transHashSha2.set, None, None)
./authorizenet/apicontractsv1.py:8137:        __transHash.name() : __transHash,
./authorizenet/apicontractsv1.py:8151:        __transHashSha2.name() : __transHashSha2,
./authorizenet/apicontractsv1.py:26703:transactionResponse._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(Namespace, 'transHash'), pyxb.binding.datatypes.string, scope=transactionResponse, location=pyxb.utils.utility.Location('https://apitest.authorize.net/xml/v1/schema/AnetApiSchema.xsd', 2542, 6)))                                                                              
./authorizenet/apicontractsv1.py:26731:transactionResponse._AddElement(pyxb.binding.basis.element(pyxb.namespace.ExpandedName(Namespace, 'transHashSha2'), pyxb.binding.datatypes.string, scope=transactionResponse, location=pyxb.utils.utility.Location('https://apitest.authorize.net/xml/v1/schema/AnetApiSchema.xsd', 2648, 6)))                                                                          
./authorizenet/apicontractsv1.py:26839:    symbol = pyxb.binding.content.ElementUse(transactionResponse._UseForTag(pyxb.namespace.ExpandedName(Namespace, 'transHash')), pyxb.utils.utility.Location('https://apitest.authorize.net/xml/v1/schema/AnetApiSchema.xsd', 2542, 6))                                                                                                                                
./authorizenet/apicontractsv1.py:26909:    symbol = pyxb.binding.content.ElementUse(transactionResponse._UseForTag(pyxb.namespace.ExpandedName(Namespace, 'transHashSha2')), pyxb.utils.utility.Location('https://apitest.authorize.net/xml/v1/schema/AnetApiSchema.xsd', 2648, 6))

Will the imminent removal of the transHash field from responses cause response parsing to break in the SDK as it stands today? Or will it handle the absence of the transHash gracefully?

Get Transaction Details Info Errror

We are getting a Create Document Exception: <class 'pyxb.exceptions_.ContentNondeterminismExceededError'>, (<authorizenet.apicontractsv1. customerAddressType object at 0x7f2ecf0129b0> every time we pull transaction details from the API. The error is occurring on line 149 of apicontrollersbase.py.

The code being used to fetch the transaction details is (some login settings omitted)

from authorizenet import apicontractsv1
from authorizenet.apicontrollers import getTransactionDetailsController

    def verify_transaction(self, transaction_id, amount):
        logging.debug("Verifyng transaction id %s" % transaction_id)
        transaction_details_request = apicontractsv1.getTransactionDetailsRequest()
        transaction_details_request.merchantAuthentication = self.merchantAuth
        transaction_details_request.transId = transaction_id

        transaction_details_controller = getTransactionDetailsController(transaction_details_request)
        transaction_details_controller.setenvironment(self.environment)

        transaction_details_controller.execute()

        transaction_details_response = transaction_details_controller.getresponse()

        if transaction_details_response is None or transaction_details_response.messages.resultCode != apicontractsv1.messageTypeEnum.Ok or transaction_details_response.transaction.transactionStatus != 'capturedPendingSettlement' or transaction_details_response.transaction.authAmount != amount:
                    return False

        return True

The XML being returned from the sandbox API is:

<?xml version="1.0" encoding="UTF-8"?>
<getTransactionDetailsResponse xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <messages>
      <resultCode>Ok</resultCode>
      <message>
         <code>I00001</code>
         <text>Successful.</text>
      </message>
   </messages>
   <transaction>
      <transId>40014999477</transId>
      <submitTimeUTC>2018-06-15T15:07:53.33Z</submitTimeUTC>
      <submitTimeLocal>2018-06-15T08:07:53.33</submitTimeLocal>
      <transactionType>authCaptureTransaction</transactionType>
      <transactionStatus>capturedPendingSettlement</transactionStatus>
      <responseCode>1</responseCode>
      <responseReasonCode>1</responseReasonCode>
      <responseReasonDescription>Approval</responseReasonDescription>
      <authCode>THPCHV</authCode>
      <AVSResponse>Y</AVSResponse>
      <cardCodeResponse>P</cardCodeResponse>
      <authAmount>240.00</authAmount>
      <settleAmount>240.00</settleAmount>
      <taxExempt>false</taxExempt>
      <payment>
         <creditCard>
            <cardNumber>XXXX1111</cardNumber>
            <expirationDate>XXXX</expirationDate>
            <cardType>Visa</cardType>
         </creditCard>
      </payment>
      <billTo>
         <firstName>2</firstName>
         <lastName>2</lastName>
         <address>add</address>
         <city>City</city>
         <state>VA</state>
         <zip>20176</zip>
         <country>USA</country>
         <phoneNumber>2222222222</phoneNumber>
      </billTo>
      <recurringBilling>false</recurringBilling>
      <customerIP>11.111.1.11</customerIP>
      <product>Card Not Present</product>
      <marketType>eCommerce</marketType>
   </transaction>
   <clientId>accept-hosted</clientId>
</getTransactionDetailsResponse>

We are seeing this error when hitting the live API as well. It doesn't appear to cause any issues, as payments still process fine, but seeing the error in our logs is concerning.

Issue with importing requests from pip

Hi.
So, I am having some issues with the SDK, specifically when I try to perform some request.

The error I get is "AttributeError: module 'pip._vendor.requests' has no attribute 'Session'"
I took a look around and I found some topics saying that was fixed in release 1.1.0, however I just downloaded the SDK 1.1.0 and I still get the same error.

Under the PIP repository here in github, there is an user that does dev to the PIP repo states "We do not support for importing internal components of pip in your own program. You should be including requests in your requirements directly if you need to use it. For details see the pip docs. You should report this issue to the authors of authorizenet."
Reference: pypa/pip#5267 (comment)

9 months ago I had to download the lib and modify the authorizenet sdk files myself in order to get working, I just removed the import from the pip._venders.requests library and add the import of requests directly, (import requests) that fixed the issue. However, now that you guys updated the lIbrary, I have to perform the update again, and in the future when you guys update I still need to update manually.

It would be great to just have the version in PIP working fine. Is there a reason why you guys are still doing the import for the lib requests from pip._vendors instead of doing the import of requests directly?

Kind regards,
Rafael Juzwiak

WARNING Multiple accepting paths for <class 'authorizenet.apicontractsv1.CTD_ANON_##'>

Hi There,
I'm getting below errors(or some related ones) on my console while charging a credit card(or creating a subscription):

WARNING Multiple accepting paths for <class 'authorizenet.apicontractsv1.CTD_ANON_9'>
WARNING Multiple accepting paths for <class 'authorizenet.apicontractsv1.CTD_ANON_8'>
WARNING Multiple accepting paths for {AnetApi/xml/v1/schema/AnetApiSchema.xsd}transactionResponse

Currently, I'm testing these using Sandbox Credentials for Django(v1.8) using Python-sdk and have not tested on production.
Also, tell me if these are the matter of concern before going live.

Apply Release Engineering and Pin Versions of Required Libraries

You should explicitly list all required libraries, including requests, here:

install_requires=['pyxb==1.2.5', 'nose', 'mock', 'lxml'],

And you are being negligent by not specifying versions of each library you use. If you do not pin versions of libraries, it is unclear what your test cases actually mean when they passed---we do not know what versions of libraries your software works with.

Since commits are intermittent on this project, I highly recommend you pin the versions so that we don't have to worry about grabbing a new version that breaks your library---and in the worst case silently.

IncompleteElementContentError when trying to create a customer

I'm following the code in the examples to create a new customer profile and tokenize his credit card. If I plug in the sandbox credentials, it works fine, but if I put some production credentials I get a very cryptic exception:
File "/Users/grigore/ics/instacar-back/env/lib/python2.7/site-packages/pyxb/binding/content.py", line 493, in _diagnoseIncompleteContent raise pyxb.IncompleteElementContentError(self.__instance, cfg, symbols, symbol_set) pyxb.exceptions_.IncompleteElementContentError: (<authorizenet.apicontractsv1.CTD_ANON_35 object at 0x1064a0150>, <pyxb.utils.fac.Configuration object at 0x1064a0190>, [<pyxb.binding.basis.ElementContent object at 0x1064a0090>], {})

Here's the code I'm running:

from authorizenet.apicontrollers import *

merchantAuth = apicontractsv1.merchantAuthenticationType()
merchantAuth.name = 'my_api_login_id'
merchantAuth.transactionKey = 'my_transaction_key'


credit_card = apicontractsv1.creditCardType()
credit_card.cardNumber = '4111111111111111'
credit_card.expirationDate = '2017-05'
credit_card.cardCode = '123'

payment = apicontractsv1.paymentType()
payment.creditCard = credit_card


payment_profile = apicontractsv1.customerPaymentProfileType()
payment_profile.payment = payment

profile = apicontractsv1.customerProfileType()
profile.paymentProfiles = [payment_profile]


create_customer_profile_request = apicontractsv1.createCustomerProfileRequest()
create_customer_profile_request.merchantAuthentication = merchantAuth
create_customer_profile_request.profile = profile

controller = createCustomerProfileController(create_customer_profile_request)
controller.execute()

Getting Print statement error in apicontrollersbase.py Python 2 print in Python 3 Lib?

Hi,

Just trying this library and installed on Python35-32, when I run sample I get this error stack:
Am I using a wrong version?
Ryan

Traceback (most recent call last):
File "testauth.py", line 5, in
from authorizenet.apicontrollers import *
File "", line 969, in _find_and_load
File "", line 958, in _find_and_load_unlocked
File "", line 664, in _load_unlocked
File "", line 634, in _load_backward_compatible
File "D:\Python35-32\lib\site-packages\authorizenet-1.0.9-py3.5.egg\authorizen
et\apicontrollers.py", line 9, in
File "", line 969, in _find_and_load
File "", line 954, in _find_and_load_unlocked
File "", line 896, in _find_spec
File "", line 1136, in find_spec
File "", line 1112, in _get_spec
File "", line 1093, in _legacy_get_spec
File "", line 444, in spec_from_loader
File "", line 530, in spec_from_file_loc
ation
File "D:\Python35-32\lib\site-packages\authorizenet-1.0.9-py3.5.egg\authorizen
et\apicontrollersbase.py", line 147
print "Response error"
^
SyntaxError: Missing parentheses in call to 'print'

Roadmap?

Is this meant for public use or is this an internal project at the moment? If it's meant for the public, there appear to be a few things hindering adoption of this library. It would be great to have some clarity on the future of this project.

Test failures

There are many test failures related to pyxb contracts, which I'm not familiar with. There are lots of references to "C:\Users\krgupta\Desktop", so I'm assuming this is part of the problem? I submitted #55 to at least correct the README, so the test instructions will actually run the tests, but the tests fail even on master so my changes don't appear to be the culprit (tested under Python 2.7.11).

Python 3 Support

The README says "We'll be ensuring this SDK is compatible with Python 2.6+, 3.2+ and PyPy". However, this library is not compatible with Python 3.x. I've submitted #54 to fix usages of print as a statement (rather than a function) but there appears to be many other significant issues standing in the way of full Python 3 support. #56 is my attempt to start adding support for Python 3.4+ (3.2 is no longer supported as of February 2016 and 3.3 is only supported until September 2017, so it's questionable whether to support that version now).

JSON API

Are there any plans to introduce support for the JSON API?

AttributeError: module 'pip._vendor.requests' has no attribute 'Session

File "/answersingenesis/virtualpythons/answersingenesis.local/lib/python3.5/site-packages/authorizenet/apicontrollersbase.py", line 11, in
from pip._vendor import requests

Pip no longer supports import the requests library in this way. Instead, the requests library should be added to this package's requirements.txt, and imported directly.

Create Document Exception masked by objectify error handling

Every once in a while we get a Create Document Exception when we receive data that raises validation errors in pyxb when our code executes APIOperationBase.execute method. The way in which the error is handled, makes hard for our logging systems to catch and repair the input from the user.

A much better way to deal with this is to separate the objectify error handling from the CreateFromDocument process. That way if there're validation errors we can easly inspect them.

Related to #109

PyXB version requirement problem

setup.py merely requires PyXB, but use of version 1.2.4 is hard-coded into the code as a requirement. PyXB is at 1.2.5 now and thus installs or upgrades break. You need to specify version in setup.py or remove the hard-coded version check.

IncompleteElementContentError when trying to configure: hostedPaymentOrderOptions, hostedPaymentSecurityOptions and hostedPaymentBillingAddressOptions

I'm currently using a sandbox account to implement authorize.net SIM (hosted form) with a python e-commerce solution.

I am not able to successfully configure the parameters for the following:
hostedPaymentOrderOptions, hostedPaymentSecurityOptions and hostedPaymentBillingAddressOptions

I am able to use most other configuration options successfully but the three above give me this error:
The code fails on the paymentPageController.execute() line.

Error:

  Module authorizenet.apicontrollersbase, line 153, in execute
  Module pyxb.binding.basis, line 555, in toxml
  Module pyxb.binding.basis, line 527, in toDOM
  Module pyxb.binding.basis, line 2663, in _toDOM_csc
  Module pyxb.binding.basis, line 2190, in _validatedChildren
  Module pyxb.binding.content, line 638, in sequencedChildren
  Module pyxb.binding.content, line 493, in _diagnoseIncompleteContent
IncompleteElementContentError: (<authorizenet.apicontractsv1.CTD_ANON_86 object at 0x7faba45a4810>, <pyxb.utils.fac.Configuration object at 0x7faba45a43d0>, [<pyxb.binding.basis.ElementContent object at 0x7faba45a4250>], {})

My code (with lines settings.setting.append(setting4), settings.setting.append(setting6) and settings.setting.append(setting9) currently commented out as they are failing:

    def token(self):

        merchantAuth = apicontractsv1.merchantAuthenticationType()
        merchantAuth.name = get_setting('authorizenet_api_login_id_dev')
        merchantAuth.transactionKey = get_setting('authorizenet_transaction_key_dev')
        
        settingNameEnum = apicontractsv1.settingNameEnum

        setting1 = apicontractsv1.settingType()
        setting1.settingName = settingNameEnum.hostedPaymentButtonOptions
        setting1.settingValue = '{"text": "Pay"}'

        setting2 = apicontractsv1.settingType()
        setting2.settingName = settingNameEnum.hostedPaymentOrderOptions
        setting2.settingValue = '{"show": false}'

        setting3 = apicontractsv1.settingType()
        setting3.settingName = settingNameEnum.hostedPaymentReturnOptions
        setting3.settingValue = '{"showReceipt" : true, "url":"https://www.google.com", "urlText": "Continue", "cancelUrl": "https://www.yahoo.com", "cancelUrlText": "This request was cancelled."}'

        setting4 = apicontractsv1.settingType()
        setting4.settingName = settingNameEnum.hostedPaymentOrderOptions
        setting4.settingValue = '{"show": true, "merchantName":"BOOK SELLERS INC."}'

        setting5 = apicontractsv1.settingType()
        setting5.settingName = settingNameEnum.hostedPaymentStyleOptions
        setting5.settingValue = '{"bgColor": "red"}'

        setting6 = apicontractsv1.settingType()
        setting6.settingName = settingNameEnum.hostedPaymentSecurityOptions
        setting6.settingValue = '{"captcha": true}'

        setting7 = apicontractsv1.settingType()
        setting7.settingName = settingNameEnum.hostedPaymentBillingAddressOptions
        setting7.settingValue = '{"show": true, "required":true}'

        setting8 = apicontractsv1.settingType()
        setting8.settingName = settingNameEnum.hostedPaymentShippingAddressOptions
        setting8.settingValue = '{"show": true, "required":true}'

        setting9 = apicontractsv1.settingType()
        setting9.settingName = settingNameEnum.hostedPaymentBillingAddressOptions
        setting9.settingValue = '{"show": true, "required":true}'

        setting10 = apicontractsv1.settingType()
        setting10.settingName = settingNameEnum.hostedPaymentCustomerOptions
        setting10.settingValue = '{"showEmail": true, "requiredEmail":false}'

        settings = apicontractsv1.ArrayOfSetting()
        settings.setting.append(setting1)
        settings.setting.append(setting2)
        settings.setting.append(setting3)
#        settings.setting.append(setting4)
        settings.setting.append(setting5)
#        settings.setting.append(setting6)
        settings.setting.append(setting7)
        settings.setting.append(setting8)
   #     settings.setting.append(setting9)
        settings.setting.append(setting10)
        
        transactionrequest = apicontractsv1.transactionRequestType()
        transactionrequest.transactionType = "authCaptureTransaction"
        transactionrequest.amount = self.amount

        paymentPageRequest = apicontractsv1.getHostedPaymentPageRequest()
        paymentPageRequest.merchantAuthentication = merchantAuth
        paymentPageRequest.transactionRequest = transactionrequest
        paymentPageRequest.hostedPaymentSettings = settings

        paymentPageController = getHostedPaymentPageController(paymentPageRequest)
        paymentPageController.execute() # Makes a http-post call. 
        paymentPageResponse = paymentPageController.getresponse()

        if paymentPageResponse is not None:
            ok = apicontractsv1.messageTypeEnum.Ok
            if paymentPageResponse.messages.resultCode == ok:
		        print('Successfully got hosted payment page!')

		        print('Token : %s' % paymentPageResponse.token)

		        if paymentPageResponse.messages:
			        print('Message Code : %s' % \
                    paymentPageResponse.messages.message[0]['code'].text)
			        print('Message Text : %s' % \
                    paymentPageResponse.messages.message[0]['text'].text)
            else:
                if paymentPageResponse.messages:
                    print('Failed to get batch statistics.\nCode:%s \nText:%s'%\
                    (paymentPageResponse.messages.message[0]['code'].text,
                     paymentPageResponse.messages.message[0]['text'].text))

        return paymentPageResponse.token

Also here is the xml that is generated by the pyxb.binding.toxml method (with all the settings including the failing ones):

<?xml version="1.0" encoding="UTF-8"?>
<getHostedPaymentPageRequest xmlns:ns1="AnetApi/xml/v1/schema/AnetApiSchema.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <ns1:merchantAuthentication>
        <ns1:name>3mJwL8X68g7n</ns1:name>
        <ns1:transactionKey>33T3mQ38Djv6J22h</ns1:transactionKey>
    </ns1:merchantAuthentication>
    <ns1:clientId>sdk-python-1.0.13</ns1:clientId>
    <ns1:transactionRequest>
        <ns1:transactionType>authCaptureTransaction</ns1:transactionType>
        <ns1:amount>18.65</ns1:amount>
    </ns1:transactionRequest>
    <ns1:hostedPaymentSettings>
        <ns1:setting>
            <ns1:settingName xsi:type="ns1:settingNameEnum">hostedPaymentButtonOptions</ns1:settingName>
            <ns1:settingValue>{&amp;quot;text&amp;quot;: &amp;quot;Pay&amp;quot;}</ns1:settingValue>
        </ns1:setting>
        <ns1:setting>
            <ns1:settingName xsi:type="ns1:settingNameEnum">hostedPaymentOrderOptions</ns1:settingName>
            <ns1:settingValue>{&amp;quot;show&amp;quot;: false}</ns1:settingValue>
        </ns1:setting>
        <ns1:setting>
            <ns1:settingName xsi:type="ns1:settingNameEnum">hostedPaymentReturnOptions</ns1:settingName>
            <ns1:settingValue>{&amp;quot;showReceipt&amp;quot; : true, &amp;quot;url&amp;quot;:&amp;quot;https://www.reddit.com&amp;quot;, &amp;quot;urlText&amp;quot;: &amp;quot;Continue&amp;quot;, &amp;quot;cancelUrl&amp;quot;: &amp;quot;https://www.reddit.com&amp;quot;, &amp;quot;cancelUrlText&amp;quot;: &amp;quot;This request was cancelled.&amp;quot;}</ns1:settingValue>
        </ns1:setting>
        <ns1:setting>
            <ns1:settingName xsi:type="ns1:settingNameEnum">hostedPaymentOrderOptions</ns1:settingName>
            <ns1:settingValue>{&amp;quot;show&amp;quot;: true, &amp;quot;merchantName&amp;quot;:&amp;quot;BOOK SELLERS INC.&amp;quot;}</ns1:settingValue>
        </ns1:setting>
        <ns1:setting>
            <ns1:settingName xsi:type="ns1:settingNameEnum">hostedPaymentStyleOptions</ns1:settingName>
            <ns1:settingValue>{&amp;quot;bgColor&amp;quot;: &amp;quot;red&amp;quot;}</ns1:settingValue>
        </ns1:setting>
        <ns1:setting>
            <ns1:settingName xsi:type="ns1:settingNameEnum">hostedPaymentSecurityOptions</ns1:settingName>
            <ns1:settingValue>{&amp;quot;captcha&amp;quot;: true}</ns1:settingValue>
        </ns1:setting>
        <ns1:setting>
            <ns1:settingName xsi:type="ns1:settingNameEnum">hostedPaymentBillingAddressOptions</ns1:settingName>
            <ns1:settingValue>{&amp;quot;show&amp;quot;: true, &amp;quot;required&amp;quot;:true}</ns1:settingValue>
        </ns1:setting>
        <ns1:setting>
            <ns1:settingName xsi:type="ns1:settingNameEnum">hostedPaymentShippingAddressOptions</ns1:settingName>
            <ns1:settingValue>{&amp;quot;show&amp;quot;: true, &amp;quot;required&amp;quot;:true}</ns1:settingValue>
        </ns1:setting>
        <ns1:setting>
            <ns1:settingName xsi:type="ns1:settingNameEnum">hostedPaymentBillingAddressOptions</ns1:settingName>
            <ns1:settingValue>{&amp;quot;show&amp;quot;: true, &amp;quot;required&amp;quot;:true}</ns1:settingValue>
        </ns1:setting>
        <ns1:setting>
            <ns1:settingName xsi:type="ns1:settingNameEnum">hostedPaymentCustomerOptions</ns1:settingName>
            <ns1:settingValue>{&amp;quot;showEmail&amp;quot;: true, &amp;quot;requiredEmail&amp;quot;:false}</ns1:settingValue>
        </ns1:setting>
    </ns1:hostedPaymentSettings>
</getHostedPaymentPageRequest>

Do I need to set any special settings on my sandbox account? Or are some of these options not available to sandbox accounts? or is it something else?

Thank you for looking into this.

Python 3.6 compatibility

I haven't investigated fully yet, but running the sample code on Python 3.6 generates a few errors. For example:
Type {AnetApi/xml/v1/schema/AnetApiSchema.xsd}ArrayOfSetting cannot be created from {AnetApi/xml/v1/schema/AnetApiSchema.xsd}settingType: <authorizenet.apicontractsv1.settingType object at 0x7f20a2ca7710>
Don't know yet whether this is something that can be fixed in the samples, or there's an underlying incompatibility in the SDK.

Circular import issue

from pip._vendor import requests

authorizenet/apicontrollers.py", line 9, in
from authorizenet import apicontrollersbase
File "/home/delhivery/Downloads/nikhil/venv/local/lib/python2.7/site-packages/authorizenet/apicontrollersbase.py", line 11, in
from pip._vendor import requests
File "/home/delhivery/Downloads/nikhil/venv/local/lib/python2.7/site-packages/pip/_vendor/requests/init.py", line 83, in
from pip._internal.compat import WINDOWS
File "/home/delhivery/Downloads/nikhil/venv/local/lib/python2.7/site-packages/pip/_internal/init.py", line 42, in
from pip._internal import cmdoptions
File "/home/delhivery/Downloads/nikhil/venv/local/lib/python2.7/site-packages/pip/_internal/cmdoptions.py", line 16, in
from pip._internal.index import (
File "/home/delhivery/Downloads/nikhil/venv/local/lib/python2.7/site-packages/pip/_internal/index.py", line 15, in
from pip._vendor import html5lib, requests, six
ImportError: cannot import name requests

Better to directly import requests

Accept Hosted Form: Truncated Last Zero

We have noticed that the pricing/amount of the payment form is not showing all of of the cent values. For example, when we set the amount to "25.00" or "25.50", the price on the payment form is shown as "$25.0" or "25.5" respectively. If the payment is "25.01" then the payment is shown correctly.

AttributeError: no such child: {AnetApi/xml/v1/schema/AnetApiSchema.xsd}messages

When trying to create an accept js payment transaction we're occasionally getting this error:

AttributeError: no such child: {AnetApi/xml/v1/schema/AnetApiSchema.xsd}messages

We've used the example given here almost verbatim:
https://github.com/AuthorizeNet/sample-code-python/blob/master/PaymentTransactions/create-an-accept-payment-transaction.py

Looking at all the python samples I can't find a good example of what to do when messages doesn't exist on response.

UnicodeEncodeError on getTransactionDetailsRequest

Possibly related to #73, but at a different point in execute().

For transactions with non-ASCII characters, I'm getting UnicodeEncodeError: 'ascii' codec can't encode characters in position 873-874: ordinal not in range(128) when retrieving transaction details.

  File "[virtualenv]/lib/python2.7/site-packages/authorizenet/apicontrollersbase.py", line 156, in execute
    domResponse = xml.dom.minidom.parseString(self._httpResponse)
  File "/usr/lib64/python2.7/xml/dom/minidom.py", line 1928, in parseString
    return expatbuilder.parseString(string)
  File "/usr/lib64/python2.7/xml/dom/expatbuilder.py", line 940, in parseString
    return builder.parseString(string)
  File "/usr/lib64/python2.7/xml/dom/expatbuilder.py", line 223, in parseString
    parser.Parse(string, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 876-877: ordinal not in range(128)

#75 added xml.dom.minidom.parseString(self._httpResponse.encode('utf-8').decode('utf-8')) when logging an error see here, but the initial response parsing doesn't do so, and raises an uncaught exception.

Unable to import apicontrollers in python 3.5.2

I am working on a project for my place of employment using the python sdk, and am receiving a massive error when trying to from authorizenet import apicontrollers.

In my module authorize_net_api.py I have made my own class to interface with the sdk.

it starts with:

import os, sys
import imp
from authorizenet import apicontractsv1
from authorizenet import apicontrollers
from authorizenet.utility import *
from authorizenet import utility

through the process of elimination I commented the lines out and tested one by one to see which line was giving the error, and sure enough, it was the apicontrollers

when running my own tests using tox, I'm not even testing the API yet, just importing my class, I get this

.tox/py3/lib/python3.5/site-packages/_pytest/config.py:329: in _getconftestmodules
    return self._path2confmods[path]
E   KeyError: local('<redacted>/tests/api')

During handling of the above exception, another exception occurred:
.tox/py3/lib/python3.5/site-packages/_pytest/config.py:360: in _importconftest
    return self._conftestpath2mod[conftestpath]
E   KeyError: local('<redacted>/tests/api/conftest.py')

During handling of the above exception, another exception occurred:
.tox/py3/lib/python3.5/site-packages/_pytest/config.py:366: in _importconftest
    mod = conftestpath.pyimport()
.tox/py3/lib/python3.5/site-packages/py/_path/local.py:668: in pyimport
    __import__(modname)
<frozen importlib._bootstrap>:969: in _find_and_load
    ???
<frozen importlib._bootstrap>:958: in _find_and_load_unlocked
    ???
<frozen importlib._bootstrap>:664: in _load_unlocked
    ???
<frozen importlib._bootstrap>:634: in _load_backward_compatible
    ???
.tox/py3/lib/python3.5/site-packages/_pytest/assertion/rewrite.py:213: in load_module
    py.builtin.exec_(co, mod.__dict__)
tests/api/conftest.py:3: in <module>
    from botw.api.authorize_net_api import AuthorizeNetAPI
.tox/py3/lib/python3.5/site-packages/botw/api/authorize_net_api.py:4: in <module>
    from authorizenet import apicontrollers
.tox/py3/lib/python3.5/site-packages/authorizenet/apicontrollers.py:9: in <module>
    from authorizenet import apicontrollersbase
.tox/py3/lib/python3.5/site-packages/authorizenet/apicontrollersbase.py:11: in <module>
    from pip._vendor import requests
.tox/py3/lib/python3.5/site-packages/pip/__init__.py:45: in <module>
    from pip.vcs import git, mercurial, subversion, bazaar  # noqa
.tox/py3/lib/python3.5/site-packages/pip/vcs/mercurial.py:9: in <module>
    from pip.download import path_to_url
.tox/py3/lib/python3.5/site-packages/pip/download.py:40: in <module>
    from pip._vendor import requests, six
.tox/py3/lib/python3.5/site-packages/pip/_vendor/requests/__init__.py:98: in <module>
    from . import packages
.tox/py3/lib/python3.5/site-packages/pip/_vendor/requests/packages.py:12: in <module>
    sys.modules['pip._vendor.requests.packages.' + mod] = sys.modules["pip._vendor." + mod]
E   KeyError: 'pip._vendor.urllib3.contrib'

During handling of the above exception, another exception occurred:
.tox/py3/lib/python3.5/site-packages/py/_path/common.py:377: in visit
    for x in Visitor(fil, rec, ignore, bf, sort).gen(self):
.tox/py3/lib/python3.5/site-packages/py/_path/common.py:418: in gen
    dirs = self.optsort([p for p in entries
.tox/py3/lib/python3.5/site-packages/py/_path/common.py:419: in <listcomp>
    if p.check(dir=1) and (rec is None or rec(p))])
.tox/py3/lib/python3.5/site-packages/_pytest/main.py:411: in _recurse
    ihook = self.gethookproxy(path)
.tox/py3/lib/python3.5/site-packages/_pytest/main.py:315: in gethookproxy
    my_conftestmodules = pm._getconftestmodules(fspath)
.tox/py3/lib/python3.5/site-packages/_pytest/config.py:343: in _getconftestmodules
    mod = self._importconftest(conftestpath)
.tox/py3/lib/python3.5/site-packages/_pytest/config.py:368: in _importconftest
    raise ConftestImportFailure(conftestpath, sys.exc_info())
E   _pytest.config.ConftestImportFailure: KeyError('pip._vendor.urllib3.contrib',)
E     File "<frozen importlib._bootstrap>", line 969, in _find_and_load
E     File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
E     File "<frozen importlib._bootstrap>", line 664, in _load_unlocked
E     File "<frozen importlib._bootstrap>", line 634, in _load_backward_compatible
E     File "<redacted>/.tox/py3/lib/python3.5/site-packages/_pytest/assertion/rewrite.py", line 213, in load_module
E       py.builtin.exec_(co, mod.__dict__)
E     File "<redacted>/tests/api/conftest.py", line 3, in <module>
E       from botw.api.authorize_net_api import AuthorizeNetAPI
E     File "<redacted>/.tox/py3/lib/python3.5/site-packages/botw/api/authorize_net_api.py", line 4, in <module>
E       from authorizenet import apicontrollers
E     File "<redacted>/.tox/py3/lib/python3.5/site-packages/authorizenet/apicontrollers.py", line 9, in <module>
E       from authorizenet import apicontrollersbase
E     File "<redacted>/.tox/py3/lib/python3.5/site-packages/authorizenet/apicontrollersbase.py", line 11, in <module>
E       from pip._vendor import requests
E     File "<redacted>/.tox/py3/lib/python3.5/site-packages/pip/__init__.py", line 45, in <module>
E       from pip.vcs import git, mercurial, subversion, bazaar  # noqa
E     File "<redacted>/.tox/py3/lib/python3.5/site-packages/pip/vcs/mercurial.py", line 9, in <module>
E       from pip.download import path_to_url
E     File "<redacted>/.tox/py3/lib/python3.5/site-packages/pip/download.py", line 40, in <module>
E       from pip._vendor import requests, six
E     File "<redacted>/.tox/py3/lib/python3.5/site-packages/pip/_vendor/requests/__init__.py", line 98, in <module>
E       from . import packages
E     File "<redacted>/.tox/py3/lib/python3.5/site-packages/pip/_vendor/requests/packages.py", line 12, in <module>
E       sys.modules['pip._vendor.requests.packages.' + mod] = sys.modules["pip._vendor." + mod]

I was hoping you could advise and help.

Thank you.

IncompleteElementContentError - Bank Refund

Greetings!
I get this error when I attempt bank eCheck refund. Same code works for CC refunds. Need help to solve the problem. Code follows. Thanks.

def refundTransaction(refTransId, tag, amount):
ret = 0
#first instantiate a CustomerProfile Object using policy id
print("Refunding Txn id: %s" % refTransId)
try:
obj = ChargeTransaction.objects.get(transaction_id=refTransId)
except:
print ("Failed to get ChargeTransaction for charge id: %s" % refTransId)
return ret

            merchantAuth = apicontractsv1.merchantAuthenticationType()
            merchantAuth.name = security_tokens['LOGIN_ID']
            merchantAuth.transactionKey = security_tokens["TRANSACTION_KEY"]

            payment = apicontractsv1.paymentType()

            if obj.payment_method=="CC":
                            creditCard = apicontractsv1.creditCardType()
                            creditCard.cardNumber = obj.last_four
                            creditCard.expirationDate = "XXXX"
                            payment.creditCard = creditCard
            else:
                            bankAc = apicontractsv1.bankAccountType()
                            bankAc.accountNumber = "XXXX" + obj.last_four
                            payment.bankAccount = bankAc

            transactionrequest = apicontractsv1.transactionRequestType()
            transactionrequest.transactionType = "refundTransaction"
            transactionrequest.amount = Decimal (amount)
            #set refTransId to transId of a settled transaction
            transactionrequest.refTransId = refTransId
            transactionrequest.payment = payment


            createtransactionrequest = apicontractsv1.createTransactionRequest()
            createtransactionrequest.merchantAuthentication = merchantAuth
            createtransactionrequest.refId = tag
            createtransactionrequest.transactionRequest = transactionrequest
            createtransactioncontroller = createTransactionController(createtransactionrequest)
            if SANDBOX:
                            createtransactioncontroller.setenvironment(constants.SANDBOX)
            else:
                            createtransactioncontroller.setenvironment(constants.PRODUCTION)

            createtransactioncontroller.execute()

            response = createtransactioncontroller.getresponse()

            if response is not None:
                            if response.messages.resultCode == "Ok":
                                            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 ('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);
                            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

getHostedPaymentPageController response is always None

The code below is copied almost verbatim from the python example.

For some reason paymentPageResponse below always returns None. The only way I can get it to at least a failure is by switching from constants.SANDBOX to constants.PRODUCTION.

What is the meaning of None? The API key and transaction key I provide are for a sandbox account I created earlier today. Do I have to enable anything in the merchant interface for this to work?

from authorizenet import apicontractsv1
from authorizenet.apicontrollers import *
from authorizenet.constants import constants

def test():
            merchantAuth = apicontractsv1.merchantAuthenticationType()

            merchantAuth.name = <API_LOGIN_ID>
            merchantAuth.transactionKey = <TRANSACTION_KEY>

            setting1 = apicontractsv1.settingType()
            setting1.settingName = apicontractsv1.settingNameEnum.hostedPaymentButtonOptions
            setting1.settingValue = "{\"text\": \"Pay\"}"

            setting2 = apicontractsv1.settingType()
            setting2.settingName = apicontractsv1.settingNameEnum.hostedPaymentOrderOptions
            setting2.settingValue = "{\"show\": false}"

            settings = apicontractsv1.ArrayOfSetting()
            settings.setting.append(setting1)
            settings.setting.append(setting2)

            transactionrequest = apicontractsv1.transactionRequestType()
            transactionrequest.transactionType = "authCaptureTransaction"
            transactionrequest.amount = Decimal ('100.00')

            paymentPageRequest = apicontractsv1.getHostedPaymentPageRequest()
            paymentPageRequest.merchantAuthentication = merchantAuth
            paymentPageRequest.transactionRequest = transactionrequest
            paymentPageRequest.hostedPaymentSettings = settings

            paymentPageController = getHostedPaymentPageController(paymentPageRequest)
            paymentPageController.setenvironment(constants.SANDBOX)
            paymentPageController.execute()
            paymentPageResponse = paymentPageController.getresponse()

test()

Edit: And also is there a way to enable HTTP level logging. It's one black box atm

Advice on unpacking of lineItems object

I am successfully using the Python SDK and the get-transaction-details.py sample script to retrieve most of the the details of a credit card transaction. However, I can't figure out how to unpack the transactionDetailsResponse.transaction.lineItems object. Can someone post an example of how this is done?

createTransactionRequest with Tax

I am trying to add tax via the SDK in the "charge-credit-card.py" file, but it seems that the sdk does not support this function. Is there a fix for this?

` # 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

transactionrequest.tax.amount = "1.99"

transactionrequest.tax.name = "test tax"

transactionrequest.tax.description = "this is a tax for level 2"`

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.