def get_unsettled_transaction_list():
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = constants.apiLoginId
    merchantAuth.transactionKey = constants.transactionKey

    unsettledTransactionListRequest = apicontractsv1.getUnsettledTransactionListRequest()
    unsettledTransactionListRequest.merchantAuthentication = merchantAuth

    unsettledTransactionListController = getUnsettledTransactionListController(unsettledTransactionListRequest)

    unsettledTransactionListController.execute()

    unsettledTransactionListResponse = unsettledTransactionListController.getresponse()

    if unsettledTransactionListResponse is not None:
        if unsettledTransactionListResponse.messages.resultCode == apicontractsv1.messageTypeEnum.Ok:
            print('Successfully got unsettled transaction list!')

            for transaction in unsettledTransactionListResponse.transactions.transaction:
                print('Transaction Id : %s' % transaction.transId)
                print('Transaction Status : %s' % transaction.transactionStatus)
                print('Amount Type : %s' % transaction.accountType)
                print('Settle Amount : %s' % transaction.settleAmount)

            if unsettledTransactionListResponse.messages:
                print('Message Code : %s' % unsettledTransactionListResponse.messages.message[0]['code'].text)
                print('Message Text : %s' % unsettledTransactionListResponse.messages.message[0]['text'].text)
        else:
            if unsettledTransactionListResponse.messages:
                print('Failed to get unsettled transaction list.\nCode:%s \nText:%s' % (unsettledTransactionListResponse.messages.message[0]['code'].text,unsettledTransactionListResponse.messages.message[0]['text'].text))

    return unsettledTransactionListResponse
def update_split_tender_group():
	merchantAuth = apicontractsv1.merchantAuthenticationType()
	merchantAuth.name = constants.apiLoginId
	merchantAuth.transactionKey = constants.transactionKey


	updateSplitTenderGroup = apicontractsv1.updateSplitTenderGroupRequest()
	updateSplitTenderGroup.merchantAuthentication = merchantAuth
	updateSplitTenderGroup.splitTenderId = "115901"
	enum = apicontractsv1.splitTenderStatusEnum
	updateSplitTenderGroup.splitTenderStatus = enum.voided


	updateSplitTenderController = updateSplitTenderGroupController(updateSplitTenderGroup)
	updateSplitTenderController.execute()

	response = updateSplitTenderController.getresponse()


	if (response.messages.resultCode=="Ok"):
	    print response.messages.message[0]['text'].text
	else:
	    print "response code: %s" % response.messages.resultCode
	    print response.messages.message[0]['text'].text

	return response
def get_transaction_details(transId):
	merchantAuth = apicontractsv1.merchantAuthenticationType()
	merchantAuth.name = constants.apiLoginId
	merchantAuth.transactionKey = constants.transactionKey

	transactionDetailsRequest = apicontractsv1.getTransactionDetailsRequest()
	transactionDetailsRequest.merchantAuthentication = merchantAuth
	transactionDetailsRequest.transId = "40000276420"

	transactionDetailsController = getTransactionDetailsController(transactionDetailsRequest)

	transactionDetailsController.execute()

	transactionDetailsResponse = transactionDetailsController.getresponse()

	if transactionDetailsResponse is not None:
		if transactionDetailsResponse.messages.resultCode == apicontractsv1.messageTypeEnum.Ok:
			print('Successfully got transaction details!')

			print('Transaction Id : %s' % transactionDetailsResponse.transaction.transId)
			print('Transaction Type : %s' % transactionDetailsResponse.transaction.transactionType)
			print('Transaction Status : %s' % transactionDetailsResponse.transaction.transactionStatus)
			print('Auth Amount : %s' % transactionDetailsResponse.transaction.authAmount)
			print('Settle Amount : %s' % transactionDetailsResponse.transaction.settleAmount)
			if hasattr(transactionDetailsResponse.transaction, 'tax') == True:
				print('Tax : %s' % transactionDetailsResponse.transaction.tax.amount)

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

	return transactionDetailsResponse
Example #4
0
    def __init__(self, apiRequest):
        self._httpResponse = None
        self._request = None
        self._response = None
               
        if None == apiRequest:
            raise ValueError('Input request cannot be null')
         
        self._request = apiRequest
        __merchantauthentication = apicontractsv1.merchantAuthenticationType()
        APIOperationBase.__environment = constants.SANDBOX
        
        APIOperationBase.setmerchantauthentication(__merchantauthentication)

        if ( False == APIOperationBase.__classinitialized()):
            loggingfilename = utility.helper.getproperty(constants.propertiesloggingfilename)
            logginglevel = utility.helper.getproperty(constants.propertiesexecutionlogginglevel)
            
            if (None == loggingfilename):
                loggingfilename = constants.defaultLogFileName
            if (None == logginglevel):
                logginglevel = constants.defaultLoggingLevel
                
            logging.basicConfig(filename=loggingfilename, level=logginglevel, format=constants.defaultlogformat)
            __initialized = True

        self.validate()
            
        return
def create_customer_profile_from_transaction(transactionId):
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = constants.apiLoginId
    merchantAuth.transactionKey = constants.transactionKey

    profile = apicontractsv1.customerProfileBaseType()
    profile.merchantCustomerId = "12332"
    profile.description = "This is a sample profile"
    profile.email = "*****@*****.**"

    createCustomerProfileFromTransaction = apicontractsv1.createCustomerProfileFromTransactionRequest()
    createCustomerProfileFromTransaction.merchantAuthentication = merchantAuth
    createCustomerProfileFromTransaction.transId = transactionId
    #You can either specify the customer information in form of customerProfileBaseType object
    createCustomerProfileFromTransaction.customer = profile
    #  OR
    # You can just provide the customer Profile ID
    # createCustomerProfileFromTransaction.customerProfileId = "123343"

    controller = createCustomerProfileFromTransactionController(createCustomerProfileFromTransaction)
    controller.execute()

    response = controller.getresponse()

    if (response.messages.resultCode=="Ok"):
        print("Successfully created a customer profile with id: %s from transaction id: %s" % (response.customerProfileId, createCustomerProfileFromTransaction.transId))
    else:
        print("Failed to create customer payment profile from transaction %s" % response.messages.message[0]['text'].text)

    return response
def get_subscription_status(subscriptionId):
    # Setting the mercahnt details
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = constants.apiLoginId
    merchantAuth.transactionKey = constants.transactionKey
    # Seeting the request
    request = apicontractsv1.ARBGetSubscriptionStatusRequest()
    request.merchantAuthentication = merchantAuth
    request.refId = "Sample"
    request.subscriptionId = subscriptionId
    # Executing the controller
    controller = ARBGetSubscriptionStatusController(request)
    controller.execute()
    # Getting the response
    response = controller.getresponse()

    if (response.messages.resultCode=="Ok"):
        print ("SUCCESS:")
        print ("Message Code : %s" % response.messages.message[0]['code'].text)
        print ("Message text : %s" % response.messages.message[0]['text'].text)
        print ("Subscription Status : %s" % response.status)
    else:
        print ("ERROR:")
        print ("Message Code : %s" % response.messages.message[0]['code'].text)
        print ("Message text : %s" % response.messages.message[0]['text'].text)

    return response
