def process_payment(self): # Init transaction self.transaction = self.create_transaction() self.transaction_type = self.create_transaction_type( settings.AUTHORIZE_NET_TRANSACTION_TYPE_DEFAULT) self.transaction_type.amount = self.to_valid_decimal( self.invoice.get_one_time_transaction_total()) self.transaction_type.payment = self.create_authorize_payment() self.transaction_type.billTo = self.create_billing_address( apicontractsv1.customerAddressType()) # Optional items for make it easier to read and use on the Authorize.net portal. if self.invoice.order_items: self.transaction_type.lineItems = self.create_line_item_array( self.invoice.order_items.all()) # You set the request to the transaction self.transaction.transactionRequest = self.transaction_type self.controller = createTransactionController(self.transaction) self.set_controller_api_endpoint() self.controller.execute() # You execute and get the response response = self.controller.getresponse() self.check_response(response) self.process_payment_transaction_response()
def is_card_valid(self): """ Handles an Authorize Only transaction to ensure that the funds are in the customers bank account """ self.create_payment_model() self.transaction = self.create_transaction() self.transaction_type = self.create_transaction_type( self.transaction_types[TransactionTypes.AUTHORIZE]) self.transaction_type.amount = self.to_valid_decimal( self.invoice.get_recurring_total()) self.transaction_type.payment = self.create_authorize_payment() self.transaction_type.billTo = self.create_billing_address( apicontractsv1.customerAddressType()) self.transaction.transactionRequest = self.transaction_type self.controller = createTransactionController(self.transaction) self.set_controller_api_endpoint() self.controller.execute() # You execute and get the response response = self.controller.getresponse() self.check_response(response) if self.transaction_submitted: self.void_payment(self.transaction_message['trans_id'].text) return True return False
def setUp(self): utility.helper.setpropertyfile('anet_python_sdk_properties.ini') self.amount = str(round(random.random() * 100, 2)) self.merchantAuthentication = apicontractsv1.merchantAuthenticationType( ) self.merchantAuthentication.name = utility.helper.getproperty( 'api.login.id') self.merchantAuthentication.transactionKey = utility.helper.getproperty( 'transaction.key') self.ref_id = 'Sample' self.dateOne = datetime.date(2020, 8, 30) self.interval = CTD_ANON() self.interval.length = 1 self.interval.unit = 'months' self.paymentScheduleOne = apicontractsv1.paymentScheduleType() self.paymentScheduleOne.interval = self.interval self.paymentScheduleOne.startDate = self.dateOne self.paymentScheduleOne.totalOccurrences = 12 self.paymentScheduleOne.trialOccurrences = 1 self.creditCardOne = apicontractsv1.creditCardType() self.creditCardOne.cardNumber = "4111111111111111" self.creditCardOne.expirationDate = "2020-12" self.payment = apicontractsv1.paymentType() self.payment.creditCard = self.creditCardOne self.customerOne = apicontractsv1.nameAndAddressType() self.customerOne.firstName = "John" self.customerOne.lastName = "Smith" self.customerData = apicontractsv1.customerDataType() self.customerData.id = "99999456654" self.subscriptionOne = apicontractsv1.ARBSubscriptionType() self.subscriptionOne.paymentSchedule = self.paymentScheduleOne self.subscriptionOne.amount = Decimal( str(round(random.random() * 100, 2))) self.subscriptionOne.trialAmount = Decimal('0.03') self.subscriptionOne.payment = self.payment self.subscriptionOne.billTo = self.customerOne self.order = apicontractsv1.orderType() self.order.invoiceNumber = "INV-21345" self.order.description = "Product description" self.billTo = apicontractsv1.customerAddressType() self.billTo.firstName = "Ellen" self.billTo.lastName = "Johnson" self.billTo.company = "Souveniropolis" self.billTo.address = "14 Main St" self.billTo.city = "Seattle" self.billTo.state = "WA" self.billTo.zip = "98122" self.billTo.country = "USA"
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 update_customer_payment_profile(customerProfileId, customerPaymentProfileId): 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 paymentProfile = apicontractsv1.customerPaymentProfileExType() paymentProfile.billTo = apicontractsv1.customerAddressType() paymentProfile.billTo.firstName = "John" paymentProfile.billTo.lastName = "Doe" paymentProfile.billTo.address = "123 Main St." paymentProfile.billTo.city = "Bellevue" paymentProfile.billTo.state = "WA" paymentProfile.billTo.zip = "98004" paymentProfile.billTo.country = "USA" paymentProfile.billTo.phoneNumber = "000-000-000" paymentProfile.payment = payment paymentProfile.customerPaymentProfileId = customerPaymentProfileId updateCustomerPaymentProfile = apicontractsv1.updateCustomerPaymentProfileRequest( ) updateCustomerPaymentProfile.merchantAuthentication = merchantAuth updateCustomerPaymentProfile.paymentProfile = paymentProfile updateCustomerPaymentProfile.customerProfileId = customerProfileId updateCustomerPaymentProfile.validationMode = apicontractsv1.validationModeEnum.liveMode controller = updateCustomerPaymentProfileController( updateCustomerPaymentProfile) controller.execute() response = controller.getresponse() if (response.messages.resultCode == "Ok"): print("Successfully updated customer payment profile with id %s" % updateCustomerPaymentProfile.paymentProfile. customerPaymentProfileId) else: print(response.messages.message[0]['text'].text) print("Failed to update customer with customer payment profile id %s" % updateCustomerPaymentProfile.paymentProfile. customerPaymentProfileId) return response
def make_billTo(first_name, last_name, company_name, address, city, state, zip_code, country, phone): """Create a billTo object""" billTo = apicontractsv1.customerAddressType() billTo.firstName = first_name billTo.lastName = last_name billTo.company = company_name billTo.address = address billTo.city = city billTo.state = state billTo.zip = zip_code billTo.country = country billTo.phoneNumber = phone return billTo
def createCustomerPaymentProfile(customerInfo): merchantAuth = apicontractsv1.merchantAuthenticationType() merchantAuth.name = '4urP8Y47' merchantAuth.transactionKey = '538g4Tg2uMBte3W8' creditCard = apicontractsv1.creditCardType() creditCard.cardNumber = "6011000000000012" # for the sake of testing this doesn't change creditCard.expirationDate = "2021-12" # this too payment = apicontractsv1.paymentType() payment.creditCard = creditCard billTo = apicontractsv1.customerAddressType() billTo.firstName = customerInfo["firstName"] billTo.lastName = customerInfo["lastName"] profile = apicontractsv1.customerPaymentProfileType() profile.payment = payment profile.billTo = billTo createCustomerPaymentProfile = apicontractsv1.createCustomerPaymentProfileRequest( ) createCustomerPaymentProfile.merchantAuthentication = merchantAuth createCustomerPaymentProfile.paymentProfile = profile customerProfileId = customerInfo[ "customerId"] # grab the same info from the dictionary but place it in their variable print( "customerProfileId in createCustomerPaymentProfile. customerProfileId = %s" % customerProfileId) createCustomerPaymentProfile.customerProfileId = str(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) return response.customerPaymentProfileId
def create_customer_payment_profile(customerProfileId): merchantAuth = apicontractsv1.merchantAuthenticationType() merchantAuth.name = constants.apiLoginId merchantAuth.transactionKey = constants.transactionKey creditCard = apicontractsv1.creditCardType() creditCard.cardNumber = "4111111111111111" creditCard.expirationDate = "2035-12" payment = apicontractsv1.paymentType() payment.creditCard = creditCard billTo = apicontractsv1.customerAddressType() billTo.firstName = "John" billTo.lastName = "Snow" profile = apicontractsv1.customerPaymentProfileType() profile.payment = payment profile.billTo = billTo createCustomerPaymentProfile = apicontractsv1.createCustomerPaymentProfileRequest( ) createCustomerPaymentProfile.merchantAuthentication = merchantAuth createCustomerPaymentProfile.paymentProfile = profile print( "customerProfileId in create_customer_payment_profile. customerProfileId = %s" % customerProfileId) createCustomerPaymentProfile.customerProfileId = str(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) return response
def update_customer_payment_profile(customerProfileId, customerPaymentProfileId): 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 paymentProfile = apicontractsv1.customerPaymentProfileExType() paymentProfile.billTo = apicontractsv1.customerAddressType() paymentProfile.billTo.firstName = "John" paymentProfile.billTo.lastName = "Doe" paymentProfile.billTo.address = "123 Main St." paymentProfile.billTo.city = "Bellevue" paymentProfile.billTo.state = "WA" paymentProfile.billTo.zip = "98004" paymentProfile.billTo.country = "USA" paymentProfile.billTo.phoneNumber = "000-000-000" paymentProfile.payment = payment paymentProfile.customerPaymentProfileId = customerPaymentProfileId updateCustomerPaymentProfile = apicontractsv1.updateCustomerPaymentProfileRequest() updateCustomerPaymentProfile.merchantAuthentication = merchantAuth updateCustomerPaymentProfile.paymentProfile = paymentProfile updateCustomerPaymentProfile.customerProfileId = customerProfileId updateCustomerPaymentProfile.validationMode = apicontractsv1.validationModeEnum.liveMode controller = updateCustomerPaymentProfileController(updateCustomerPaymentProfile) controller.execute() response = controller.getresponse() if (response.messages.resultCode=="Ok"): print ("Successfully updated customer payment profile with id %s" % updateCustomerPaymentProfile.paymentProfile.customerPaymentProfileId) else: print (response.messages.message[0]['text'].text) print ("Failed to update customer with customer payment profile id %s" % updateCustomerPaymentProfile.paymentProfile.customerPaymentProfileId) return response
def _create_bill_to(self, customer): """ Create a Bill To element that can be applied to an Authorize.net Transaction Request. :param customer: A silver customer. :returns apicontractsv1.customerAddressType instance: """ billTo = apicontractsv1.customerAddressType() billTo.firstName = customer.first_name billTo.lastName = customer.last_name billTo.company = customer.company billTo.address = customer.address_1 billTo.city = customer.city billTo.state = customer.state billTo.zip = customer.zip_code billTo.country = customer.country return billTo
def create_saved_payment(self, credit_card, address=None, profile_id=None): """ Creates a payment profile. """ creditCard = apicontractsv1.creditCardType() creditCard.cardNumber = credit_card.card_number creditCard.expirationDate = '{0.exp_year}-{0.exp_month:0>2}'.format(credit_card) creditCard.cardCode = credit_card.cvv payment = apicontractsv1.paymentType() payment.creditCard = creditCard billTo = apicontractsv1.customerAddressType() if credit_card.first_name: billTo.firstName = credit_card.first_name if credit_card.last_name: billTo.lastName = credit_card.last_name profile = apicontractsv1.customerPaymentProfileType() profile.payment = payment profile.billTo = billTo self._address_to_profile(address, profile) if profile_id: createCustomerPaymentProfile = apicontractsv1.createCustomerPaymentProfileRequest() createCustomerPaymentProfile.merchantAuthentication = self.merchantAuth createCustomerPaymentProfile.paymentProfile = profile createCustomerPaymentProfile.customerProfileId = str(profile_id) controller = createCustomerPaymentProfileController(createCustomerPaymentProfile) if not self.debug: controller.setenvironment(constants.PRODUCTION) controller.execute() response = controller.getresponse() if response.messages.resultCode == "Ok": return response.customerPaymentProfileId else: raise AuthorizeResponseError( "Failed to create customer payment profile %s" % response.messages.message[0]['text'].text) else: return profile
def create_customer_shipping_address(customerProfileId): # Give merchant details merchantAuth = apicontractsv1.merchantAuthenticationType() merchantAuth.name = constants.apiLoginId merchantAuth.transactionKey = constants.transactionKey # Give address details officeAddress = apicontractsv1.customerAddressType() officeAddress.firstName = "John" officeAddress.lastName = "Doe" officeAddress.address = "123 Main St." officeAddress.city = "Bellevue" officeAddress.state = "WA" officeAddress.zip = "98004" officeAddress.country = "USA" officeAddress.phoneNumber = "000-000-0000" # Create shipping address request shippingAddressRequest = apicontractsv1.createCustomerShippingAddressRequest( ) shippingAddressRequest.address = officeAddress shippingAddressRequest.customerProfileId = customerProfileId shippingAddressRequest.merchantAuthentication = merchantAuth # Make an API call controller = createCustomerShippingAddressController( shippingAddressRequest) controller.execute() response = controller.getresponse() if response.messages.resultCode == "Ok": print("SUCCESS") print("Transaction ID : %s " % response.messages.message[0]['text'].text) print("Customer address id : %s" % response.customerAddressId) 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 testCreateAndGetCustomerShippingAddress(self): officeAddress = apicontractsv1.customerAddressType() officeAddress.firstName = "John" officeAddress.lastName = "Doe" officeAddress.address = "123 Main St." officeAddress.city = "Bellevue" officeAddress.state = "WA" officeAddress.zip = "98004" officeAddress.country = "USA" officeAddress.phoneNumber = "000-000-0000" shippingAddressRequest = apicontractsv1.createCustomerShippingAddressRequest( ) shippingAddressRequest.address = officeAddress CustomerProfileID = self.testCreateCustomerProfile() shippingAddressRequest.customerProfileId = CustomerProfileID shippingAddressRequest.merchantAuthentication = self.merchantAuthentication controller = createCustomerShippingAddressController( shippingAddressRequest) controller.execute() response = controller.getresponse() if hasattr(response, 'messages') == True: if hasattr(response.messages, 'resultCode') == True: self.assertEquals('Ok', response.messages.resultCode) if hasattr(response, 'customerAddressId') == True: createdShippingAddressId = str(response.customerAddressId) #return str(createdShippingAddressId) #def testGetCustomerShippingAddress(self): getShippingAddress = apicontractsv1.getCustomerShippingAddressRequest() getShippingAddress.merchantAuthentication = self.merchantAuthentication getShippingAddress.customerProfileId = CustomerProfileID getShippingAddress.customerAddressId = createdShippingAddressId getShippingAddressController = getCustomerShippingAddressController( getShippingAddress) getShippingAddressController.execute() response = getShippingAddressController.getresponse() if hasattr(response, 'messages') == True: if hasattr(response.messages, 'resultCode') == True: self.assertEquals('Ok', response.messages.resultCode)
def create_billing_address(self): """ Creates Billing address to improve security in transaction """ billing_address = apicontractsv1.customerAddressType() billing_address.firstName = " ".join( self.payment_info.data.get('full_name', "").split(" ")[:-1])[:50] billing_address.lastName = (self.payment_info.data.get( 'full_name', "").split(" ")[-1])[:50] billing_address.company = self.billing_address.data.get('company', "")[:50] billing_address.address = ", ".join([ self.billing_address.data.get('address_1', ""), str(self.billing_address.data.get('address_2', "")) ])[:60] billing_address.city = self.billing_address.data.get("city", "")[:40] billing_address.state = self.billing_address.data.get("state", "")[:40] billing_address.zip = self.billing_address.data.get("postal_code")[:20] country = Country(int(self.billing_address.data.get("country"))) billing_address.country = str(country.name) return billing_address
def testCreateAndGetCustomerShippingAddress(self): officeAddress = apicontractsv1.customerAddressType(); officeAddress.firstName = "John" officeAddress.lastName = "Doe" officeAddress.address = "123 Main St." officeAddress.city = "Bellevue" officeAddress.state = "WA" officeAddress.zip = "98004" officeAddress.country = "USA" officeAddress.phoneNumber = "000-000-0000" shippingAddressRequest = apicontractsv1.createCustomerShippingAddressRequest() shippingAddressRequest.address = officeAddress CustomerProfileID = self.testCreateCustomerProfile() shippingAddressRequest.customerProfileId = CustomerProfileID shippingAddressRequest.merchantAuthentication = self.merchantAuthentication controller = createCustomerShippingAddressController(shippingAddressRequest) controller.execute() response = controller.getresponse() if hasattr(response, 'messages') == True: if hasattr(response.messages, 'resultCode') == True: self.assertEquals('Ok', response.messages.resultCode) if hasattr(response, 'customerAddressId') == True: createdShippingAddressId = str(response.customerAddressId) #return str(createdShippingAddressId) #def testGetCustomerShippingAddress(self): getShippingAddress = apicontractsv1.getCustomerShippingAddressRequest() getShippingAddress.merchantAuthentication = self.merchantAuthentication getShippingAddress.customerProfileId = CustomerProfileID getShippingAddress.customerAddressId = createdShippingAddressId getShippingAddressController = getCustomerShippingAddressController(getShippingAddress) getShippingAddressController.execute() response = getShippingAddressController.getresponse() if hasattr(response, 'messages') == True: if hasattr(response.messages, 'resultCode') == True: self.assertEquals('Ok', response.messages.resultCode)
def create_customer_shipping_address(customerProfileId): # Give merchant details merchantAuth = apicontractsv1.merchantAuthenticationType() merchantAuth.name = constants.apiLoginId merchantAuth.transactionKey = constants.transactionKey # Give address details officeAddress = apicontractsv1.customerAddressType(); officeAddress.firstName = "John" officeAddress.lastName = "Doe" officeAddress.address = "123 Main St." officeAddress.city = "Bellevue" officeAddress.state = "WA" officeAddress.zip = "98004" officeAddress.country = "USA" officeAddress.phoneNumber = "000-000-0000" # Create shipping address request shippingAddressRequest = apicontractsv1.createCustomerShippingAddressRequest(); shippingAddressRequest.address = officeAddress shippingAddressRequest.customerProfileId = customerProfileId shippingAddressRequest.merchantAuthentication = merchantAuth # Make an API call controller = createCustomerShippingAddressController(shippingAddressRequest) controller.execute() response = controller.getresponse(); if response.messages.resultCode == "Ok": print "SUCCESS" print "Transaction ID : %s " % response.messages.message[0]['text'].text print "Customer address id : %s" % response.customerAddressId 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 create_customer_payment_profile(customerProfileId): 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 billTo = apicontractsv1.customerAddressType() billTo.firstName = "John" billTo.lastName = "Snow" profile = apicontractsv1.customerPaymentProfileType() profile.payment = payment profile.billTo = billTo createCustomerPaymentProfile = apicontractsv1.createCustomerPaymentProfileRequest() createCustomerPaymentProfile.merchantAuthentication = merchantAuth createCustomerPaymentProfile.paymentProfile = profile print("customerProfileId in create_customer_payment_profile. customerProfileId = %s" %customerProfileId) createCustomerPaymentProfile.customerProfileId = str(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) return response
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
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
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("cardyear", None) + '-' + request.POST.get("cardmonth", None)) 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
# Gives error if an address is already present for the given customer Id from authorizenet import apicontractsv1 from authorizenet.apicontrollers import * # Give merchant details merchantAuth = apicontractsv1.merchantAuthenticationType() merchantAuth.name = '5KP3u95bQpv' merchantAuth.transactionKey = '4Ktq966gC55GAX7S' # Give address details officeAddress = apicontractsv1.customerAddressType(); officeAddress.firstName = "John" officeAddress.lastName = "Doe" officeAddress.address = "123 Main St." officeAddress.city = "Bellevue" officeAddress.state = "WA" officeAddress.zip = "98004" officeAddress.country = "USA" officeAddress.phoneNumber = "000-000-0000" # Create shipping address request shippingAddressRequest = apicontractsv1.createCustomerShippingAddressRequest(); shippingAddressRequest.address = officeAddress shippingAddressRequest.customerProfileId = "36152165" shippingAddressRequest.merchantAuthentication = merchantAuth # Make an API call createCustomerShippingAddressController= createCustomerShippingAddressController(shippingAddressRequest) createCustomerShippingAddressController.execute() response = createCustomerShippingAddressController.getresponse();
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
def createTransactionRequest( cart, refId, opaque_data, contact_info, transactionType='authCaptureTransaction'): # Get Authorize.net API credentials merchantAuth = _getMerchantAuth() # Get payment info payment = _getPayment(opaque_data) # Create order information order = apicontractsv1.orderType() order.description = refId # Set the customer's Bill To address customerAddress = apicontractsv1.customerAddressType() customerAddress.firstName = contact_info.get( 'first_name', contact_info.get('name_on_card', '')) customerAddress.lastName = contact_info.get('last_name', '') customerAddress.address = contact_info['address'] customerAddress.city = contact_info['city'] customerAddress.state = contact_info['state'] customerAddress.zip = contact_info['zip'] customerAddress.country = contact_info['country'] customerAddress.phoneNumber = contact_info['phone'] # Set the customer's identifying information customerData = apicontractsv1.customerDataType() customerData.type = "individual" customerData.email = contact_info['email'] # @@@ shipping # Add values for transaction settings duplicateWindowSetting = apicontractsv1.settingType() duplicateWindowSetting.settingName = "duplicateWindow" duplicateWindowSetting.settingValue = "600" settings = apicontractsv1.ArrayOfSetting() settings.setting.append(duplicateWindowSetting) # Create a transactionRequestType object and add the previous objects to it transactionrequest = apicontractsv1.transactionRequestType() transactionrequest.transactionType = transactionType transactionrequest.amount = str(cart.amount) transactionrequest.order = order transactionrequest.payment = payment transactionrequest.billTo = customerAddress transactionrequest.customer = customerData transactionrequest.transactionSettings = settings transactionrequest.lineItems = _getLineItems(cart) # Assemble the complete transaction request createtransactionrequest = apicontractsv1.createTransactionRequest() createtransactionrequest.merchantAuthentication = merchantAuth createtransactionrequest.transactionRequest = transactionrequest # Create the controller and get response createtransactioncontroller = createTransactionController( createtransactionrequest) if config.IN_PRODUCTION: createtransactioncontroller.setenvironment(constants.PRODUCTION) createtransactioncontroller.execute() response = createtransactioncontroller.getresponse() if response.messages.resultCode == 'Ok': if response.transactionResponse.responseCode != 1: # Approved raise PaymentProcessingException( 'Your card could not be processed.') return response else: raise PaymentProcessingException(response.messages.message[0].text)
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 charge_credit_card(): #try: # Create a merchantAuthenticationType object with authentication details # retrieved from the constants file merchantAuth = apicontractsv1.merchantAuthenticationType() merchantAuth.name = CONSTANTS.apiLoginId merchantAuth.transactionKey = CONSTANTS.transactionKey # Create the payment data for a credit card creditCard = apicontractsv1.creditCardType() creditCard.cardNumber = "4111111111111111" creditCard.expirationDate = "2020-12" creditCard.cardCode = cardCode # Add the payment data to a paymentType object payment = apicontractsv1.paymentType() payment.creditCard = creditCard # Create order information order = apicontractsv1.orderType() order.invoiceNumber = "110011" order.description = "Lost a Bet" # Set the customer's Bill To address fullname1 = f.get('/Users/' + loser, 'name') customerAddress = apicontractsv1.customerAddressType() customerAddress.firstName = "John" customerAddress.lastName = "Doe" customerAddress.company = "Souveniropolis" customerAddress.address1 = "14 Main Street" customerAddress.city1 = "Pecan Springs" customerAddress.state1 = "TX" customerAddress.zip1 = "44628" customerAddress.country1 = "USA" # Add values for transaction settings duplicateWindowSetting = apicontractsv1.settingType() duplicateWindowSetting.settingName = "duplicateWindow" duplicateWindowSetting.settingValue = "600" settings = apicontractsv1.ArrayOfSetting() settings.setting.append(duplicateWindowSetting) customerData = apicontractsv1.customerDataType() customerData.type = "individual" customerData.id = "99999456657" customerData.email = "*****@*****.**" # Create a transactionRequestType object and add the previous objects to it. #charged transactionrequest = apicontractsv1.transactionRequestType() transactionrequest.transactionType = "authCaptureTransaction" transactionrequest.amount = amount transactionrequest.payment = payment transactionrequest.order = order transactionrequest.billTo = customerAddress transactionrequest.customer = customerData transactionrequest.transactionSettings = settings # Assemble the complete transaction request createtransactionrequest = apicontractsv1.createTransactionRequest() createtransactionrequest.merchantAuthentication = merchantAuth #createtransactionrequest.refId = "MerchantID-0001" createtransactionrequest.transactionRequest = transactionrequest # Create the controller createtransactioncontroller = createTransactionController( createtransactionrequest) createtransactioncontroller.execute() response = createtransactioncontroller.getresponse() if response is not None: # Check to see if the API request was successfully received and acted upon if response.messages.resultCode == "Ok": # Since the API request was successful, look for a transaction response # and parse it to display the results of authorizing the card if hasattr(response.transactionResponse, 'messages') is True: print( 'Successfully created transaction with Transaction ID: %s' % response.transactionResponse.transId) print('Transaction Response Code: %s' % response.transactionResponse.responseCode) print('Message Code: %s' % response.transactionResponse.messages.message[0].code) print('Description: %s' % response.transactionResponse. messages.message[0].description) else: print('Failed Transaction.') if hasattr(response.transactionResponse, 'errors') is True: print('Error Code: %s' % str(response.transactionResponse. errors.error[0].errorCode)) print( 'Error message: %s' % response.transactionResponse.errors.error[0].errorText) # Or, print errors if the API request wasn't successful else: print('Failed Transaction.') if hasattr(response, 'transactionResponse') is True and hasattr( response.transactionResponse, 'errors') is True: print('Error Code: %s' % str( response.transactionResponse.errors.error[0].errorCode)) print('Error message: %s' % response.transactionResponse.errors.error[0].errorText) else: print('Error Code: %s' % response.messages.message[0]['code'].text) print('Error message: %s' % response.messages.message[0]['text'].text) else: print('Null Response.') return response
def authnet_charge(request): # data refs data = request.data card = request.card reference_doc = request.reference_doc # Create the payment data for a credit card credit_card = apicontractsv1.creditCardType() credit_card.cardNumber = request.card.number credit_card.expirationDate = request.card.expiration_date credit_card.cardCode = request.card.code # Add the payment data to a paymentType object payment = apicontractsv1.paymentType() payment.creditCard = credit_card # determin company name to attach to customer address record customer_name = None if reference_doc.doctype == "Quotation" and frappe.db.exists("Customer", reference_doc.party_name): # sanity test, only fetch customer record from party_name customer_name = reference_doc.party_name else: customer_name = reference_doc.customer name_parts = card.holder_name.split(None, 1) customer_address = apicontractsv1.customerAddressType() customer_address.firstName = name_parts[0] or data.payer_name customer_address.lastName = name_parts[1] if len(name_parts) > 1 else "" customer_address.email = card.holder_email or data.payer_email # setting billing address details if frappe.db.exists("Address", reference_doc.customer_address): address = frappe.get_doc("Address", reference_doc.customer_address) customer_address.address = (address.address_line1 or "")[:60] customer_address.city = (address.city or "")[:40] customer_address.state = (address.state or "")[:40] customer_address.zip = (address.pincode or "")[:20] customer_address.country = (address.country or "")[:60] # record company name when not an individual customer_type = frappe.db.get_value("Customer", customer_name, "customer_type") if customer_type != "Individual": customer_address.company = reference_doc.customer_name # Create order information order = apicontractsv1.orderType() order.invoiceNumber = reference_doc.name # build the array of line items line_items = apicontractsv1.ArrayOfLineItem() for item in reference_doc.get("items"): # setup individual line items line_item = apicontractsv1.lineItemType() line_item.itemId = item.item_code line_item.name = item.item_name[:30] line_item.description = item.item_name line_item.quantity = item.qty line_item.unitPrice = cstr(item.rate) line_items.lineItem.append(line_item) # Adjust duplicate window to avoid duplicate window issues on declines duplicateWindowSetting = apicontractsv1.settingType() duplicateWindowSetting.settingName = "duplicateWindow" # seconds before an identical transaction can be submitted duplicateWindowSetting.settingValue = "10" settings = apicontractsv1.ArrayOfSetting() settings.setting.append(duplicateWindowSetting) # Create a transactionRequestType object and add the previous objects to it. transaction_request = apicontractsv1.transactionRequestType() transaction_request.transactionType = "authCaptureTransaction" transaction_request.amount = data.amount transaction_request.payment = payment transaction_request.order = order transaction_request.billTo = customer_address transaction_request.lineItems = line_items transaction_request.transactionSettings = settings # Assemble the complete transaction request create_transaction_request = apicontractsv1.createTransactionRequest() create_transaction_request.merchantAuthentication = request.merchant_auth create_transaction_request.transactionRequest = transaction_request create_transaction_request.refId = reference_doc.name # Create the controller createtransactioncontroller = createTransactionController(create_transaction_request) if not frappe.db.get_single_value("Authorizenet Settings", "sandbox_mode"): createtransactioncontroller.setenvironment(constants.PRODUCTION) createtransactioncontroller.execute() return createtransactioncontroller.getresponse()
c.execute(sql2) row2 = c.fetchone() customer_profile_id = row2[0] conn.commit() merchantAuth = apicontractsv1.merchantAuthenticationType() merchantAuth.name = constants.apiLoginId merchantAuth.transactionKey = constants.transactionKey creditCard = apicontractsv1.creditCardType() creditCard.cardNumber = cardnumber creditCard.expirationDate = expirationDate payment = apicontractsv1.paymentType() payment.creditCard = creditCard billTo = apicontractsv1.customerAddressType() billTo.firstName = name profile = apicontractsv1.customerPaymentProfileType() profile.payment = payment profile.billTo = billTo createCustomerPaymentProfile = apicontractsv1.createCustomerPaymentProfileRequest() createCustomerPaymentProfile.merchantAuthentication = merchantAuth createCustomerPaymentProfile.paymentProfile = profile createCustomerPaymentProfile.customerProfileId = str(customer_profile_id) controller = createCustomerPaymentProfileController(createCustomerPaymentProfile) controller.execute()
def charge_credit_card(data, card_number, expiration_date, card_code): """ Charge a credit card """ data = json.loads(data) data = frappe._dict(data) # Create Integration Request integration_request = create_request_log(data, "Host", "Authorizenet") # Authenticate with Authorizenet merchant_auth = apicontractsv1.merchantAuthenticationType() merchant_auth.name = frappe.db.get_single_value("Authorizenet Settings", "api_login_id") merchant_auth.transactionKey = get_decrypted_password( 'Authorizenet Settings', 'Authorizenet Settings', fieldname='api_transaction_key', raise_exception=False) # Create the payment data for a credit card credit_card = apicontractsv1.creditCardType() credit_card.cardNumber = card_number credit_card.expirationDate = expiration_date credit_card.cardCode = card_code # Add the payment data to a paymentType object payment = apicontractsv1.paymentType() payment.creditCard = credit_card pr = frappe.get_doc(data.reference_doctype, data.reference_docname) reference_doc = frappe.get_doc(pr.reference_doctype, pr.reference_name).as_dict() customer_address = apicontractsv1.customerAddressType() customer_address.firstName = data.payer_name customer_address.email = data.payer_email customer_address.address = reference_doc.customer_address[:60] # Create order information order = apicontractsv1.orderType() order.invoiceNumber = reference_doc.name # build the array of line items line_items = apicontractsv1.ArrayOfLineItem() for item in reference_doc.get("items"): # setup individual line items line_item = apicontractsv1.lineItemType() line_item.itemId = item.item_code line_item.name = item.item_name[:30] line_item.description = item.item_name line_item.quantity = item.qty line_item.unitPrice = cstr(item.rate) line_items.lineItem.append(line_item) # Create a transactionRequestType object and add the previous objects to it. transaction_request = apicontractsv1.transactionRequestType() transaction_request.transactionType = "authCaptureTransaction" transaction_request.amount = data.amount transaction_request.payment = payment transaction_request.order = order transaction_request.billTo = customer_address transaction_request.lineItems = line_items # Assemble the complete transaction request create_transaction_request = apicontractsv1.createTransactionRequest() create_transaction_request.merchantAuthentication = merchant_auth create_transaction_request.transactionRequest = transaction_request # Create the controller createtransactioncontroller = createTransactionController( create_transaction_request) if not frappe.db.get_single_value("Authorizenet Settings", "sandbox_mode"): createtransactioncontroller.setenvironment(constants.PRODUCTION) createtransactioncontroller.execute() response = createtransactioncontroller.getresponse() status = "Failed" if response is not None: # Check to see if the API request was successfully received and acted upon if response.messages.resultCode == "Ok" and hasattr( response.transactionResponse, 'messages') is True: status = "Completed" if status != "Failed": try: pr.run_method("on_payment_authorized", status) except Exception as ex: raise ex response_dict = to_dict(response) integration_request.update_status(data, status) description = "Something went wrong while trying to complete the transaction. Please try again." if status == "Completed": description = response_dict.get("transactionResponse").get( "messages").get("message").get("description") elif status == "Failed": description = error_text = response_dict.get( "transactionResponse").get("errors").get("error").get("errorText") integration_request.error = error_text integration_request.save(ignore_permissions=True) return frappe._dict({"status": status, "description": description})
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" }
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')
def createTransactionRequest(cart, refId, opaque_data, contact_info, transactionType='authCaptureTransaction'): # Get Authorize.net API credentials merchantAuth = _getMerchantAuth() # Get payment info payment = _getPayment(opaque_data) # Create order information order = apicontractsv1.orderType() order.description = refId # Set the customer's Bill To address customerAddress = apicontractsv1.customerAddressType() customerAddress.firstName = contact_info.get( 'first_name', contact_info.get('name_on_card', '')) customerAddress.lastName = contact_info.get('last_name', '') customerAddress.address = contact_info['address'] customerAddress.city = contact_info['city'] customerAddress.state = contact_info['state'] customerAddress.zip = contact_info['zip'] customerAddress.country = contact_info['country'] customerAddress.phoneNumber = contact_info['phone'] # Set the customer's identifying information customerData = apicontractsv1.customerDataType() customerData.type = "individual" customerData.email = contact_info['email'] # @@@ shipping # Add values for transaction settings duplicateWindowSetting = apicontractsv1.settingType() duplicateWindowSetting.settingName = "duplicateWindow" duplicateWindowSetting.settingValue = "600" settings = apicontractsv1.ArrayOfSetting() settings.setting.append(duplicateWindowSetting) # Create a transactionRequestType object and add the previous objects to it transactionrequest = apicontractsv1.transactionRequestType() transactionrequest.transactionType = transactionType transactionrequest.amount = six.text_type(cart.amount) transactionrequest.order = order transactionrequest.payment = payment transactionrequest.billTo = customerAddress transactionrequest.customer = customerData transactionrequest.transactionSettings = settings transactionrequest.lineItems = _getLineItems(cart) # Assemble the complete transaction request createtransactionrequest = apicontractsv1.createTransactionRequest() createtransactionrequest.merchantAuthentication = merchantAuth createtransactionrequest.transactionRequest = transactionrequest with enhanced_authnet_logging(): controller = createTransactionController(createtransactionrequest) if config.IN_PRODUCTION: controller.setenvironment(constants.PRODUCTION) controller.execute() response = controller.getresponse() logger.info('createTransactionController response: {}'.format( response.__repr__())) defaultMsg = 'Your card could not be processed.' if controller._httpResponse: logger.info('Authorize.net response: {}'.format( controller._httpResponse)) if response.messages.resultCode == 'Ok': if response.transactionResponse.responseCode != 1: # Approved raise PaymentProcessingException(defaultMsg) return response else: raise PaymentProcessingException(response.messages.message[0].text or defaultMsg)
# Gives error if an address is already present for the given customer Id from authorizenet import apicontractsv1 from authorizenet.apicontrollers import * # Give merchant details merchantAuth = apicontractsv1.merchantAuthenticationType() merchantAuth.name = '5KP3u95bQpv' merchantAuth.transactionKey = '4Ktq966gC55GAX7S' # Give address details officeAddress = apicontractsv1.customerAddressType() officeAddress.firstName = "John" officeAddress.lastName = "Doe" officeAddress.address = "123 Main St." officeAddress.city = "Bellevue" officeAddress.state = "WA" officeAddress.zip = "98004" officeAddress.country = "USA" officeAddress.phoneNumber = "000-000-0000" # Create shipping address request shippingAddressRequest = apicontractsv1.createCustomerShippingAddressRequest() shippingAddressRequest.address = officeAddress shippingAddressRequest.customerProfileId = "36152165" shippingAddressRequest.merchantAuthentication = merchantAuth # Make an API call createCustomerShippingAddressController = createCustomerShippingAddressController( shippingAddressRequest) createCustomerShippingAddressController.execute() response = createCustomerShippingAddressController.getresponse()
def create_an_accept_payment_transaction(amount): # Create a merchantAuthenticationType object with authentication details # retrieved from the constants file merchantAuth = apicontractsv1.merchantAuthenticationType() merchantAuth.name = constants.apiLoginId merchantAuth.transactionKey = constants.transactionKey # Set the transaction's refId refId = "ref {}".format(time.time()) # Create the payment object for a payment nonce opaqueData = apicontractsv1.opaqueDataType() opaqueData.dataDescriptor = "COMMON.ACCEPT.INAPP.PAYMENT" opaqueData.dataValue = "119eyJjb2RlIjoiNTBfMl8wNjAwMDUyN0JEODE4RjQxOUEyRjhGQkIxMkY0MzdGQjAxQUIwRTY2NjhFNEFCN0VENzE4NTUwMjlGRUU0M0JFMENERUIwQzM2M0ExOUEwMDAzNzlGRDNFMjBCODJEMDFCQjkyNEJDIiwidG9rZW4iOiI5NDkwMjMyMTAyOTQwOTk5NDA0NjAzIiwidiI6IjEuMSJ9" # Add the payment data to a paymentType object paymentOne = apicontractsv1.paymentType() paymentOne.opaqueData = opaqueData # Create order information order = apicontractsv1.orderType() order.invoiceNumber = "10101" order.description = "Golf Shirts" # Set the customer's Bill To address customerAddress = apicontractsv1.customerAddressType() customerAddress.firstName = "Ellen" customerAddress.lastName = "Johnson" customerAddress.company = "Souveniropolis" customerAddress.address = "14 Main Street" customerAddress.city = "Pecan Springs" customerAddress.state = "TX" customerAddress.zip = "44628" customerAddress.country = "USA" # Set the customer's identifying information customerData = apicontractsv1.customerDataType() customerData.type = "individual" customerData.id = "99999456654" customerData.email = "*****@*****.**" # Add values for transaction settings duplicateWindowSetting = apicontractsv1.settingType() duplicateWindowSetting.settingName = "duplicateWindow" duplicateWindowSetting.settingValue = "600" settings = apicontractsv1.ArrayOfSetting() settings.setting.append(duplicateWindowSetting) # Create a transactionRequestType object and add the previous objects to it transactionrequest = apicontractsv1.transactionRequestType() transactionrequest.transactionType = "authCaptureTransaction" transactionrequest.amount = amount transactionrequest.order = order transactionrequest.payment = paymentOne transactionrequest.billTo = customerAddress transactionrequest.customer = customerData transactionrequest.transactionSettings = settings # Assemble the complete transaction request createtransactionrequest = apicontractsv1.createTransactionRequest() createtransactionrequest.merchantAuthentication = merchantAuth createtransactionrequest.refId = refId createtransactionrequest.transactionRequest = transactionrequest # Create the controller and get response createtransactioncontroller = createTransactionController( createtransactionrequest) createtransactioncontroller.execute() response = createtransactioncontroller.getresponse() if response is not None: # Check to see if the API request was successfully received and acted upon if response.messages.resultCode == "Ok": # Since the API request was successful, look for a transaction response # and parse it to display the results of authorizing the card if hasattr(response.transactionResponse, 'messages') == True: print( 'Successfully created transaction with Transaction ID: %s' % response.transactionResponse.transId) print('Transaction Response Code: %s' % response.transactionResponse.responseCode) print('Message Code: %s' % response.transactionResponse.messages.message[0].code) print('Auth Code: %s' % response.transactionResponse.authCode) print('Description: %s' % response.transactionResponse. messages.message[0].description) else: print('Failed Transaction.') if hasattr(response.transactionResponse, 'errors') == True: print('Error Code: %s' % str(response.transactionResponse. errors.error[0].errorCode)) print( 'Error Message: %s' % response.transactionResponse.errors.error[0].errorText) # Or, print errors if the API request wasn't successful else: print('Failed Transaction.') if hasattr(response, 'transactionResponse') == True and hasattr( response.transactionResponse, 'errors') == True: print('Error Code: %s' % str( response.transactionResponse.errors.error[0].errorCode)) print('Error Message: %s' % response.transactionResponse.errors.error[0].errorText) else: print('Error Code: %s' % response.messages.message[0]['code'].text) print('Error Message: %s' % response.messages.message[0]['text'].text) else: print('Null Response.') return response
def authorize( payment_information: PaymentData, config: GatewayConfig, user_id: Optional[int] = None, ) -> GatewayResponse: """Based on AcceptSuite create-an-accept-payment-transaction example. https://github.com/AuthorizeNet/sample-code-python/blob/master/AcceptSuite/create-an-accept-payment-transaction.py """ kind = TransactionKind.CAPTURE if config.auto_capture else TransactionKind.AUTH merchant_auth = _get_merchant_auth(config.connection_params) # The Saleor token is the authorize.net "opaque data" opaque_data = apicontractsv1.opaqueDataType() opaque_data.dataDescriptor = "COMMON.ACCEPT.INAPP.PAYMENT" opaque_data.dataValue = payment_information.token payment_one = apicontractsv1.paymentType() payment_one.opaqueData = opaque_data order = apicontractsv1.orderType() order.invoiceNumber = payment_information.order_id order.description = payment_information.graphql_payment_id # An auth.net "profile" id is the id generated by auth.net. # It is not the Saleor user id. customer_id = (payment_information.customer_id if payment_information.reuse_source else None) customer_data = apicontractsv1.customerDataType() customer_data.type = "individual" if user_id: customer_data.id = str(user_id) customer_data.email = payment_information.customer_email transaction_request = apicontractsv1.transactionRequestType() transaction_request.transactionType = ("authCaptureTransaction" if config.auto_capture else "authOnlyTransaction") transaction_request.amount = payment_information.amount transaction_request.currencyCode = payment_information.currency transaction_request.order = order transaction_request.payment = payment_one transaction_request.customer = customer_data if payment_information.reuse_source and customer_id is None: profile = apicontractsv1.customerProfilePaymentType() profile.createProfile = True transaction_request.profile = profile if payment_information.billing: customer_address = apicontractsv1.customerAddressType() customer_address.firstName = payment_information.billing.first_name customer_address.lastName = payment_information.billing.last_name customer_address.company = payment_information.billing.company_name # authorize.net support says we should not attempt submitting street_address_2 customer_address.address = payment_information.billing.street_address_1 customer_address.city = payment_information.billing.city customer_address.state = payment_information.billing.country_area customer_address.zip = payment_information.billing.postal_code customer_address.country = payment_information.billing.country transaction_request.billTo = customer_address create_transaction_request = apicontractsv1.createTransactionRequest() create_transaction_request.merchantAuthentication = merchant_auth create_transaction_request.refId = str(payment_information.payment_id) create_transaction_request.transactionRequest = transaction_request response = _make_request(create_transaction_request, config.connection_params) ( success, error, transaction_id, transaction_response, raw_response, ) = _handle_authorize_net_response(response) psp_reference = None if transaction_id: psp_reference = transaction_id elif payment_information.token: transaction_id = payment_information.token if hasattr(response, "profileResponse") and hasattr( response.profileResponse, "customerProfileId"): customer_id = response.profileResponse.customerProfileId payment_method_info = _authorize_net_account_to_payment_method_info( transaction_response) return GatewayResponse( is_success=success, action_required=False, transaction_id=transaction_id, amount=payment_information.amount, currency=payment_information.currency, error=error, payment_method_info=payment_method_info, kind=kind, raw_response=raw_response, customer_id=customer_id, psp_reference=str(psp_reference) if psp_reference else None, )
from authorizenet import apicontractsv1 from authorizenet.apicontrollers import * merchantAuth = apicontractsv1.merchantAuthenticationType() merchantAuth.name = '5KP3u95bQpv' merchantAuth.transactionKey = '4Ktq966gC55GAX7S' creditCard = apicontractsv1.creditCardType() creditCard.cardNumber = "4111111111111111" creditCard.expirationDate = "2020-12" payment = apicontractsv1.paymentType() payment.creditCard = creditCard paymentProfile = apicontractsv1.customerPaymentProfileExType() paymentProfile.billTo = apicontractsv1.customerAddressType() paymentProfile.billTo.firstName = "John" paymentProfile.billTo.lastName = "Doe" paymentProfile.billTo.address = "123 Main St." paymentProfile.billTo.city = "Bellevue" paymentProfile.billTo.state = "WA" paymentProfile.billTo.zip = "98004" paymentProfile.billTo.country = "USA" paymentProfile.billTo.phoneNumber = "000-000-000" paymentProfile.payment = payment paymentProfile.customerPaymentProfileId = "34823065" updateCustomerPaymentProfile = apicontractsv1.updateCustomerPaymentProfileRequest() updateCustomerPaymentProfile.merchantAuthentication = merchantAuth updateCustomerPaymentProfile.paymentProfile = paymentProfile updateCustomerPaymentProfile.customerProfileId = "36731856"
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
from authorizenet import apicontractsv1 from authorizenet.apicontrollers import * merchantAuth = apicontractsv1.merchantAuthenticationType() merchantAuth.name = '5KP3u95bQpv' merchantAuth.transactionKey = '4Ktq966gC55GAX7S' creditCard = apicontractsv1.creditCardType() creditCard.cardNumber = "4111111111111111" creditCard.expirationDate = "2020-12" payment = apicontractsv1.paymentType() payment.creditCard = creditCard paymentProfile = apicontractsv1.customerPaymentProfileExType() paymentProfile.billTo = apicontractsv1.customerAddressType() paymentProfile.billTo.firstName = "John" paymentProfile.billTo.lastName = "Doe" paymentProfile.billTo.address = "123 Main St." paymentProfile.billTo.city = "Bellevue" paymentProfile.billTo.state = "WA" paymentProfile.billTo.zip = "98004" paymentProfile.billTo.country = "USA" paymentProfile.billTo.phoneNumber = "000-000-000" paymentProfile.payment = payment paymentProfile.customerPaymentProfileId = "34823065" updateCustomerPaymentProfile = apicontractsv1.updateCustomerPaymentProfileRequest( ) updateCustomerPaymentProfile.merchantAuthentication = merchantAuth updateCustomerPaymentProfile.paymentProfile = paymentProfile