def purchase(card, amount): authorization = apicontractsv1.merchantAuthenticationType() authorization.name = get_api_login_id() authorization.transactionKey = get_transaction_id() card_info = apicontractsv1.creditCardType() card_info.cardNumber = card.number card_info.expirationDate = card.expiration_date card_info.cardCode = card.code payment = apicontractsv1.paymentType() payment.creditCard = card_info request_info = apicontractsv1.transactionRequestType() request_info.transactionType = "authCaptureTransaction" request_info.amount = Decimal(amount) request_info.payment = payment request = apicontractsv1.createTransactionRequest() request.merchantAuthentication = authorization request.refId = "MerchantID-0001" request.transactionRequest = request_info controller = createTransactionController(request) controller.execute() api_response = controller.getresponse() response = response_options(api_response) return response
def refund_credit_card(merchant_name, merchant_transactionKey, transaction_amount, refTransId, credit_card_number, credit_card_expiration_date, mobileDeviceId=None, refId=None, paymentProfileId=None, cardCode=None, shippingProfileId=None, bankAccount_accountNumber=None,): TransactionRequest = CreateTransactionRequest(merchant_name=merchant_name, transactionKey=merchant_transactionKey, transactionType='refundTransaction', amount=transaction_amount, refTransId=refTransId, cardNumber=credit_card_number, expirationDate=credit_card_expiration_date, mobileDeviceId=mobileDeviceId, refId=refId, paymentProfileId=paymentProfileId, cardCode=cardCode, shippingProfileId=shippingProfileId, accountNumber=bankAccount_accountNumber, ) TransactionController = createTransactionController(TransactionRequest) TransactionController.execute() response = TransactionController.getresponse() if response.messages.resultCode == 'Error': for message in response.messages.message: if message.code == 'E00027': raise Error_E00027(response) return response
def charge_credit_card(card, amount): merchant_auth = apicontractsv1.merchantAuthenticationType() merchant_auth.name = settings.get_api_login_id() merchant_auth.transactionKey = settings.get_transaction_id() credit_card = apicontractsv1.creditCardType() credit_card.cardNumber = card.number credit_card.expirationDate = card.expiration_date credit_card.cardCode = card.code payment = apicontractsv1.paymentType() payment.creditCard = credit_card transaction_request = apicontractsv1.transactionRequestType() transaction_request.transactionType = "authCaptureTransaction" transaction_request.amount = Decimal(amount) transaction_request.payment = payment request = apicontractsv1.createTransactionRequest() request.merchantAuthentication = merchant_auth request.refId = "MerchantID-0001" request.transactionRequest = transaction_request transaction_controller = createTransactionController(request) transaction_controller.execute() api_response = transaction_controller.getresponse() response = response_mapper(api_response) return response
def authorize_credit_card(): 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 transactionrequest = apicontractsv1.transactionRequestType() transactionrequest.transactionType = "authCaptureTransaction" transactionrequest.amount = Decimal(amount) transactionrequest.payment = payment createtransactionrequest = apicontractsv1.createTransactionRequest() createtransactionrequest.merchantAuthentication = merchantAuth createtransactionrequest.refId = "MerchantID-0001" createtransactionrequest.transactionRequest = transactionrequest createtransactioncontroller = createTransactionController( createtransactionrequest) createtransactioncontroller.execute() response = createtransactioncontroller.getresponse() if (response.messages.resultCode == "Ok"): print("Transaction ID : %s" % response.transactionResponse.transId) else: print("response code: %s" % response.messages.resultCode)
def void_transaction(self, transaction, payment_method=None): """ Void a transaction :param transaction: A Silver transaction with a AuthorizeNet payment method. :param payment_method: The payment method used to authorize the original transaction :returns True if the state transition was successful, False otherwise. """ payment_processor = get_instance(transaction.payment_processor) if not payment_processor == self: return False transId = str(transaction.data.get('authorizenet_id')) req = apicontractsv1.transactionRequestType() req.transactionType = "voidTransaction" req.refTransId = transId t_req = apicontractsv1.createTransactionRequest() t_req.merchantAuthentication = self.merchantAuth t_req.refId = self.merchantId t_req.transactionRequest = req controller = createTransactionController(t_req) try: controller.execute() except Exception as e: logger.warning('Error executing request to void transaction %s', { 'transaction_id': transId, 'exception': str(e) }) response = controller.getresponse() have_resp = response is not None if have_resp: status, resp_ok = self._get_authorizenet_transaction_status( response) return self._transition_silver_transaction_to( transaction, response, status, transaction.States.Canceled) else: logger.warning( 'Couldn\'t void transaction %s', { 'transaction_id': transId, 'messages': response.messages.message[0]['text'].text }) return False
def _make_request(create_transaction_request, connection_params: Dict[str, Any]): """Create an auth.net transaction controller and execute the request. Returns auth.net response object """ create_transaction_controller = createTransactionController( create_transaction_request) if connection_params.get("use_sandbox") is False: create_transaction_controller.setenvironment(constants.PRODUCTION) create_transaction_controller.execute() response = create_transaction_controller.getresponse() return response
def void_credit_card(merchant_name, merchant_transactionKey, refTransId, mobileDeviceId=None, refId=None,): TransactionRequest = CreateTransactionRequest(merchant_name=merchant_name, transactionKey=merchant_transactionKey, refTransId=refTransId, transactionType='voidTransaction', refId=refId, ) TransactionController = createTransactionController(TransactionRequest) TransactionController.execute() response = TransactionController.getresponse() if response.messages.resultCode == 'Error': for message in response.messages.message: if message.code == 'E00027': raise Error_E00027(response) return response
def charge_authorized_credit_card(merchant_name, merchant_transactionKey, transaction_amount, refTransId, credit_card_number, credit_card_expiration_date, mobileDeviceId=None, refId=None,): TransactionRequest = CreateTransactionRequest(merchant_name=merchant_name, transactionKey=merchant_transactionKey, transactionType='authCaptureTransaction', amount=transaction_amount, refTransId=refTransId, cardNumber=credit_card_number, expirationDate=credit_card_expiration_date, mobileDeviceId=mobileDeviceId, refId=refId, ) TransactionController = createTransactionController(TransactionRequest) TransactionController.execute() response = TransactionController.getresponse() if response.messages.resultCode == 'Error': for message in response.messages.message: if message.code == 'E00027': raise Error_E00027(response) return response
def credit_bank_account(amount): """ Credit a bank account """ # Create a merchantAuthenticationType object with authentication details # retrieved from the constants file merchantAuth = apicontractsv1.merchantAuthenticationType() merchantAuth.name = CONSTANTS.apiLoginId merchantAuth.transactionKey = CONSTANTS.transactionKey # Create the payment data for a bank account bankAccount = apicontractsv1.bankAccountType() accountType = apicontractsv1.bankAccountTypeEnum bankAccount.accountType = accountType.checking bankAccount.routingNumber = "121042882" bankAccount.accountNumber = "1234567890" bankAccount.nameOnAccount = "John Doe" # Add the payment data to a paymentType object payment = apicontractsv1.paymentType() payment.bankAccount = bankAccount # Create a transactionRequestType object and add the previous objects to it. transactionrequest = apicontractsv1.transactionRequestType() transactionrequest.transactionType = "refundTransaction" transactionrequest.amount = amount transactionrequest.payment = payment # Assemble the complete transaction request createtransactionrequest = apicontractsv1.createTransactionRequest() createtransactionrequest.merchantAuthentication = merchantAuth createtransactionrequest.refId = "MerchantID-0001" createtransactionrequest.transactionRequest = transactionrequest # Create the controller createtransactioncontroller = createTransactionController( createtransactionrequest) createtransactioncontroller.execute() response = createtransactioncontroller.getresponse() if response is not None: # Check to see if the API request was successfully received and acted upon if response.messages.resultCode == "Ok": # Since the API request was successful, look for a transaction response # and parse it to display the results of authorizing the card if hasattr(response.transactionResponse, 'messages') is True: print( 'Successfully created transaction with Transaction ID: %s' % response.transactionResponse.transId) print('Transaction Response Code: %s' % response.transactionResponse.responseCode) print('Message Code: %s' % response.transactionResponse.messages.message[0].code) print('Description: %s' % response.transactionResponse. messages.message[0].description) else: print('Failed Transaction.') if hasattr(response.transactionResponse, 'errors') is True: print('Error Code: %s' % str(response.transactionResponse. errors.error[0].errorCode)) print( 'Error message: %s' % response.transactionResponse.errors.error[0].errorText) # Or, print errors if the API request wasn't successful else: print('Failed Transaction.') if hasattr(response, 'transactionResponse') is True and hasattr( response.transactionResponse, 'errors') is True: print('Error Code: %s' % str( response.transactionResponse.errors.error[0].errorCode)) print('Error message: %s' % response.transactionResponse.errors.error[0].errorText) else: print('Error Code: %s' % response.messages.message[0]['code'].text) print('Error message: %s' % response.messages.message[0]['text'].text) else: print('Null Response.') return response
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 charge_credit_card(data): # Create a merchantAuthenticationType object with authentication details # retrieved from the constants file merchantAuth = apicontractsv1.merchantAuthenticationType() merchantAuth.name = "2U6x9AuE" merchantAuth.transactionKey = "5KY6z6r64HtK8kgv" # Create the payment data for a credit card creditCard = apicontractsv1.creditCardType() creditCard.cardNumber = data["createTransactionRequest"]["transactionRequest"]["payment"]["creditCard"]["cardNumber"] creditCard.expirationDate = data["createTransactionRequest"]["transactionRequest"]["payment"]["creditCard"]["expirationDate"] creditCard.cardCode = data["createTransactionRequest"]["transactionRequest"]["payment"]["creditCard"]["cardCode"] # Add the payment data to a paymentType object payment = apicontractsv1.paymentType() payment.creditCard = creditCard # Create a transactionRequestType object and add the previous objects to it. transactionrequest = apicontractsv1.transactionRequestType() transactionrequest.transactionType = "authCaptureTransaction" transactionrequest.amount = data["createTransactionRequest"]["transactionRequest"]["amount"] transactionrequest.payment = payment # Assemble the complete transaction request createtransactionrequest = apicontractsv1.createTransactionRequest() createtransactionrequest.merchantAuthentication = merchantAuth createtransactionrequest.refId = "MerchantID-0001" createtransactionrequest.transactionRequest = transactionrequest # Create the controller createtransactioncontroller = createTransactionController( createtransactionrequest) createtransactioncontroller.execute() response = createtransactioncontroller.getresponse() if response is not None: # Check to see if the API request was successfully received and acted upon if response.messages.resultCode == "Ok": # Since the API request was successful, look for a transaction response # and parse it to display the results of authorizing the card if hasattr(response.transactionResponse, 'messages') is True: print( 'Successfully created transaction with Transaction ID: %s' % response.transactionResponse.transId) print('Transaction Response Code: %s' % response.transactionResponse.responseCode) print('Message Code: %s' % response.transactionResponse.messages.message[0].code) print('Description: %s' % response.transactionResponse. messages.message[0].description) else: print('Failed Transaction.') if hasattr(response.transactionResponse, 'errors') is True: print('Error Code: %s' % str(response.transactionResponse. errors.error[0].errorCode)) print( 'Error message: %s' % response.transactionResponse.errors.error[0].errorText) # Or, print errors if the API request wasn't successful else: print('Failed Transaction.') if hasattr(response, 'transactionResponse') is True and hasattr( response.transactionResponse, 'errors') is True: print('Error Code: %s' % str( response.transactionResponse.errors.error[0].errorCode)) print('Error message: %s' % response.transactionResponse.errors.error[0].errorText) else: print('Error Code: %s' % response.messages.message[0]['code'].text) print('Error message: %s' % response.messages.message[0]['text'].text) else: print('Null Response.') return response
def 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 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 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 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()
def issue_credit(self, order_number, basket, reference_number, amount, currency): # pylint: disable=too-many-statements """ Refund a AuthorizeNet payment for settled transactions.For more Authorizenet Refund API information, visit https://developer.authorize.net/api/reference/#payment-transactions-refund-a-transaction """ try: paymnet_response = PaymentProcessorResponse.objects.filter( processor_name=self.NAME, transaction_id=reference_number ).latest('created') reference_transaction_details = json.loads(paymnet_response.response) except: msg = 'AuthorizeNet issue credit error for order [{}]. Unable to get payment transaction details.'.format( order_number) logger.exception(msg) raise PaymentProcessorResponseNotFound(msg) transaction_card_info = reference_transaction_details.get('transaction', {}).get('payment', {}).get( 'creditCard', {}) if not transaction_card_info: msg = 'AuthorizeNet issue credit error for order [{}]. Unable to get card-information.'.format( order_number) logger.exception(msg) raise MissingProcessorResponseCardInfo(msg) merchant_auth = apicontractsv1.merchantAuthenticationType() merchant_auth.name = self.merchant_auth_name merchant_auth.transactionKey = self.transaction_key credit_card = apicontractsv1.creditCardType() credit_card.cardNumber = transaction_card_info.get('cardNumber', "")[-4:] credit_card.expirationDate = transaction_card_info.get('expirationDate', "") payment = apicontractsv1.paymentType() payment.creditCard = credit_card transaction_request = apicontractsv1.transactionRequestType() transaction_request.transactionType = "refundTransaction" transaction_request.amount = amount transaction_request.refTransId = reference_number # set refTransId to transId of a settled transaction transaction_request.payment = payment create_transaction_request = apicontractsv1.createTransactionRequest() create_transaction_request.merchantAuthentication = merchant_auth create_transaction_request.transactionRequest = transaction_request create_transaction_controller = createTransactionController(create_transaction_request) create_transaction_controller.execute() response = create_transaction_controller.getresponse() if response is not None: if response.messages.resultCode == "Ok": if hasattr(response.transactionResponse, 'messages'): logger.info('Message Code: %s', response.transactionResponse.messages.message[0].code) logger.info('Description: %s', response.transactionResponse.messages.message[0].description) refund_transaction_id = response.transactionResponse.transId refund_transaction_dict = LxmlObjectJsonEncoder().encode(response) self.record_processor_response( refund_transaction_dict, transaction_id=refund_transaction_id, basket=basket) return refund_transaction_id else: logger.error('AuthorizeNet issue credit request failed.') if hasattr(response.transactionResponse, 'errors'): logger.error('Error Code: %s', str(response.transactionResponse.errors.error[0].errorCode)) logger.error('Error message: %s', response.transactionResponse.errors.error[0].errorText) else: logger.error('AuthorizeNet issue credit request failed.') if hasattr(response, 'transactionResponse') and hasattr(response.transactionResponse, 'errors'): logger.error('Error Code: %s', str(response.transactionResponse.errors.error[0].errorCode)) logger.error('Error message: %s', response.transactionResponse.errors.error[0].errorText) else: logger.error('Error Code: %s', response.messages.message[0]['code'].text) logger.error('Error message: %s', response.messages.message[0]['text'].text) msg = 'An error occurred while attempting to issue a credit (via Authorizenet) for order [{}].'.format( order_number) logger.exception(msg) raise RefundError(msg)
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 _charge_transaction(self, transaction, charge_profile=False): """ :param transaction: The Silver transaction to be charged. Must have a usable AuthorizeNet payment_method. :return: True on success, False on failure. """ payment_method = transaction.payment_method if payment_method.canceled: try: transaction.fail(fail_reason='Payment method was canceled.') transaction.save() finally: return False # Create a transactionRequestType object and add the previous objects to it. # TODO: customerdata for everything if charge_profile: logger.info("Charging to profile") try: customer_data = CustomerData.objects.get(customer=transaction.customer) except CustomerData.DoesNotExist: created = create_customer_profile(transaction.customer) if created: logger.info("Created new profile") finally: customer_data = CustomerData.objects.get(customer=transaction.customer) logger.info("Creating request") t_reqs = self._create_transaction_request_for_profile( transaction, customer_data.get('profile_id'), customer_data.get('payment_id') ) else: logger.info("Charging card") t_reqs = self._create_transaction_request(transaction) # Create the transaction controller transaction_controller = createTransactionController(t_reqs) # Set the environment transaction_controller.setenvironment(self.environment) # Execute the transaction request try: transaction_controller.execute() except Exception as e: logger.info( 'Error in request create transaction %s', { 'exception': str(e) } ) response = transaction_controller.getresponse() try: return self._update_silver_transaction_status(transaction, response) except TransitionNotAllowed: # TODO: handle this return False
def refund_transaction(self, transaction, payment_method=None): """ Refund a transaction :param transaction: A Silver transaction with a AuthorizeNet payment method. :param payment_method: The payment method used to authorize the original transaction :returns True if the state transition was successful, False otherwise. """ payment_processor = get_instance(transaction.payment_processor) if not payment_processor == self: return False transId = str(transaction.data.get('authorizenet_id')) payment = apicontractsv1.paymentType() payment.creditCard = self._create_credit_card( transaction.payment_method.customer) tr_req = apicontractsv1.transactionRequestType() tr_req.transactionType = "refundTransaction" tr_req.amount = transaction.amount tr_req.refTransId = transId tr_req.payment = payment create_req = apicontractsv1.createTransactionRequest() create_req.merchantAuthentication = self.merchantAuth create_req.refId = self.merchantId create_req.transactionRequest = tr_req controller = createTransactionController(create_req) try: controller.execute() except Exception as e: logger.warning('Error executing request to refund transaction %s', { 'transaction_id': transId, 'exception': str(e) }) response = controller.getresponse() have_resp = response is not None if have_resp: status, resp_okay = self._get_authorizenet_transaction_status( response) t_resp = response.transactionResponse if resp_okay: transaction.external_reference = t_resp.transId # TODO: wrong object for `response`? return self._transition_silver_transaction_to( transaction, response, status, transaction.States.Refunded) else: logger.warning( 'Couldn\'t refund transaction %s', { 'transaction_id': transId, 'messages': response.messages.message[0]['text'].text }) return False
def charge_new_credit_card(merchant_name, merchant_transactionKey, transaction_amount, employeeId=None, track1=None, track2=None, credit_card_number=None, credit_card_expiration_date=None, cardCode=None, createProfile=None, solution_id=None, invoiceNumber=None, order_description=None, #lineItems, tax_amount=None, tax_name=None, tax_description=None, duty_amount=None, duty_name=None, duty_description=None, shipping_amount=None, shipping_name=None, shipping_description=None, taxExempt=None, poNumber=None, customer_type=None, customer_id=None, customer_email=None, billTo_firstName=None, billTo_lastName=None, billTo_company=None, billTo_address=None, billTo_city=None, billTo_state=None, billTo_zip=None, billTo_country=None, billTo_phoneNumber=None, billTo_faxNumber=None, shipTo_firstName=None, shipTo_lastName=None, shipTo_company=None, shipTo_address=None, shipTo_city=None, shipTo_state=None, shipTo_zip=None, shipTo_country=None, customerIp=None, authenticationIndicator=None, cardholderAuthenticationValue=None, marketType=None, deviceType=None, settingName=None, settingValue=None, userField_name=None, userField_value=None, mobileDeviceId=None, refId=None,): # must provide track1, track2 or cardNumber and expirationDate if not (track1 or track2 or (credit_card_number and credit_card_expiration_date)): pass # TODO raise error TransactionRequest = CreateTransactionRequest(merchant_name=merchant_name, transactionKey=merchant_transactionKey, amount=transaction_amount, employeeId=employeeId, track1=track1, track2=track2, cardNumber=credit_card_number, expirationDate=credit_card_expiration_date, cardCode=cardCode, createProfile=createProfile, solution_id=solution_id, invoiceNumber=invoiceNumber, description=order_description, #TODO lineItems, tax_amount=tax_amount, tax_name=tax_name, tax_description=tax_description, duty_amount=duty_amount, duty_name=duty_name, duty_description=duty_description, shipping_amount=shipping_amount, shipping_name=shipping_name, shipping_description=shipping_description, taxExempt=taxExempt, poNumber=poNumber, type=customer_type, customer_id=customer_id, email=customer_email, customerAddress_firstName=billTo_firstName, customerAddress_lastName=billTo_lastName, customerAddress_company=billTo_company, customerAddress_address=billTo_address, customerAddress_city=billTo_city, customerAddress_state=billTo_state, customerAddress_zip=billTo_zip, customerAddress_country=billTo_country, customerAddress_phoneNumber=billTo_phoneNumber, customerAddress_faxNumber=billTo_faxNumber, shipTo_firstName=shipTo_firstName, shipTo_lastName=shipTo_lastName, shipTo_company=shipTo_company, shipTo_address=shipTo_address, shipTo_city=shipTo_city, shipTo_state=shipTo_state, shipTo_zip=shipTo_zip, shipTo_country=shipTo_country, customerIP=customerIp, authenticationIndicator=authenticationIndicator, cardholderAuthenticationValue=cardholderAuthenticationValue, marketType=marketType, deviceType=deviceType, settingName=settingName, settingValue=settingValue, userField_name=userField_name, userField_value=userField_value, mobileDeviceId=mobileDeviceId, transactionType='authCaptureTransaction', refId=refId, ) TransactionController = createTransactionController(TransactionRequest) TransactionController.execute() response = TransactionController.getresponse() if response.messages.resultCode == 'Error': for message in response.messages.message: if message.code == 'E00027': raise Error_E00027(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 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 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 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