def decrypt_visa_checkout_data():
	merchantAuth = apicontractsv1.merchantAuthenticationType()
	merchantAuth.name = constants.apiLoginId
	merchantAuth.transactionKey = constants.transactionKey
	# Populate the payment data
	opaqueData = apicontractsv1.opaqueDataType()
	opaqueData.dataDescriptor = "COMMON.VCO.ONLINE.PAYMENT"
	opaqueData.dataValue = "q1rx4GVCh0dqjZGgSBI8RB/VlI/1lwzTxDnrW/L1D4f/lfKZeQPo34eTB59akZXdRlRBW/dHVWgc2eVebvWpkAKmDrc+7Zr7lGXvHbLG78e0ZgfEReQNS4es6K7DxsDXp0UZSdnxw6g3stQhW2TqR6fcwLj7gWpZvAL3GAftP6QNCJfv6ohFPN9L/t84A1h8M0jClNq7DtDsUhuy35dEBdP8/MKOb7hSRkMqb/8qh7XUR+84FOoAKHAcG6KoRRdogTrYmPBuyDoaWUmDFgRFSSXN7Wj7evVsliis5H9y+tub/f5mAiZtl+fyFC7uIEZOLUcSWHfeX1lWxyWTEYxRq5TwnzewPNn0VbmqPh+/uaHooDQT891nUeZfm79Bunj+NfWtr06YIxW2LW3P6IWuyAhquAseL1hOv7vHT5QGogPuUJlv/+jY52tSsXrVccWu4rTjHShwvFmvxl82VZx55zcIrYFROiFVw+3sN88BL4hNnh3RCYrotWDiAwdJmJLdYhAzO2xiWLRRBgiGn27hi+G381EwLUy/6K1rx6iAN+x2bWWHgyKddSYLo0U7g+UfHBrvNSHZQcQM5LzjiZP86bx2SqQoLrqgSZQcChSy/T6C4vIvlFyomx9+7Soht6J61KoRvhM1yzlvwwjyF0ouamCRUBzrKR6j366TbdrAhAVLfuVc2XbE57Wc9bF0w4+K5I4kfA47XfRHlkA+6S4dpgp+fV+bC/jzrqIQwrs+wehzEaiR43lBQpyfPElX2SGfGk0WH4c4SbIhUY0KtyLmfgCbcAHyCAXN1ZNQvNb8Axw2j/C2B77cE81Dsi9DyGdGclM2u14UqxkXEINS2FoYQI4mZj04TR4oDG6axkp52d+ndagOS0kIH8SM71fPPiXSGw/zbm+JRdrTJLuYSvf1LbrFL2WPnHbuQuZIZDab0guanrVNjsEokJjffUPbvf+uCxytCZ148T5GWD2Daou/MK63mjl05XeySENdl3opaUj0joYFg+MkzaVYpvgiIxGEGuBdy+oA06Y/uxrgt2Xgcwwn2eo3YDUr4kqXWOI7SpqDDV1QWfd/anacjR9hCoqP2+sN2HbzbPi/jqR02etk/eSil2NiWORph2s8KneoQiMMoKfoUvi3SkzzaOxXYhD+UFdN69cxox7Y8enw++faUnDcxydr/Go5LmxJKrLH+Seez6m412ygABHzki+ooJiyYPRL+TuXzQuVDWwPh7qjrh9cU3ljkaWW2HZp+AFInyh65JHUZpSkjeXM+Sfz3VASBLTB8zq/Co737KT9t38lZEn/ffLLvD7NGW1dB3K8h4xhX7FhMLwFCt7WCvtpAXJ4J2FF55x4RDQdwdsPjXR9vHPmRsjU/eNAT8tRrJh8XTSFubyIYNd+67j+Y0u+PvVUCPK2mWTfDgU1ZNsGrI2asrVaStsER64lkfgSWD0bN4hbJaJVPAPaOxYkpzhfU34B2e3IUKdBccgqrXpMXe1r3OETmfLFnk2sIPZwBcDLVtAH5bePsu3wK3MtvmEWjGR4QQGI5oPlz9GnUaexOPAkRVJeOJIazGOgBeFDGDm7urxnKKYZzNKNnjXlij/ccWR9NYDB4TSZ1yxBZpXkLQ9TbOvrxnsy3ZrFhlJT4Nn/0YOPvfYt+sMcUXcB+09oRpFZdpVtPtkxMRiNjetZPjoXKq/2Jxj7yCAfYzRrrlbqbKXF8b06PcmFRb2dsZzbN+maEYhwWgRRa9yy7Ha2TGrH00jZ8tiowcBmnW6/UsuGn0ZMEgA02iaeIqQKf+Kqwa6EMN8HqED4IK38XKOr5RYthTaOcL9FA629MIAArVu5/LPj4b5abM3pTXk9gItVEuf5KfWceaSG1CFY1dD8/IRqIwWQGobQRpyTsYXiirkOIJnnlC8ph6eMIlCMu3wDfB4a2KrXDQuc06qRXi2KNHl8opawi2lpR/rjBfEyX5if47wNlEJkj+D/bCutN9APbSiFGs03X8cTb6CKVghQfx9PD/T+XZTA3yzBwHHZNiNJK2mhheEubgNYcnw1t9Lf9cx174OEayQrU+AORjPnEPGWYx+bYtK6XuQ9bt9gAo4HzaGRF1WB6Dr0p8gfqrxHe9HhjrbeHILmVtIJnv2jDds20pR/VRYs1IFJNWyDjgCe2uWBM+oC22YdSYyn3f2swouqqXz6yl9UTImzCM8KAzLpPGZVFlafJka8soKSxr9KBvAsBnfb34RPB7OMgSo+uqgvB3YGvOu5LpLoaVNxQ1d6GLeeQ9u9olb12Y2kPzGni99f04lI77qoleqzCcCFZC9Q"
	opaqueData.dataKey = "KCSJeIab7wwH7mFcPM/YL+V9xBCDe4CmSjJ0MPHEodpWz4rmz78U8bR4Qqs1ipLBqH9mrfvLF4pytIcLOjKUtXvAII/xCze84INFMdtsVBgtEp5bZ4leehRQhNM+3/NH"
	# Initialize decrypt request
	request = apicontractsv1.decryptPaymentDataRequest()
	request.merchantAuthentication = merchantAuth
	request.opaqueData = opaqueData
	request.callId = "1238408836021304101"
	# Execute API request
	controller = decryptPaymentDataController(request)
	controller.execute()
	response = controller.getresponse()

	if (response.messages.resultCode=="Ok"):
		print "SUCCESS"
		print "Message Code : %s" % response.messages.message[0].code
		print "Message text : %s" % response.messages.message[0].text
		print "Card number : %s" % response.cardInfo.cardNumber
		print "Amount : %s" % response.paymentDetails.amount
	else:
		print "ERROR"
		print "Message Code : %s" % response.messages.message[0].code
		print "Message text : %s" % response.messages.message[0].text

	return response
def delete_customer_shipping_address(customerProfileId, customerProfileShippingId):

	# Give merchant details
	merchantAuth = apicontractsv1.merchantAuthenticationType()
	merchantAuth.name = constants.apiLoginId
	merchantAuth.transactionKey = constants.transactionKey

	# create delete request
	deleteShippingAddress = apicontractsv1.deleteCustomerShippingAddressRequest()
	deleteShippingAddress.merchantAuthentication = merchantAuth
	deleteShippingAddress.customerProfileId = customerProfileId
	deleteShippingAddress.customerAddressId = customerProfileShippingId

	# Make the API call
	deleteShippingAddressController = deleteCustomerShippingAddressController(deleteShippingAddress)
	deleteShippingAddressController.execute()
	response = deleteShippingAddressController.getresponse()

	if response.messages.resultCode == "Ok":
	    print("SUCCESS")
	    print("Message code : %s " % response.messages.message[0]['code'].text)
	    print("Message text : %s " % response.messages.message[0]['text'].text)
	else:
	    print("ERROR")
	    print("Message code : %s " % response.messages.message[0]['code'].text)
	    print("Message text : %s " % response.messages.message[0]['text'].text)

	return response
def get_customer_payment_profile_list():
    """Retrieve a list of customer payment profiles matching the specific search parameters"""

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

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

    # Set the paging (this particular API call will only return up to 10 results at a time)
    paging = apicontractsv1.Paging()
    paging.limit = 10
    paging.offset = 1

    # Set the sorting
    sorting = apicontractsv1.CustomerPaymentProfileSorting()
    sorting.orderBy = apicontractsv1.CustomerPaymentProfileOrderFieldEnum.id
    sorting.orderDescending = "false"

    # Set search parameters
    search = apicontractsv1.CustomerPaymentProfileSearchTypeEnum.cardsExpiringInMonth
    month = "2020-12"

    # Creating the request with the required parameters
    request = apicontractsv1.getCustomerPaymentProfileListRequest()
    request.merchantAuthentication = merchant_auth
    request.refId = ref_id
    request.paging = paging
    request.sorting = sorting
    request.searchType = search
    request.month = month

    controller = getCustomerPaymentProfileListController(request)
    controller.execute()

    response = controller.getresponse()

    if response is not None:
        if response.messages.resultCode == apicontractsv1.messageTypeEnum.Ok:
            print ("SUCCESS")
            print ("Total Num in Result Set: %s" % response.totalNumInResultSet)
            for profile in response.paymentProfiles.paymentProfile:
                print("Profile ID: %s" % profile.customerProfileId)
                print("Payment Profile ID: %s" % profile.customerPaymentProfileId)
                try:
                    print("Card: %s" % profile.payment.creditCard.cardNumber)
                except AttributeError:
                    print("Bank account: %s" % profile.payment.bankAccount.accountNumber)
                print()

        else:
            print ("ERROR")
            if response.messages is not None:
                print ("Result code: %s" % response.messages.resultCode)
                print ("Message code: %s" % response.messages.message[0]['code'].text)
                print ("Message text: %s" % response.messages.message[0]['text'].text)
    return response
def capture_previously_authorized_amount():
	merchantAuth = apicontractsv1.merchantAuthenticationType()
	merchantAuth.name = constants.apiLoginId
	merchantAuth.transactionKey = constants.transactionKey


	transactionrequest = apicontractsv1.transactionRequestType()
	transactionrequest.transactionType = "priorAuthCaptureTransaction"
	transactionrequest.amount = Decimal ('2.55')
	transactionrequest.refTransId = "2245440574"



	createtransactionrequest = apicontractsv1.createTransactionRequest()
	createtransactionrequest.merchantAuthentication = merchantAuth
	createtransactionrequest.refId = "MerchantID-0001"

	createtransactionrequest.transactionRequest = transactionrequest
	createtransactioncontroller = createTransactionController(createtransactionrequest)
	createtransactioncontroller.execute()

	response = createtransactioncontroller.getresponse()

	if (response.messages.resultCode=="Ok"):
	    print "Transaction ID : %s" % response.transactionResponse.transId
	    print response.transactionResponse.messages.message[0].description
	else:
	    print "response code: %s" % response.messages.resultCode

	return response
def get_customer_payment_profile(customerProfileId, customerPaymentProfileId):

	merchantAuth = apicontractsv1.merchantAuthenticationType()
	merchantAuth.name = constants.apiLoginId
	merchantAuth.transactionKey = constants.transactionKey

	getCustomerPaymentProfile = apicontractsv1.getCustomerPaymentProfileRequest()
	getCustomerPaymentProfile.merchantAuthentication = merchantAuth
	getCustomerPaymentProfile.customerProfileId = customerProfileId
	getCustomerPaymentProfile.customerPaymentProfileId = customerPaymentProfileId

	controller = getCustomerPaymentProfileController(getCustomerPaymentProfile)
	controller.execute()

	response = controller.getresponse()

	if (response.messages.resultCode=="Ok"):
		print("Successfully retrieved a payment profile with profile id %s and customer id %s" % (getCustomerPaymentProfile.customerProfileId, getCustomerPaymentProfile.customerProfileId))
		if hasattr(response, 'paymentProfile') == True:
			if hasattr(response.paymentProfile, 'subscriptionIds') == True:
				if hasattr(response.paymentProfile.subscriptionIds, 'subscriptionId') == True:
					print("list of subscriptionid:")
					for subscriptionid in response.paymentProfile.subscriptionIds.subscriptionId:
						print(subscriptionid)
	else:
		print("response code: %s" % response.messages.resultCode)
		print("Failed to get payment profile information with id %s" % getCustomerPaymentProfile.customerPaymentProfileId)

	return response
def get_transaction_list():
	merchantAuth = apicontractsv1.merchantAuthenticationType()
	merchantAuth.name = constants.apiLoginId
	merchantAuth.transactionKey = constants.transactionKey

	transactionListRequest = apicontractsv1.getTransactionListRequest()
	transactionListRequest.merchantAuthentication = merchantAuth
	transactionListRequest.batchId = "4551107"

	transactionListController = getTransactionListController(transactionListRequest)

	transactionListController.execute()

	transactionListResponse = transactionListController.getresponse()

	if transactionListResponse is not None:
		if transactionListResponse.messages.resultCode == apicontractsv1.messageTypeEnum.Ok:
			print('Successfully got transaction list!')

			for transaction in transactionListResponse.transactions.transaction:
				print('Transaction Id : %s' % transaction.transId)
				print('Transaction Status : %s' % transaction.transactionStatus)
				print('Amount Type : %s' % transaction.accountType)
				print('Settle Amount : %s' % transaction.settleAmount)

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

	return transactionListResponse
