def get_authorizenet_payment_settings(self, basket): """ return AuthorizeNet_sdk Setting Instance containing required transaction settings to control the receipt page urls and buttons. Visit https://developer.authorize.net/api/reference/features/accept_hosted.html for more detail. """ course_id = basket.all_lines()[0].product.course_id course_id_hash = base64.b64encode(course_id.encode()) redirect_url = reverse('authorizenet:redirect') ecommerce_base_url = get_ecommerce_url() return_url = '{}{}?course={}'.format(ecommerce_base_url, redirect_url, course_id_hash) # Create Authorizenet Settings object payment_button_setting = apicontractsv1.settingType() payment_button_setting.settingName = apicontractsv1.settingNameEnum.hostedPaymentButtonOptions payment_button_setting.settingValue = json.dumps({'text': 'Pay'}) payment_return_setting = apicontractsv1.settingType() payment_return_setting.settingName = apicontractsv1.settingNameEnum.hostedPaymentReturnOptions payment_return_configrations = { 'url': return_url, 'urlText': 'Continue', 'cancelUrl': self.cancel_url, 'cancelUrlText': 'Cancel' } payment_return_setting.settingValue = json.dumps(payment_return_configrations) settings = apicontractsv1.ArrayOfSetting() settings.setting.append(payment_button_setting) settings.setting.append(payment_return_setting) return settings
def get_an_accept_payment_page(amount): merchantAuth = apicontractsv1.merchantAuthenticationType() merchantAuth.name = constants.apiLoginId merchantAuth.transactionKey = constants.transactionKey setting1 = apicontractsv1.settingType() setting1.settingName = apicontractsv1.settingNameEnum.hostedPaymentButtonOptions setting1.settingValue = "{\"text\": \"Pay\"}" setting2 = apicontractsv1.settingType() setting2.settingName = apicontractsv1.settingNameEnum.hostedPaymentOrderOptions setting2.settingValue = "{\"show\": false}" settings = apicontractsv1.ArrayOfSetting() settings.setting.append(setting1) settings.setting.append(setting2) transactionrequest = apicontractsv1.transactionRequestType() transactionrequest.transactionType = "authCaptureTransaction" transactionrequest.amount = amount paymentPageRequest = apicontractsv1.getHostedPaymentPageRequest() paymentPageRequest.merchantAuthentication = merchantAuth paymentPageRequest.transactionRequest = transactionrequest paymentPageRequest.hostedPaymentSettings = settings paymentPageController = getHostedPaymentPageController(paymentPageRequest) paymentPageController.execute() paymentPageResponse = paymentPageController.getresponse() if paymentPageResponse is not None: if paymentPageResponse.messages.resultCode == apicontractsv1.messageTypeEnum.Ok: print('Successfully got hosted payment page!') print('Token : %s' % paymentPageResponse.token) if paymentPageResponse.messages is not None: print('Message Code : %s' % paymentPageResponse.messages.message[0]['code'].text) print('Message Text : %s' % paymentPageResponse.messages.message[0]['text'].text) else: if paymentPageResponse.messages is not None: print('Failed to get batch statistics.\nCode:%s \nText:%s' % (paymentPageResponse.messages.message[0]['code'].text, paymentPageResponse.messages.message[0]['text'].text)) return paymentPageResponse
def __init__(self, settingName=None, settingValue=None): super(ArrayOfSetting, self).__init__() self.setting = apicontractsv1.settingType() if settingName: self.setting.settingName = settingName if settingValue: self.setting.settingValue = settingValue
def get_hosted_payment_page(amount): merchantAuth = apicontractsv1.merchantAuthenticationType() merchantAuth.name = constants.apiLoginId merchantAuth.transactionKey = constants.transactionKey setting1 = apicontractsv1.settingType() setting1.settingName = apicontractsv1.settingNameEnum.hostedPaymentButtonOptions setting1.settingValue = "{\"text\": \"Pay\"}" setting2 = apicontractsv1.settingType() setting2.settingName = apicontractsv1.settingNameEnum.hostedPaymentOrderOptions setting2.settingValue = "{\"show\": false}" settings = apicontractsv1.ArrayOfSetting() settings.setting.append(setting1) settings.setting.append(setting2) transactionrequest = apicontractsv1.transactionRequestType() transactionrequest.transactionType = "authCaptureTransaction" transactionrequest.amount = amount paymentPageRequest = apicontractsv1.getHostedPaymentPageRequest() paymentPageRequest.merchantAuthentication = merchantAuth paymentPageRequest.transactionRequest = transactionrequest paymentPageRequest.hostedProfileSettings = settings paymentPageController = getHostedPaymentPageController(paymentPageRequest) paymentPageController.execute() paymentPageResponse = paymentPageController.getresponse() if paymentPageResponse is not None: if paymentPageResponse.messages.resultCode == apicontractsv1.messageTypeEnum.Ok: print('Successfully got hosted payment page!') print('Token : %s' % paymentPageResponse.token) if paymentPageResponse.messages: print('Message Code : %s' % paymentPageResponse.messages.message[0]['code'].text) print('Message Text : %s' % paymentPageResponse.messages.message[0]['text'].text) else: if paymentPageResponse.messages: print('Failed to get batch statistics.\nCode:%s \nText:%s' % (paymentPageResponse.messages.message[0]['code'].text,paymentPageResponse.messages.message[0]['text'].text)) return paymentPageResponse
def _create_transaction_settings(self): """ Create transaction settings for an Authorize.net request. """ # Ensure that no duplicate transaction can be submitted for 600 # seconds. duplicateWindowSetting = apicontractsv1.settingType() duplicateWindowSetting.settingName = "duplicateWindow" duplicateWindowSetting.settingValue = "600" settings = apicontractsv1.ArrayOfSetting() settings.setting.append(duplicateWindowSetting) return settings
def get_hosted_profile_page(customerProfileId): merchantAuth = apicontractsv1.merchantAuthenticationType() merchantAuth.name = constants.apiLoginId merchantAuth.transactionKey = constants.transactionKey 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 = customerProfileId 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) if profilePageResponse.messages: print('Message Code : %s' % profilePageResponse.messages.message[0].code) print('Message Text : %s' % profilePageResponse.messages.message[0].text) else: if profilePageResponse.messages: print('Failed to get batch statistics.\nCode:%s \nText:%s' % (profilePageResponse.messages.message[0].code, profilePageResponse.messages.message[0].text)) return profilePageResponse
def get_accept_customer_profile_page(customerProfileId): merchantAuth = apicontractsv1.merchantAuthenticationType() merchantAuth.name = constants.apiLoginId merchantAuth.transactionKey = constants.transactionKey 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 = customerProfileId 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) if profilePageResponse.messages: print('Message Code : %s' % profilePageResponse.messages.message[0]['code'].text) print('Message Text : %s' % profilePageResponse.messages.message[0]['text'].text) else: if profilePageResponse.messages: print('Failed to get batch statistics.\nCode:%s \nText:%s' % (profilePageResponse.messages.message[0]['code'].text,profilePageResponse.messages.message[0]['text'].text)) return profilePageResponse
def get_accept_customer_profile_page(apiLoginId, apiTransactionKey, hostedProfileIFrameCommunicatorUrl,customerId): merchantAuth = apicontractsv1.merchantAuthenticationType() merchantAuth.name = apiLoginId merchantAuth.transactionKey = apiTransactionKey setting = apicontractsv1.settingType() setting.settingName = apicontractsv1.settingNameEnum.hostedProfileIFrameCommunicatorUrl setting.settingValue = hostedProfileIFrameCommunicatorUrl settings = apicontractsv1.ArrayOfSetting() settings.setting.append(setting) profilePageRequest = apicontractsv1.getHostedProfilePageRequest() profilePageRequest.merchantAuthentication = merchantAuth profilePageRequest.customerProfileId = customerId 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) if profilePageResponse.messages: print('Message Code : %s' % profilePageResponse.messages.message[0]['code'].text) print('Message Text : %s' % profilePageResponse.messages.message[0]['text'].text) else: if profilePageResponse.messages: print('Failed to get batch statistics.\nCode:%s \nText:%s' % (profilePageResponse.messages.message[0]['code'].text,profilePageResponse.messages.message[0]['text'].text)) return profilePageResponse
def get_an_accept_payment_page(apiLoginId, apiTransactionKey, hostedPaymentIFrameCommunicatorUrl,customerId= None): merchantAuth = apicontractsv1.merchantAuthenticationType() merchantAuth.name = apiLoginId merchantAuth.transactionKey = apiTransactionKey setting1 = apicontractsv1.settingType() setting1.settingName = apicontractsv1.settingNameEnum.hostedPaymentButtonOptions setting1.settingValue = "{\"text\": \"Pay\"}" setting2 = apicontractsv1.settingType() setting2.settingName = apicontractsv1.settingNameEnum.hostedPaymentOrderOptions setting2.settingValue = "{\"show\": false}" setting3 = apicontractsv1.settingType() setting3.settingName = apicontractsv1.settingNameEnum.hostedPaymentIFrameCommunicatorUrl setting3.settingValue = "{\"url\": \"" + hostedPaymentIFrameCommunicatorUrl + "\"}" setting4 = apicontractsv1.settingType() setting4.settingName = apicontractsv1.settingNameEnum.hostedPaymentBillingAddressOptions setting4.settingValue = "{\"show\": false}" setting5 = apicontractsv1.settingType() setting5.settingName = apicontractsv1.settingNameEnum.hostedPaymentReturnOptions setting5.settingValue = "{\"showReceipt\": false,\"url\":\"" + hostedPaymentIFrameCommunicatorUrl + "\",\"urlText\":\"Continue\",\"cancelUrlText\":\"Cancel\"}" settings = apicontractsv1.ArrayOfSetting() settings.setting.append(setting1) settings.setting.append(setting2) settings.setting.append(setting3) settings.setting.append(setting4) settings.setting.append(setting5) transactionrequest = apicontractsv1.transactionRequestType() transactionrequest.transactionType = "authCaptureTransaction" transactionrequest.amount = 99 if customerId is not None: if customerId != '': custprofile = apicontractsv1.customerProfilePaymentType() custprofile.customerProfileId = customerId transactionrequest.profile =custprofile paymentPageRequest = apicontractsv1.getHostedPaymentPageRequest() paymentPageRequest.merchantAuthentication = merchantAuth paymentPageRequest.transactionRequest = transactionrequest paymentPageRequest.hostedPaymentSettings = settings paymentPageController = getHostedPaymentPageController(paymentPageRequest) paymentPageController.execute() paymentPageResponse = paymentPageController.getresponse() if paymentPageResponse is not None: if paymentPageResponse.messages.resultCode == apicontractsv1.messageTypeEnum.Ok: print('Successfully got hosted payment page!') print('Token : %s' % paymentPageResponse.token) if paymentPageResponse.messages is not None: print('Message Code : %s' % paymentPageResponse.messages.message[0]['code'].text) print('Message Text : %s' % paymentPageResponse.messages.message[0]['text'].text) else: if paymentPageResponse.messages is not None: print('Failed to get batch statistics.\nCode:%s \nText:%s' % (paymentPageResponse.messages.message[0]['code'].text,paymentPageResponse.messages.message[0]['text'].text)) return paymentPageResponse
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 create_an_accept_payment_transaction(self, order_number, dataValue, dataDescriptor, total): # 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 object for a payment nonce opaqueData = apicontractsv1.opaqueDataType() opaqueData.dataDescriptor = dataDescriptor opaqueData.dataValue = dataValue # 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" # 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 = total.incl_tax #transactionrequest.order = order transactionrequest.payment = paymentOne # Assemble the complete transaction request createtransactionrequest = apicontractsv1.createTransactionRequest() createtransactionrequest.merchantAuthentication = merchantAuth # Set the transaction's refId createtransactionrequest.refId = str(order_number) 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'): reference = "Transaction ID: %s\nAuth Code: %s\nTransaction Response Code: %s" \ % (response.transactionResponse.transId, response.transactionResponse.authCode, response.transactionResponse.responseCode) # Record payment source and event self.recordPayment('Authorize.net', total, reference) 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) raise exceptions.UnableToTakePayment 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) raise exceptions.PaymentError else: raise exceptions.PaymentError
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)
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 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 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 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 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 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()
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)
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
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 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
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