def charge_customer_profile(customerProfileId, paymentProfileId, amount):
	merchantAuth = apicontractsv1.merchantAuthenticationType()
	merchantAuth.name = constants.apiLoginId
	merchantAuth.transactionKey = constants.transactionKey

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

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


	createtransactionrequest = apicontractsv1.createTransactionRequest()
	createtransactionrequest.merchantAuthentication = merchantAuth
	createtransactionrequest.refId = "MerchantID-0001"

	createtransactionrequest.transactionRequest = transactionrequest
	createtransactioncontroller = createTransactionController(createtransactionrequest)
	createtransactioncontroller.execute()

	response = createtransactioncontroller.getresponse()

	if (response.messages.resultCode=="Ok"):
		print "Transaction ID : %s" % response.transactionResponse.transId
	else:
		print "response code: %s" % response.messages.resultCode

	return response
def cancel_subscription(subscriptionId):
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = constants.apiLoginId
    merchantAuth.transactionKey = constants.transactionKey

    request = apicontractsv1.ARBCancelSubscriptionRequest()
    request.merchantAuthentication = merchantAuth
    request.refId = "Sample"
    request.subscriptionId = subscriptionId

    controller = ARBCancelSubscriptionController(request)
    controller.execute()

    response = controller.getresponse()

    if (response.messages.resultCode=="Ok"):
        print ("SUCCESS")
        print ("Message Code : %s" % response.messages.message[0]['code'].text)
        print ("Message text : %s" % response.messages.message[0]['text'].text)
    else:
        print ("ERROR")
        print ("Message Code : %s" % response.messages.message[0]['code'].text)
        print ("Message text : %s" % response.messages.message[0]['text'].text)

    return response
def get_details(refTransId):
	merchantAuth = apicontractsv1.merchantAuthenticationType()
	merchantAuth.name = constants.apiLoginId
	merchantAuth.transactionKey = constants.transactionKey

	transactionrequest = apicontractsv1.transactionRequestType()
	transactionrequest.transactionType = apicontractsv1.transactionTypeEnum.getDetailsTransaction
	transactionrequest.refTransId = refTransId

	request = apicontractsv1.createTransactionRequest()
	request.merchantAuthentication = merchantAuth
	request.refId = "Sample"
	request.transactionRequest = transactionrequest

	controller = createTransactionController(request)
	controller.execute()

	response = controller.getresponse()

	if (response.messages.resultCode=="Ok"):
	    print "SUCCESS"
	    print "Message Code : %s" % response.messages.message[0]['code'].text
	    print "Message text : %s" % response.messages.message[0]['text'].text
	    if (response.transactionResponse.responseCode == "1" ):
	        print "Payer Id : %s " % response.transactionResponse.secureAcceptance.PayerID
	        print "Transaction ID : %s " % response.transactionResponse.transId
	else:
	    print "ERROR"
	    print "Message Code : %s" % response.messages.message[0]['code'].text
	    print "Message text : %s" % response.messages.message[0]['text'].text

	return response
def update_customer_profile(customerProfileId):
	merchantAuth = apicontractsv1.merchantAuthenticationType()
	merchantAuth.name = constants.apiLoginId
	merchantAuth.transactionKey = constants.transactionKey

	updateCustomerProfile = apicontractsv1.updateCustomerProfileRequest()
	updateCustomerProfile.merchantAuthentication = merchantAuth
	updateCustomerProfile.profile = apicontractsv1.customerProfileExType()

	updateCustomerProfile.profile.customerProfileId = customerProfileId
	updateCustomerProfile.profile.merchantCustomerId = "mycustomer"
	updateCustomerProfile.profile.description = "john doe"
	updateCustomerProfile.profile.email = "*****@*****.**"

	controller = updateCustomerProfileController(updateCustomerProfile)
	controller.execute()

	response = controller.getresponse()

	if (response.messages.resultCode=="Ok"):
		print "Successfully updated customer with customer profile id %s" % updateCustomerProfile.profile.customerProfileId
	else:
		print response.messages.message[0]['text'].text
		print "Failed to update customer profile with customer profile id %s" % updateCustomerProfile.profile.customerProfileId

	return response
def void_transaction(refTransId):
	merchantAuth = apicontractsv1.merchantAuthenticationType()
	merchantAuth.name = constants.apiLoginId
	merchantAuth.transactionKey = constants.transactionKey


	transactionrequest = apicontractsv1.transactionRequestType()
	transactionrequest.transactionType = "voidTransaction"
	#set refTransId to transId of an unsettled transaction
	transactionrequest.refTransId = refTransId

	createtransactionrequest = apicontractsv1.createTransactionRequest()
	createtransactionrequest.merchantAuthentication = merchantAuth
	createtransactionrequest.refId = "MerchantID-0001"

	createtransactionrequest.transactionRequest = transactionrequest
	createtransactioncontroller = createTransactionController(createtransactionrequest)
	createtransactioncontroller.execute()

	response = createtransactioncontroller.getresponse()

	if (response.messages.resultCode=="Ok"):
	    print "Transaction ID : %s" % response.transactionResponse.transId
	    print response.transactionResponse.messages.message[0].description
	else:
	    print "response code: %s" % response.messages.resultCode
	    print response.transactionResponse.errors.error[0].errorText

	return response
def get_merchant_details():
	merchantAuth = apicontractsv1.merchantAuthenticationType()
	merchantAuth.name = constants.apiLoginId
	merchantAuth.transactionKey = constants.transactionKey

	getMerchantDetailsRequest = apicontractsv1.getMerchantDetailsRequest()
	getMerchantDetailsRequest.merchantAuthentication = merchantAuth

	controller = getMerchantDetailsController(getMerchantDetailsRequest)
	controller.execute()

	response = controller.getresponse()

	if response is not None:
		if response.messages.resultCode == "Ok":
			print("Merchant Name: ", response.merchantName)
			print("Gateway ID: ", response.gatewayId)
			print("Processors: "),
			for processor in response.processors.processor:
				print(processor.name, "; "),
		else:
			print ("Failed Transaction.")
	else:
		print ("Null Response.")

	return response
def debit_bank_account():

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

	merchantAuth = apicontractsv1.merchantAuthenticationType()
	merchantAuth.name = constants.apiLoginId
	merchantAuth.transactionKey = constants.transactionKey


	payment = apicontractsv1.paymentType()

	bankAccountType = apicontractsv1.bankAccountType()
	accountType = apicontractsv1.bankAccountTypeEnum
	bankAccountType.accountType = accountType.checking
	bankAccountType.routingNumber = "125000024"
	bankAccountType.accountNumber = "12345678"
	bankAccountType.nameOnAccount = "John Doe"

	transactionrequest = apicontractsv1.transactionRequestType()
	transactionrequest.transactionType = "authCaptureTransaction"
	transactionrequest.amount = Decimal (amount)
	transactionrequest.payment = payment
	transactionrequest.payment.bankAccount = bankAccountType


	createtransactionrequest = apicontractsv1.createTransactionRequest()
	createtransactionrequest.merchantAuthentication = merchantAuth
	createtransactionrequest.refId = "MerchantID-0001"

	createtransactionrequest.transactionRequest = transactionrequest
	createtransactioncontroller = createTransactionController(createtransactionrequest)
	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
def get_list_of_subscriptions():
    """get list of subscriptions"""
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = constants.apiLoginId
    merchantAuth.transactionKey = constants.transactionKey

    # set sorting parameters
    sorting = apicontractsv1.ARBGetSubscriptionListSorting()
    sorting.orderBy = apicontractsv1.ARBGetSubscriptionListOrderFieldEnum.id
    sorting.orderDescending = True

    # set paging and offset parameters
    paging = apicontractsv1.Paging()
    # Paging limit can be up to 1000 for this request
    paging.limit = 20
    paging.offset = 1

    request = apicontractsv1.ARBGetSubscriptionListRequest()
    request.merchantAuthentication = merchantAuth
    request.refId = "Sample"
    request.searchType = apicontractsv1.ARBGetSubscriptionListSearchTypeEnum.subscriptionInactive
    request.sorting = sorting
    request.paging = paging

    controller = ARBGetSubscriptionListController(request)
    controller.execute()

    # Work on the response
    response = controller.getresponse()

    if response is not None:
        if response.messages.resultCode == apicontractsv1.messageTypeEnum.Ok:
            if hasattr(response, 'subscriptionDetails'):
                print('Successfully retrieved subscription list.')
                if response.messages is not None:
                    print('Message Code: %s' % response.messages.message[0]['code'].text)
                    print('Message Text: %s' % response.messages.message[0]['text'].text)
                    print('Total Number In Results: %s' % response.totalNumInResultSet)
                    print()
                for subscription in response.subscriptionDetails.subscriptionDetail:
                    print('Subscription Id: %s' % subscription.id)
                    print('Subscription Name: %s' % subscription.name)
                    print('Subscription Status: %s' % subscription.status)
                    print('Customer Profile Id: %s' % subscription.customerProfileId)
                    print()
            else:
                if response.messages is not None:
                    print('Failed to get subscription list.')
                    print('Code: %s' % (response.messages.message[0]['code'].text))
                    print('Text: %s' % (response.messages.message[0]['text'].text))
        else:
            if response.messages is not None:
                print('Failed to get transaction list.')
                print('Code: %s' % (response.messages.message[0]['code'].text))
                print('Text: %s' % (response.messages.message[0]['text'].text))
    else:
        print('Error. No response received.')

    return response
Example #21
0
 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"
    
 
     
def get_customer_profile_ids():
    """get customer profile IDs"""
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = constants.apiLoginId
    merchantAuth.transactionKey = constants.transactionKey

    CustomerProfileIdsRequest = apicontractsv1.getCustomerProfileIdsRequest()
    CustomerProfileIdsRequest.merchantAuthentication = merchantAuth
    CustomerProfileIdsRequest.refId = "Sample"

    controller = getCustomerProfileIdsController(CustomerProfileIdsRequest)
    controller.execute()

    # Work on the response
    response = controller.getresponse()

    # if (response.messages.resultCode == "Ok"):
    #     print("Successfully retrieved customer ids:")
    #     for identity in response.ids.numericString:
    #         print(identity)
    # else:
    #     print("response code: %s" % response.messages.resultCode)



    if response is not None:
        if response.messages.resultCode == apicontractsv1.messageTypeEnum.Ok:
            if hasattr(response, 'ids'):
                if hasattr(response.ids, 'numericString'):
                    print('Successfully retrieved customer IDs.')
                    if response.messages is not None:
                        print('Message Code: %s' % response.messages.message[0]['code'].text)
                        print('Message Text: %s' % response.messages.message[0]['text'].text)
                        print('Total Number of IDs Returned in Results: %s'
                            % len(response.ids.numericString))
                        print()
                    # There's no paging options in this API request; the full list is returned every call.
                    # If the result set is going to be large, for this sample we'll break it down into smaller
                    # chunks so that we don't put 72,000 lines into a log file
                    print('First 20 results:')
                    for profileId in range(0,19):
                        print(response.ids.numericString[profileId])
            else:
                if response.messages is not None:
                    print('Failed to get list.')
                    print('Code: %s' % (response.messages.message[0]['code'].text))
                    print('Text: %s' % (response.messages.message[0]['text'].text))
        else:
            if response.messages is not None:
                print('Failed to get list.')
                print('Code: %s' % (response.messages.message[0]['code'].text))
                print('Text: %s' % (response.messages.message[0]['text'].text))
    else:
        print('Error. No response received.')

    return response
def capture_funds_authorized_through_another_channel():

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

    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = constants.apiLoginId
    merchantAuth.transactionKey = constants.transactionKey

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

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

    transactionrequest = apicontractsv1.transactionRequestType()
    transactionrequest.transactionType = "captureOnlyTransaction"
    transactionrequest.amount = Decimal (amount)
    transactionrequest.payment = payment
    transactionrequest.authCode = "ROHNFQ"

    createtransactionrequest = apicontractsv1.createTransactionRequest()
    createtransactionrequest.merchantAuthentication = merchantAuth
    createtransactionrequest.refId = "MerchantID-0001"

    createtransactionrequest.transactionRequest = transactionrequest
    createtransactioncontroller = createTransactionController(createtransactionrequest)
    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
def refund_transaction(refTransId):
	merchantAuth = apicontractsv1.merchantAuthenticationType()
	merchantAuth.name = constants.apiLoginId
	merchantAuth.transactionKey = constants.transactionKey

	creditCard = apicontractsv1.creditCardType()
	creditCard.cardNumber = "0015"
	creditCard.expirationDate = "XXXX"

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

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


	createtransactionrequest = apicontractsv1.createTransactionRequest()
	createtransactionrequest.merchantAuthentication = merchantAuth
	createtransactionrequest.refId = "MerchantID-0001"

	createtransactionrequest.transactionRequest = transactionrequest
	createtransactioncontroller = createTransactionController(createtransactionrequest)
	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
Example #25
0
def _getMerchantAuth():
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    if config.IN_PRODUCTION:
        merchantAuth.name = get_setting('authorizenet_api_login_id_production')
        merchantAuth.transactionKey = get_setting(
            'authorizenet_transaction_key_production')
    else:
        merchantAuth.name = get_setting('authorizenet_api_login_id_dev')
        merchantAuth.transactionKey = get_setting(
            'authorizenet_transaction_key_dev')
    return merchantAuth
def charge_tokenized_credit_card():
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = constants.apiLoginId
    merchantAuth.transactionKey = constants.transactionKey

    creditCard = apicontractsv1.creditCardType()
    creditCard.cardNumber = "4111111111111111"
    creditCard.expirationDate = "2020-12"
    # Set the token specific info
    creditCard.isPaymentToken = True
    creditCard.cryptogram = "EjRWeJASNFZ4kBI0VniQEjRWeJA="

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

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

    createtransactionrequest = apicontractsv1.createTransactionRequest()
    createtransactionrequest.merchantAuthentication = merchantAuth
    createtransactionrequest.refId = "MerchantID-0001"
    createtransactionrequest.transactionRequest = transactionrequest

    createtransactioncontroller = createTransactionController(createtransactionrequest)
    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
def create_an_apple_pay_transaction():

	merchantAuth = apicontractsv1.merchantAuthenticationType()
	merchantAuth.name = constants.apiLoginId
	merchantAuth.transactionKey = constants.transactionKey

	opaquedata = apicontractsv1.opaqueDataType()
	opaquedata.dataDescriptor = "COMMON.APPLE.INAPP.PAYMENT"
	opaquedata.dataValue = "eyJkYXRhIjoiQkRQTldTdE1tR2V3UVVXR2c0bzdFXC9qKzFjcTFUNzhxeVU4NGI2N2l0amNZSTh3UFlBT2hzaGpoWlBycWRVcjRYd1BNYmo0emNHTWR5KysxSDJWa1BPWStCT01GMjV1YjE5Y1g0bkN2a1hVVU9UakRsbEIxVGdTcjhKSFp4Z3A5ckNnc1NVZ2JCZ0tmNjBYS3V0WGY2YWpcL284WkliS25yS1E4U2gwb3VMQUtsb1VNbit2UHU0K0E3V0tycXJhdXo5SnZPUXA2dmhJcStIS2pVY1VOQ0lUUHlGaG1PRXRxK0grdzB2UmExQ0U2V2hGQk5uQ0hxenpXS2NrQlwvMG5xTFpSVFliRjBwK3Z5QmlWYVdIZWdoRVJmSHhSdGJ6cGVjelJQUHVGc2ZwSFZzNDhvUExDXC9rXC8xTU5kNDdrelwvcEhEY1JcL0R5NmFVTStsTmZvaWx5XC9RSk4rdFMzbTBIZk90SVNBUHFPbVhlbXZyNnhKQ2pDWmxDdXcwQzltWHpcL29iSHBvZnVJRVM4cjljcUdHc1VBUERwdzdnNjQybTRQendLRitIQnVZVW5lV0RCTlNEMnU2amJBRzMiLCJ2ZXJzaW9uIjoiRUNfdjEiLCJoZWFkZXIiOnsiYXBwbGljYXRpb25EYXRhIjoiOTRlZTA1OTMzNWU1ODdlNTAxY2M0YmY5MDYxM2UwODE0ZjAwYTdiMDhiYzdjNjQ4ZmQ4NjVhMmFmNmEyMmNjMiIsInRyYW5zYWN0aW9uSWQiOiJjMWNhZjVhZTcyZjAwMzlhODJiYWQ5MmI4MjgzNjM3MzRmODViZjJmOWNhZGYxOTNkMWJhZDlkZGNiNjBhNzk1IiwiZXBoZW1lcmFsUHVibGljS2V5IjoiTUlJQlN6Q0NBUU1HQnlxR1NNNDlBZ0V3Z2ZjQ0FRRXdMQVlIS29aSXpqMEJBUUloQVBcL1wvXC9cLzhBQUFBQkFBQUFBQUFBQUFBQUFBQUFcL1wvXC9cL1wvXC9cL1wvXC9cL1wvXC9cL1wvXC9cL01Gc0VJUFwvXC9cL1wvOEFBQUFCQUFBQUFBQUFBQUFBQUFBQVwvXC9cL1wvXC9cL1wvXC9cL1wvXC9cL1wvXC9cLzhCQ0JheGpYWXFqcVQ1N1BydlZWMm1JYThaUjBHc014VHNQWTd6ancrSjlKZ1N3TVZBTVNkTmdpRzV3U1RhbVo0NFJPZEpyZUJuMzZRQkVFRWF4ZlI4dUVzUWtmNHZPYmxZNlJBOG5jRGZZRXQ2ek9nOUtFNVJkaVl3cFpQNDBMaVwvaHBcL200N242MHA4RDU0V0s4NHpWMnN4WHM3THRrQm9ONzlSOVFJaEFQXC9cL1wvXC84QUFBQUFcL1wvXC9cL1wvXC9cL1wvXC9cLys4NXZxdHB4ZWVoUE81eXNMOFl5VlJBZ0VCQTBJQUJHbStnc2wwUFpGVFwva0RkVVNreHd5Zm84SnB3VFFRekJtOWxKSm5tVGw0REdVdkFENEdzZUdqXC9wc2hCWjBLM1RldXFEdFwvdERMYkUrOFwvbTB5Q21veHc9IiwicHVibGljS2V5SGFzaCI6IlwvYmI5Q05DMzZ1QmhlSEZQYm1vaEI3T28xT3NYMkora0pxdjQ4ek9WVmlRPSJ9LCJzaWduYXR1cmUiOiJNSUlEUWdZSktvWklodmNOQVFjQ29JSURNekNDQXk4Q0FRRXhDekFKQmdVckRnTUNHZ1VBTUFzR0NTcUdTSWIzRFFFSEFhQ0NBaXN3Z2dJbk1JSUJsS0FEQWdFQ0FoQmNsK1BmMytVNHBrMTNuVkQ5bndRUU1Ba0dCU3NPQXdJZEJRQXdKekVsTUNNR0ExVUVBeDRjQUdNQWFBQnRBR0VBYVFCQUFIWUFhUUJ6QUdFQUxnQmpBRzhBYlRBZUZ3MHhOREF4TURFd05qQXdNREJhRncweU5EQXhNREV3TmpBd01EQmFNQ2N4SlRBakJnTlZCQU1lSEFCakFHZ0FiUUJoQUdrQVFBQjJBR2tBY3dCaEFDNEFZd0J2QUcwd2daOHdEUVlKS29aSWh2Y05BUUVCQlFBRGdZMEFNSUdKQW9HQkFOQzgra2d0Z212V0YxT3pqZ0ROcmpURUJSdW9cLzVNS3ZsTTE0NnBBZjdHeDQxYmxFOXc0ZklYSkFEN0ZmTzdRS2pJWFlOdDM5ckx5eTd4RHdiXC81SWtaTTYwVFoyaUkxcGo1NVVjOGZkNGZ6T3BrM2Z0WmFRR1hOTFlwdEcxZDlWN0lTODJPdXA5TU1vMUJQVnJYVFBITmNzTTk5RVBVblBxZGJlR2M4N20wckFnTUJBQUdqWERCYU1GZ0dBMVVkQVFSUk1FK0FFSFpXUHJXdEpkN1laNDMxaENnN1lGU2hLVEFuTVNVd0l3WURWUVFESGh3QVl3Qm9BRzBBWVFCcEFFQUFkZ0JwQUhNQVlRQXVBR01BYndCdGdoQmNsK1BmMytVNHBrMTNuVkQ5bndRUU1Ba0dCU3NPQXdJZEJRQURnWUVBYlVLWUNrdUlLUzlRUTJtRmNNWVJFSW0ybCtYZzhcL0pYditHQlZRSmtPS29zY1k0aU5ERkFcL2JRbG9nZjlMTFU4NFRId05SbnN2VjNQcnY3UlRZODFncTBkdEM4elljQWFBa0NISUkzeXFNbko0QU91NkVPVzlrSmsyMzJnU0U3V2xDdEhiZkxTS2Z1U2dRWDhLWFFZdVpMazJScjYzTjhBcFhzWHdCTDNjSjB4Z2VBd2dkMENBUUV3T3pBbk1TVXdJd1lEVlFRREhod0FZd0JvQUcwQVlRQnBBRUFBZGdCcEFITUFZUUF1QUdNQWJ3QnRBaEJjbCtQZjMrVTRwazEzblZEOW53UVFNQWtHQlNzT0F3SWFCUUF3RFFZSktvWklodmNOQVFFQkJRQUVnWUJhSzNFbE9zdGJIOFdvb3NlREFCZitKZ1wvMTI5SmNJYXdtN2M2VnhuN1phc05iQXEzdEF0OFB0eSt1UUNnc3NYcVprTEE3a3oyR3pNb2xOdHY5d1ltdTlVandhcjFQSFlTK0JcL29Hbm96NTkxd2phZ1hXUnowbk1vNXkzTzFLelgwZDhDUkhBVmE4OFNyVjFhNUpJaVJldjNvU3RJcXd2NXh1WmxkYWc2VHI4dz09In0="

	paymentOne = apicontractsv1.paymentType()
	paymentOne.opaqueData = opaquedata

	transactionrequest = apicontractsv1.transactionRequestType()
	transactionrequest.transactionType = apicontractsv1.transactionTypeEnum.authCaptureTransaction
	transactionrequest.amount = Decimal('151')
	transactionrequest.payment = paymentOne

	request = apicontractsv1.createTransactionRequest()
	request.merchantAuthentication = merchantAuth
	request.refId = "Sample"
	request.transactionRequest = transactionrequest

	controller = createTransactionController(request)
	controller.execute()

	response = controller.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);
				print ('AUTH Code : %s' % response.authCode)
			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
def create_an_accept_transaction():

	merchantAuth = apicontractsv1.merchantAuthenticationType()
	merchantAuth.name = constants.apiLoginId
	merchantAuth.transactionKey = constants.transactionKey

	opaquedata = apicontractsv1.opaqueDataType()
	opaquedata.dataDescriptor = "COMMON.ACCEPT.INAPP.PAYMENT"
	opaquedata.dataValue = "9471471570959063005001"

	paymentOne = apicontractsv1.paymentType()
	paymentOne.opaqueData = opaquedata

	transactionrequest = apicontractsv1.transactionRequestType()
	transactionrequest.transactionType = apicontractsv1.transactionTypeEnum.authCaptureTransaction
	transactionrequest.amount = Decimal('151')
	transactionrequest.payment = paymentOne

	request = apicontractsv1.createTransactionRequest()
	request.merchantAuthentication = merchantAuth
	request.refId = "Sample"
	request.transactionRequest = transactionrequest

	controller = createTransactionController(request)
	controller.execute()

	response = controller.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);
				print ('AUTH Code : %s' % response.authCode)
			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
def create_subscription(amount, days):

    # Setting the merchant details
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = constants.apiLoginId
    merchantAuth.transactionKey = constants.transactionKey
    # Setting payment schedule
    paymentschedule = apicontractsv1.paymentScheduleType()
    paymentschedule.interval = apicontractsv1.paymentScheduleTypeInterval() #apicontractsv1.CTD_ANON() #modified by krgupta
    paymentschedule.interval.length = days
    paymentschedule.interval.unit = apicontractsv1.ARBSubscriptionUnitEnum.days
    paymentschedule.startDate = datetime(2020, 8, 30)
    paymentschedule.totalOccurrences = 12
    paymentschedule.trialOccurrences = 1
    # Giving the credit card info
    creditcard = apicontractsv1.creditCardType()
    creditcard.cardNumber = "4111111111111111"
    creditcard.expirationDate = "2020-12"
    payment = apicontractsv1.paymentType()
    payment.creditCard = creditcard
    # Setting billing information
    billto = apicontractsv1.nameAndAddressType()
    billto.firstName = "John"
    billto.lastName = "Smith"
    # Setting subscription details
    subscription = apicontractsv1.ARBSubscriptionType()
    subscription.name = "Sample Subscription"
    subscription.paymentSchedule = paymentschedule
    subscription.amount = amount
    subscription.trialAmount = Decimal('0.00')
    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)
    controller.execute()
    # Getting the response
    response = controller.getresponse()

    if (response.messages.resultCode=="Ok"):
        print ("SUCCESS:")
        print ("Message Code : %s" % response.messages.message[0]['code'].text)
        print ("Message text : %s" % str(response.messages.message[0]['text'].text))
        print ("Subscription ID : %s" % response.subscriptionId)
    else:
        print ("ERROR:")
        print ("Message Code : %s" % response.messages.message[0]['code'].text)
        print ("Message text : %s" % response.messages.message[0]['text'].text)

    return response
def authorization_only_continued():
	merchantAuth = apicontractsv1.merchantAuthenticationType()
	merchantAuth.name = constants.apiLoginId
	merchantAuth.transactionKey = constants.transactionKey

	paypal = apicontractsv1.payPalType()
	paypal.successUrl = "http://www.merchanteCommerceSite.com/Success/TC25262"
	paypal.cancelUrl = "http://www.merchanteCommerceSite.com/Success/TC25262"
	paypal.payerID = "LM6NCLZ5RAKBY"

	payment = apicontractsv1.paymentType()
	payment.payPal = paypal

	transactionrequest = apicontractsv1.transactionRequestType()
	transactionrequest.transactionType = apicontractsv1.transactionTypeEnum.authOnlyContinueTransaction
	transactionrequest.refTransId = "2245592542"
	transactionrequest.payment = payment

	request = apicontractsv1.createTransactionRequest()
	request.merchantAuthentication = merchantAuth
	request.refId = "Sample"
	request.transactionRequest = transactionrequest

	controller = createTransactionController(request)
	controller.execute()

	response = controller.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 ("Payer Id : %s " % response.transactionResponse.secureAcceptance.PayerID)
				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
Example #31
0
def get_settled_batch_list():
    utility.helper.setpropertyfile('anet_python_sdk_properties.ini')
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = constants.apiLoginId
    merchantAuth.transactionKey = constants.transactionKey

    settledBatchListRequest = apicontractsv1.getSettledBatchListRequest()
    settledBatchListRequest.merchantAuthentication = merchantAuth
    settledBatchListRequest.firstSettlementDate = datetime.now() - timedelta(
        days=31)
    settledBatchListRequest.lastSettlementDate = datetime.now()

    settledBatchListController = getSettledBatchListController(
        settledBatchListRequest)

    settledBatchListController.execute()

    settledBatchListResponse = settledBatchListController.getresponse()

    if settledBatchListResponse is not None:
        if settledBatchListResponse.messages.resultCode == apicontractsv1.messageTypeEnum.Ok:
            print('Successfully got settled batch list!')

            #if hasattr(response, 'batch') == True:
            #mylist = settledBatchListResponse.batchList.batch

            for batchItem in settledBatchListResponse.batchList.batch:
                #print ("LOOK batchItem   = %s" %batchItem)
                print('Batch Id : %s' % batchItem.batchId)
                print('Settlement State : %s' % batchItem.settlementState)
                print('Payment Method : %s' % batchItem.paymentMethod)
                if hasattr(batchItem, 'product') == True:
                    print('Product : %s' % batchItem.product)

                if hasattr(settledBatchListResponse.batchList.batch,
                           'statistics') == True:
                    if hasattr(
                            settledBatchListResponse.batchList.batch.
                            statistics, 'statistic') == True:
                        # 				if batchItem.statistics:
                        for statistic in batchItem.statistics.statistic:
                            print('Account Type : %s' % statistic.accountType)
                            print('Charge Amount : %s' %
                                  statistic.chargeAmount)
                            print('Refund Amount : %s' %
                                  statistic.refundAmount)
                            print('Decline Count : %s' %
                                  statistic.declineCount)
            if len(settledBatchListResponse.messages) != 0:
                print(
                    'Message Code : %s' %
                    settledBatchListResponse.messages.message[0]['code'].text)
                print(
                    'Message Text : %s' %
                    settledBatchListResponse.messages.message[0]['text'].text)
        else:
            if len(settledBatchListResponse.messages) != 0:
                print(
                    'Failed to get settled batch list.\nCode:%s \nText:%s' %
                    (settledBatchListResponse.messages.message[0]['code'].text,
                     settledBatchListResponse.messages.message[0]['text'].text)
                )

    return settledBatchListResponse
Example #32
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)
    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})
Example #33
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')
Example #34
0
def provider_create_subscriptiondetails_from_customer_profile(
        amount, days, startdate, profileId):
    # Setting the merchant details
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = get_secret("API_LOGIN_ID")
    merchantAuth.transactionKey = get_secret("API_TRANSACTION_KEY")
    # Setting payment schedule
    paymentschedule = apicontractsv1.paymentScheduleType()
    paymentschedule.interval = apicontractsv1.paymentScheduleTypeInterval(
    )  # apicontractsv1.CTD_ANON() #modified by krgupta
    paymentschedule.interval.length = days
    paymentschedule.interval.unit = apicontractsv1.ARBSubscriptionUnitEnum.days
    paymentschedule.startDate = startdate
    paymentschedule.totalOccurrences = 999
    paymentschedule.trialOccurrences = 0

    # setting the customer profile details
    profile = apicontractsv1.customerProfileIdType()

    getCustomerProfile = apicontractsv1.getCustomerProfileRequest()
    getCustomerProfile.merchantAuthentication = merchantAuth
    getCustomerProfile.customerProfileId = str(profileId)
    controller = getCustomerProfileController(getCustomerProfile)
    controller.execute()

    response = controller.getresponse()

    paymentProfileId = None
    if (response.messages.resultCode == "Ok"):
        print(
            "Successfully retrieved a customer with profile id %s and customer id %s"
            % (getCustomerProfile.customerProfileId,
               response.profile.merchantCustomerId))
        if hasattr(response, 'profile') == True:
            profile.customerProfileId = getCustomerProfile.customerProfileId
            if hasattr(response.profile, 'paymentProfiles') == True:
                for paymentProfile in response.profile.paymentProfiles:
                    print("paymentProfile in get_customerprofile is:" %
                          paymentProfile)
                    print("Payment Profile ID %s" %
                          str(paymentProfile.customerPaymentProfileId))
                    paymentProfileId = str(
                        paymentProfile.customerPaymentProfileId)
        else:
            print("Failed to get customer profile information with id %s" %
                  getCustomerProfile.customerProfileId)

    profile.customerPaymentProfileId = paymentProfileId
    profile.customerAddressId = None

    # Setting subscription details
    subscription = apicontractsv1.ARBSubscriptionType()
    subscription.name = "Sample Subscription"
    subscription.paymentSchedule = paymentschedule
    subscription.amount = amount
    subscription.trialAmount = Decimal('0.00')
    subscription.profile = profile

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

    # Creating and executing the controller
    controller = ARBCreateSubscriptionController(request)
    controller.execute()
    # Getting the response
    response = controller.getresponse()

    if (response.messages.resultCode == "Ok"):
        print("SUCCESS:")
        print("Message Code : %s" % response.messages.message[0]['code'].text)
        print("Message text : %s" % response.messages.message[0]['text'].text)
        print("Subscription ID : %s" % response.subscriptionId)
    else:
        print("ERROR:")
        print("Message Code : %s" % response.messages.message[0]['code'].text)
        print("Message text : %s" % response.messages.message[0]['text'].text)

    return response
def authorization_and_capture_continue(refTransId, payerID):
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = constants.apiLoginId
    merchantAuth.transactionKey = constants.transactionKey

    paypal = apicontractsv1.payPalType()
    paypal.payerID = payerID

    payment = apicontractsv1.paymentType()
    payment.payPal = paypal

    transactionrequest = apicontractsv1.transactionRequestType()
    transactionrequest.transactionType = apicontractsv1.transactionTypeEnum.authCaptureContinueTransaction
    transactionrequest.refTransId = refTransId
    transactionrequest.payment = payment

    request = apicontractsv1.createTransactionRequest()
    request.merchantAuthentication = merchantAuth
    request.refId = "Sample"
    request.transactionRequest = transactionrequest

    controller = createTransactionController(request)
    controller.execute()

    response = controller.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("Payer Id : %s " %
                      response.transactionResponse.secureAcceptance.PayerID)
                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
Example #36
0
def charge_tokenized_credit_card():
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = constants.apiLoginId
    merchantAuth.transactionKey = constants.transactionKey

    creditCard = apicontractsv1.creditCardType()
    creditCard.cardNumber = "4111111111111111"
    creditCard.expirationDate = "2035-12"
    # Set the token specific info
    creditCard.isPaymentToken = True
    creditCard.cryptogram = "EjRWeJASNFZ4kBI0VniQEjRWeJA="

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

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

    createtransactionrequest = apicontractsv1.createTransactionRequest()
    createtransactionrequest.merchantAuthentication = merchantAuth
    createtransactionrequest.refId = "MerchantID-0001"
    createtransactionrequest.transactionRequest = transactionrequest

    createtransactioncontroller = createTransactionController(
        createtransactionrequest)
    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
Example #37
0
def get_settled_batch_list():
    """get settled batch list"""
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = CONSTANTS.apiLoginId
    merchantAuth.transactionKey = CONSTANTS.transactionKey

    settledBatchListRequest = apicontractsv1.getSettledBatchListRequest()
    settledBatchListRequest.merchantAuthentication = merchantAuth
    settledBatchListRequest.refId = "Sample"
    settledBatchListRequest.includeStatistics = True
    settledBatchListRequest.firstSettlementDate = datetime.now() - timedelta(
        days=31)
    settledBatchListRequest.lastSettlementDate = datetime.now()

    settledBatchListController = getSettledBatchListController(
        settledBatchListRequest)
    settledBatchListController.execute()

    response = settledBatchListController.getresponse()

    # Work on the response
    if response is not None:
        if response.messages.resultCode == apicontractsv1.messageTypeEnum.Ok:
            if hasattr(response, 'batchList'):
                print('Successfully retrieved batch list.')
                if response.messages is not None:
                    print('Message Code: %s' %
                          response.messages.message[0]['code'].text)
                    print('Message Text: %s' %
                          response.messages.message[0]['text'].text)
                    print()
                for batchEntry in response.batchList.batch:
                    print('Batch Id: %s' % batchEntry.batchId)
                    print('Settlement Time UTC: %s' %
                          batchEntry.settlementTimeUTC)
                    print('Payment Method: %s' % batchEntry.paymentMethod)
                    if hasattr(batchEntry, 'marketType'):
                        print('Market Type: %s' % batchEntry.marketType)
                    if hasattr(batchEntry, 'product'):
                        print('Product: %s' % batchEntry.product)
                    if hasattr(batchEntry, 'statistics'):
                        if hasattr(batchEntry.statistics, 'statistic'):
                            for statistic in batchEntry.statistics.statistic:
                                if hasattr(statistic, 'accountType'):
                                    print('Account Type: %s' %
                                          statistic.accountType)
                                if hasattr(statistic, 'chargeAmount'):
                                    print('  Charge Amount: %.2f' %
                                          statistic.chargeAmount)
                                if hasattr(statistic, 'chargeCount'):
                                    print('  Charge Count: %s' %
                                          statistic.chargeCount)
                                if hasattr(statistic, 'refundAmount'):
                                    print('  Refund Amount: %.2f' %
                                          statistic.refundAmount)
                                if hasattr(statistic, 'refundCount'):
                                    print('  Refund Count: %s' %
                                          statistic.refundCount)
                                if hasattr(statistic, 'voidCount'):
                                    print('  Void Count: %s' %
                                          statistic.voidCount)
                                if hasattr(statistic, 'declineCount'):
                                    print('  Decline Count: %s' %
                                          statistic.declineCount)
                                if hasattr(statistic, 'errorCount'):
                                    print('  Error Count: %s' %
                                          statistic.errorCount)
                                if hasattr(statistic, 'returnedItemAmount'):
                                    print('  Returned Item Amount: %.2f' %
                                          statistic.returnedItemAmount)
                                if hasattr(statistic, 'returnedItemCount'):
                                    print('  Returned Item Count: %s' %
                                          statistic.returnedItemCount)
                                if hasattr(statistic, 'chargebackAmount'):
                                    print('  Chargeback Amount: %.2f' %
                                          statistic.chargebackAmount)
                                if hasattr(statistic, 'chargebackCount'):
                                    print('  Chargeback Count: %s' %
                                          statistic.chargebackCount)
                                if hasattr(statistic, 'correctionNoticeCount'):
                                    print('  Correction Notice Count: %s' %
                                          statistic.correctionNoticeCount)
                                if hasattr(statistic,
                                           'chargeChargeBackAmount'):
                                    print('  Charge Chargeback Amount: %.2f' %
                                          statistic.chargeChargeBackAmount)
                                if hasattr(statistic, 'chargeChargeBackCount'):
                                    print('  Charge Chargeback Count: %s' %
                                          statistic.chargeChargeBackCount)
                                if hasattr(statistic,
                                           'refundChargeBackAmount'):
                                    print('  Refund Chargeback Amount: %.2f' %
                                          statistic.refundChargeBackAmount)
                                if hasattr(statistic, 'refundChargeBackCount'):
                                    print('  Refund Chargeback Count: %s' %
                                          statistic.refundChargeBackCount)
                                if hasattr(statistic,
                                           'chargeReturnedItemsAmount'):
                                    print(
                                        '  Charge Returned Items Amount: %.2f'
                                        % statistic.chargeReturnedItemsAmount)
                                if hasattr(statistic,
                                           'chargeReturnedItemsCount'):
                                    print('  Charge Returned Items Count: %s' %
                                          statistic.chargeReturnedItemsCount)
                                if hasattr(statistic,
                                           'refundReturnedItemsAmount'):
                                    print(
                                        '  Refund Returned Items Amount: %.2f'
                                        % statistic.refundReturnedItemsAmount)
                                if hasattr(statistic,
                                           'refundReturnedItemsCount'):
                                    print('  Refund Returned Items Count: %s' %
                                          statistic.refundReturnedItemsCount)
                    print()
            else:
                if response.messages is not None:
                    print('Failed to get transaction list.')
                    print('Code: %s' %
                          (response.messages.message[0]['code'].text))
                    print('Text: %s' %
                          (response.messages.message[0]['text'].text))
        else:
            if response.messages is not None:
                print('Failed to get transaction list.')
                print('Code: %s' % (response.messages.message[0]['code'].text))
                print('Text: %s' % (response.messages.message[0]['text'].text))
    else:
        print('Error. No response received.')

    return response
Example #38
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
Example #39
0
def debit_bank_account():

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

    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = constants.apiLoginId
    merchantAuth.transactionKey = constants.transactionKey

    payment = apicontractsv1.paymentType()

    bankAccountType = apicontractsv1.bankAccountType()
    accountType = apicontractsv1.bankAccountTypeEnum
    bankAccountType.accountType = accountType.checking
    bankAccountType.routingNumber = "125000024"
    bankAccountType.accountNumber = "12345678"
    bankAccountType.nameOnAccount = "John Doe"

    transactionrequest = apicontractsv1.transactionRequestType()
    transactionrequest.transactionType = "authCaptureTransaction"
    transactionrequest.amount = Decimal(amount)
    transactionrequest.payment = payment
    transactionrequest.payment.bankAccount = bankAccountType

    createtransactionrequest = apicontractsv1.createTransactionRequest()
    createtransactionrequest.merchantAuthentication = merchantAuth
    createtransactionrequest.refId = "MerchantID-0001"

    createtransactionrequest.transactionRequest = transactionrequest
    createtransactioncontroller = createTransactionController(
        createtransactionrequest)
    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
Example #40
0
    def process(data):
        # reference https://github.com/AuthorizeNet/sample-code-python/blob/master/PaymentTransactions/charge-credit-card.py
        # todo testing in a sandbox environment.

        try:
            # prepare data for sending out to Authorize.net
            name = data["name"].strip().split(" ")
            data["first_name"] = name[0] if len(name) else ""
            data["last_name"] = name[len(name) - 1] if len(name) > 1 else ""
            data["card_number"] = data["card_number"].replace("-", "").replace(
                "/", "")
            data["expiry"] = data["expiry"].replace("-", "").replace("/", "")

            # Create a merchantAuthenticationType object with authentication details
            # retrieved from the constants file
            merchantAuth = apicontractsv1.merchantAuthenticationType()
            merchantAuth.name = "login id"
            merchantAuth.transactionKey = "transaction key"

            # Create the payment data for a credit card
            creditCard = apicontractsv1.creditCardType()
            creditCard.cardNumber = data["card_number"]
            creditCard.expirationDate = data["expiry"]
            creditCard.cardCode = data["cvv"]

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

            # Set the customer's Bill To address
            customerAddress = apicontractsv1.customerAddressType()
            customerAddress.firstName = data["first_name"]
            customerAddress.lastName = data["last_name"]

            # 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 = '12'
            transactionrequest.payment = payment
            transactionrequest.billTo = customerAddress
            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()

            output = {}

            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:

                        output = {
                            "status":
                            200,
                            "message":
                            response.transactionResponse.messages.message[0].
                            description
                        }
                    else:
                        if hasattr(response.transactionResponse,
                                   'errors') is True:
                            output = {
                                "status":
                                405,
                                "message":
                                response.transactionResponse.errors.error[0].
                                errorText
                            }
                        else:
                            output = {
                                "status":
                                405,
                                "message":
                                response.messages.message[0]['text'].text
                            }
                # Or, print errors if the API request wasn't successful
                else:
                    if hasattr(response.transactionResponse, 'errors') is True:
                        output = {
                            "status":
                            406,
                            "message":
                            response.transactionResponse.errors.error[0].
                            errorText
                        }
                    else:
                        output = {
                            "status": 406,
                            "message":
                            response.messages.message[0]['text'].text
                        }
            else:
                output = {"status": 407, "message": "No Response from Server"}

            return output
        except Exception as e:
            # print(e)
            return {
                "status": 408,
                "message": "Unexpected error. Please contact the administrator"
            }
from authorizenet import apicontractsv1
from authorizenet.apicontrollers import *
from decimal import *

merchantAuth = apicontractsv1.merchantAuthenticationType()
merchantAuth.name = '5KP3u95bQpv'
merchantAuth.transactionKey = '4Ktq966gC55GAX7S'

setting = apicontractsv1.settingType()
setting.settingName = apicontractsv1.settingNameEnum.hostedProfileReturnUrl
setting.settingValue = "https://returnurl.com/return/"

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

profilePageRequest = apicontractsv1.getHostedProfilePageRequest()
profilePageRequest.merchantAuthentication = merchantAuth
profilePageRequest.customerProfileId = "36152116"
profilePageRequest.hostedProfileSettings = settings

profilePageController = getHostedProfilePageController(profilePageRequest)

profilePageController.execute()

profilePageResponse = profilePageController.getresponse()

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

		print('Token : %s' % profilePageResponse.token)
Example #42
0
def authorization_only():
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = constants.apiLoginId
    merchantAuth.transactionKey = constants.transactionKey

    paypal = apicontractsv1.payPalType()
    paypal.successUrl = "http://www.merchanteCommerceSite.com/Success/TC25262"
    paypal.cancelUrl = "http://www.merchanteCommerceSite.com/Success/TC25262"

    payment = apicontractsv1.paymentType()
    payment.payPal = paypal

    transactionrequest = apicontractsv1.transactionRequestType()
    transactionrequest.amount = Decimal('55.00')
    transactionrequest.transactionType = apicontractsv1.transactionTypeEnum.authOnlyTransaction
    transactionrequest.payment = payment

    request = apicontractsv1.createTransactionRequest()
    request.merchantAuthentication = merchantAuth
    request.refId = "Sample"
    request.transactionRequest = transactionrequest

    controller = createTransactionController(request)
    controller.execute()

    response = controller.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("Secure acceptance URL : %s " % response.
                      transactionResponse.secureAcceptance.SecureAcceptanceUrl)
                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
Example #43
0
def refund_transaction(refTransId):
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = constants.apiLoginId
    merchantAuth.transactionKey = constants.transactionKey

    creditCard = apicontractsv1.creditCardType()
    creditCard.cardNumber = "0015"
    creditCard.expirationDate = "XXXX"

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

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

    createtransactionrequest = apicontractsv1.createTransactionRequest()
    createtransactionrequest.merchantAuthentication = merchantAuth
    createtransactionrequest.refId = "MerchantID-0001"

    createtransactionrequest.transactionRequest = transactionrequest
    createtransactioncontroller = createTransactionController(
        createtransactionrequest)
    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
Example #44
0
 def setUp(self):
     self.merchant = apicontractsv1.merchantAuthenticationType()
     self.merchant.name = API_KEY
     self.merchant.transactionKey = TRANSACTION_KEY
Example #45
0
def credit_bank_account(amount):
    """
    Credit a bank account
    """
    # 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 bank account
    bankAccount = apicontractsv1.bankAccountType()
    accountType = apicontractsv1.bankAccountTypeEnum
    bankAccount.accountType = accountType.checking
    bankAccount.routingNumber = "121042882"
    bankAccount.accountNumber = "1234567890"
    bankAccount.nameOnAccount = "John Doe"

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

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

    # 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
Example #46
0
    def issue_credit(self, order_number, basket, reference_number, amount, currency):  # pylint: disable=too-many-statements
        """
            Refund a AuthorizeNet payment for settled transactions.For more Authorizenet Refund API information,
            visit https://developer.authorize.net/api/reference/#payment-transactions-refund-a-transaction
        """
        try:
            paymnet_response = PaymentProcessorResponse.objects.filter(
                processor_name=self.NAME,
                transaction_id=reference_number
            ).latest('created')
            reference_transaction_details = json.loads(paymnet_response.response)
        except:
            msg = 'AuthorizeNet issue credit error for order [{}]. Unable to get payment transaction details.'.format(
                order_number)
            logger.exception(msg)
            raise PaymentProcessorResponseNotFound(msg)

        transaction_card_info = reference_transaction_details.get('transaction', {}).get('payment', {}).get(
            'creditCard', {})

        if not transaction_card_info:
            msg = 'AuthorizeNet issue credit error for order [{}]. Unable to get card-information.'.format(
                order_number)
            logger.exception(msg)
            raise MissingProcessorResponseCardInfo(msg)

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

        credit_card = apicontractsv1.creditCardType()
        credit_card.cardNumber = transaction_card_info.get('cardNumber', "")[-4:]
        credit_card.expirationDate = transaction_card_info.get('expirationDate', "")

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

        transaction_request = apicontractsv1.transactionRequestType()
        transaction_request.transactionType = "refundTransaction"
        transaction_request.amount = amount

        transaction_request.refTransId = reference_number   # set refTransId to transId of a settled transaction
        transaction_request.payment = payment

        create_transaction_request = apicontractsv1.createTransactionRequest()
        create_transaction_request.merchantAuthentication = merchant_auth

        create_transaction_request.transactionRequest = transaction_request
        create_transaction_controller = createTransactionController(create_transaction_request)
        create_transaction_controller.execute()

        response = create_transaction_controller.getresponse()
        if response is not None:
            if response.messages.resultCode == "Ok":
                if hasattr(response.transactionResponse, 'messages'):
                    logger.info('Message Code: %s', response.transactionResponse.messages.message[0].code)
                    logger.info('Description: %s', response.transactionResponse.messages.message[0].description)

                    refund_transaction_id = response.transactionResponse.transId
                    refund_transaction_dict = LxmlObjectJsonEncoder().encode(response)
                    self.record_processor_response(
                        refund_transaction_dict, transaction_id=refund_transaction_id, basket=basket)
                    return refund_transaction_id
                else:
                    logger.error('AuthorizeNet issue credit request failed.')
                    if hasattr(response.transactionResponse, 'errors'):
                        logger.error('Error Code:  %s', str(response.transactionResponse.errors.error[0].errorCode))
                        logger.error('Error message: %s', response.transactionResponse.errors.error[0].errorText)
            else:
                logger.error('AuthorizeNet issue credit request failed.')
                if hasattr(response, 'transactionResponse') and hasattr(response.transactionResponse, 'errors'):
                    logger.error('Error Code: %s', str(response.transactionResponse.errors.error[0].errorCode))
                    logger.error('Error message: %s', response.transactionResponse.errors.error[0].errorText)
                else:
                    logger.error('Error Code: %s', response.messages.message[0]['code'].text)
                    logger.error('Error message: %s', response.messages.message[0]['text'].text)

        msg = 'An error occurred while attempting to issue a credit (via Authorizenet) for order [{}].'.format(
            order_number)
        logger.exception(msg)
        raise RefundError(msg)
Example #47
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
Example #48
0
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
Example #49
0
def charge_credit_card(data):

    # Create a merchantAuthenticationType object with authentication details
    # retrieved from the constants file
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = "2U6x9AuE"
    merchantAuth.transactionKey = "5KY6z6r64HtK8kgv"

    # Create the payment data for a credit card
    creditCard = apicontractsv1.creditCardType()
    creditCard.cardNumber = data["createTransactionRequest"]["transactionRequest"]["payment"]["creditCard"]["cardNumber"]
    creditCard.expirationDate = data["createTransactionRequest"]["transactionRequest"]["payment"]["creditCard"]["expirationDate"]
    creditCard.cardCode = data["createTransactionRequest"]["transactionRequest"]["payment"]["creditCard"]["cardCode"]

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

    # Create a transactionRequestType object and add the previous objects to it.
    transactionrequest = apicontractsv1.transactionRequestType()
    transactionrequest.transactionType = "authCaptureTransaction"
    transactionrequest.amount = data["createTransactionRequest"]["transactionRequest"]["amount"]
    transactionrequest.payment = payment

    # 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
def get_transaction_list():
    """get transaction list for a specific batch"""
    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = constants.apiLoginId
    merchantAuth.transactionKey = constants.transactionKey

    # set sorting parameters
    sorting = apicontractsv1.TransactionListSorting()
    sorting.orderBy = apicontractsv1.TransactionListOrderFieldEnum.id
    sorting.orderDescending = True

    # set paging and offset parameters
    paging = apicontractsv1.Paging()
    # Paging limit can be up to 1000 for this request
    paging.limit = 20
    paging.offset = 1

    transactionListRequest = apicontractsv1.getTransactionListRequest()
    transactionListRequest.merchantAuthentication = merchantAuth
    transactionListRequest.refId = "Sample"
    transactionListRequest.batchId = "4606008"
    transactionListRequest.sorting = sorting
    transactionListRequest.paging = paging

    transactionListController = getTransactionListController(
        transactionListRequest)
    transactionListController.execute()

    # Work on the response
    response = transactionListController.getresponse()

    if response is not None:
        if response.messages.resultCode == apicontractsv1.messageTypeEnum.Ok:
            if hasattr(response, 'transactions'):
                print('Successfully retrieved transaction list.')
                if response.messages is not None:
                    print('Message Code: %s' %
                          response.messages.message[0]['code'].text)
                    print('Message Text: %s' %
                          response.messages.message[0]['text'].text)
                    print('Total Number In Results: %s' %
                          response.totalNumInResultSet)
                    print()
                for transaction in response.transactions.transaction:
                    print('Transaction Id: %s' % transaction.transId)
                    print('Transaction Status: %s' %
                          transaction.transactionStatus)
                    if hasattr(transaction, 'accountType'):
                        print('Account Type: %s' % transaction.accountType)
                    print('Settle Amount: %.2f' % transaction.settleAmount)
                    if hasattr(transaction, 'profile'):
                        print('Customer Profile ID: %s' %
                              transaction.profile.customerProfileId)
                    print()
            else:
                if response.messages is not None:
                    print('Failed to get transaction list.')
                    print('Code: %s' %
                          (response.messages.message[0]['code'].text))
                    print('Text: %s' %
                          (response.messages.message[0]['text'].text))
        else:
            if response.messages is not None:
                print('Failed to get transaction list.')
                print('Code: %s' % (response.messages.message[0]['code'].text))
                print('Text: %s' % (response.messages.message[0]['text'].text))
    else:
        print('Error. No response received.')

    return response
Example #51
0
def chargeCard(customerInfo):  #takes a dictionary that has customer info

    merchantAuth = apicontractsv1.merchantAuthenticationType()  #required
    merchantAuth.name = '4urP8Y47'  #required
    merchantAuth.transactionKey = '538g4Tg2uMBte3W8'  #required

    creditCard = apicontractsv1.creditCardType()
    creditCard.cardNumber = "6011000000000012"  # this stays this way for testing purposes.
    creditCard.expirationDate = "2021-12"  # date only needs to be later than current date.

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

    customerAddress = apicontractsv1.customerAddressType()
    customerAddress.firstName = customerInfo["firstName"]
    customerAddress.lastName = customerInfo["lastName"]
    customerAddress.company = customerInfo["company"]
    customerAddress.address = customerInfo["address"]
    customerAddress.city = customerInfo["city"]
    customerAddress.state = customerInfo["state"]
    customerAddress.zip = customerInfo["zipCode"]
    customerAddress.phoneNumber = customerInfo["phone"]
    customerAddress.email = customerInfo["email"]

    transactionrequest = apicontractsv1.transactionRequestType()
    transactionrequest.transactionType = "authCaptureTransaction"
    transactionrequest.amount = Decimal(customerInfo["amount"])  #required
    transactionrequest.payment = payment
    transactionrequest.billTo = customerAddress

    createtransactionrequest = apicontractsv1.createTransactionRequest()
    createtransactionrequest.merchantAuthentication = merchantAuth
    createtransactionrequest.refId = "MerchantID-0001"

    createtransactionrequest.transactionRequest = transactionrequest
    createtransactioncontroller = createTransactionController(
        createtransactionrequest)
    createtransactioncontroller.execute()

    response = createtransactioncontroller.getresponse()

    if (response.messages.resultCode == "Ok"):
        error = False

        message = ("Transaction ID : %s" %
                   response.transactionResponse.transId)
        print("Transaction ID : %s" % response.transactionResponse.transId)
    else:

        message = response.messages.resultCode
        print("response code: %s" % response.messages.resultCode)
    return response.transactionResponse.transId, message


# def save_customer():

#     #save customer

# def charge_profile(customer_profile):

#     # create request to charge profile
def capture_funds_authorized_through_another_channel():

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

    merchantAuth = apicontractsv1.merchantAuthenticationType()
    merchantAuth.name = constants.apiLoginId
    merchantAuth.transactionKey = constants.transactionKey

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

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

    transactionrequest = apicontractsv1.transactionRequestType()
    transactionrequest.transactionType = "captureOnlyTransaction"
    transactionrequest.amount = Decimal(amount)
    transactionrequest.payment = payment
    transactionrequest.authCode = "ROHNFQ"

    createtransactionrequest = apicontractsv1.createTransactionRequest()
    createtransactionrequest.merchantAuthentication = merchantAuth
    createtransactionrequest.refId = "MerchantID-0001"

    createtransactionrequest.transactionRequest = transactionrequest
    createtransactioncontroller = createTransactionController(
        createtransactionrequest)
    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
Example #53
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
Example #54
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
Example #55
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
Example #56
0
def provider_create_account(request, ohsubscription, person, company, address):

    print('In provider_create_account routine')
    try:
        print("Create Customer Profile -> Using AuthorizeNet : Start")
        merchantAuth = apicontractsv1.merchantAuthenticationType()
        merchantAuth.name = get_secret("API_LOGIN_ID")
        merchantAuth.transactionKey = get_secret("API_TRANSACTION_KEY")
        '''
        Create customer profile
        '''
        createCustomerProfile = apicontractsv1.createCustomerProfileRequest()
        createCustomerProfile.merchantAuthentication = merchantAuth

        createCustomerProfile.profile = apicontractsv1.customerProfileType(
            str(ohsubscription), person.first_name + ' ' + person.last_name,
            person.email)

        controller = createCustomerProfileController(createCustomerProfile)
        controller.execute()

        response = controller.getresponse()

        if (response.messages.resultCode == "Ok"):
            print("Successfully created a customer profile with id: %s" %
                  response.customerProfileId)
        else:
            print("Failed to create customer payment profile %s" %
                  response.messages.message[0]['text'].text)
        '''
        Create customer payment profile
        '''
        if not response.customerProfileId is None:
            creditCard = apicontractsv1.creditCardType()

            creditCard.cardNumber = request.POST.get("cardnumber", None)
            # creditCard.expirationDate = str(request.POST.get("cardmonth", None)  +'-'+ request.POST.get("cardyear", None) )

            ccardMonth = request.POST.get("cardmonth", None)
            if ccardMonth is not None:
                if len(ccardMonth) < 2:
                    ccardMonth = '0' + ccardMonth

            print('ccardMonth', request.POST.get("cardmonth", None),
                  ccardMonth)
            ccardYear = request.POST.get("cardyear", None)
            print('ccardYear', ccardYear, ccardYear[2:4])
            ccardExpirationDate = ccardMonth + ccardYear[2:4]
            print('ccardExpirationDate', ccardMonth, ccardYear,
                  ccardExpirationDate)
            creditCard.expirationDate = ccardExpirationDate
            print(' creditCard.expirationDate', creditCard.expirationDate)
            creditCard.cardCode = request.POST.get("cardcvv", None)
            payment = apicontractsv1.paymentType()
            payment.creditCard = creditCard

            billTo = apicontractsv1.customerAddressType()
            billTo.firstName = person.first_name
            billTo.lastName = person.last_name
            billTo.company = company.name
            # billTo.ip_address = get_client_ip(request)
            billTo.country = address.city.zipc_code.county.state.country_id
            billTo.address = address.address_line_1 + address.address_line_2
            billTo.city = address.city.name
            billTo.state = address.city.zipc_code.county.state.name
            billTo.zip = address.city.zipc_code_id

            profile = apicontractsv1.customerPaymentProfileType()
            profile.payment = payment
            profile.billTo = billTo
            profile.customerType = 'business'

            createCustomerPaymentProfile = apicontractsv1.createCustomerPaymentProfileRequest(
            )
            createCustomerPaymentProfile.merchantAuthentication = merchantAuth
            createCustomerPaymentProfile.paymentProfile = profile
            print(
                "customerProfileId in create_customer_payment_profile. customerProfileId = %s"
                % response.customerProfileId)
            createCustomerPaymentProfile.customerProfileId = str(
                response.customerProfileId)

            controller = createCustomerPaymentProfileController(
                createCustomerPaymentProfile)
            controller.execute()

            response = controller.getresponse()

            if (response.messages.resultCode == "Ok"):
                print(
                    "Successfully created a customer payment profile with id: %s"
                    % response.customerPaymentProfileId)
            else:
                print("Failed to create customer payment profile %s" %
                      response.messages.message[0]['text'].text)
                print("Create Account -> Using Recurly API : End")

    except ValueError:
        print('Exceprion occured while creating account with Recurly', )
        return None

    print('Authorize.Net.response', response.customerProfileId)
    return response.customerProfileId