I am sending error, request, and code the only thing i changed in code is i am removing null fields from request if i dont i get E00001
const { APIContracts, APIControllers } = require('authorizenet');
const merchantAuthentication = new APIContracts.MerchantAuthenticationType();
merchantAuthentication.setName(process.env.AUTHORIZENET_API_LOGIN_ID_SANDBOX);
merchantAuthentication.setTransactionKey(process.env.AUTHORIZENET_TRANSACTION_KEY_SANDBOX);
async function createCustomerProfile(email) {
return new Promise((resolve, reject) => {
const refId = 'ref' + Date.now();
const customerProfile = new APIContracts.CustomerProfileType();
customerProfile.setDescription('Subscription');
customerProfile.setMerchantCustomerId('M_' + Date.now());
customerProfile.setEmail(email);
const createRequest = new APIContracts.CreateCustomerProfileRequest();
createRequest.setProfile(customerProfile);
createRequest.setMerchantAuthentication(merchantAuthentication);
createRequest.setRefId(refId);
const controller = new APIControllers.CreateCustomerProfileController(createRequest.getJSON());
// or
controller.execute(() => {
const apiResponse = controller.getResponse();
const response = new APIContracts.CreateCustomerProfileResponse(apiResponse);
if (
response &&
response.getMessages().getResultCode() === APIContracts.MessageTypeEnum.OK
) {
resolve(response.getCustomerProfileId());
} else {
const errorMessages = response.getMessages().getMessage();
reject(new Error(errorMessages[0].getText()));
}
});
});
}
function createPaymentProfile(customerProfileId, opaqueData, billingInfo,Email) {
return new Promise((resolve, reject) => {
const opaque = new APIContracts.OpaqueDataType();
opaque.setDataDescriptor(opaqueData.dataDescriptor);
opaque.setDataValue(opaqueData.dataValue);
console.log("opaqe",opaque);
const payment = new APIContracts.PaymentType();
payment.setOpaqueData(opaque);
// const payment = {
// opaqueData: {
// dataDescriptor: opaqueData.dataDescriptor,
// dataValue: opaqueData.dataValue
// }
// };
console.log("payment",payment);
const billTo = new APIContracts.CustomerAddressType();
billTo.setFirstName(billingInfo.firstName);
billTo.setLastName(billingInfo.lastName);
billTo.setAddress(billingInfo.address);
billTo.setCity(billingInfo.city);
billTo.setState(billingInfo.state);
billTo.setZip(billingInfo.zip);
billTo.setCountry(billingInfo.country);
billTo.setPhoneNumber(billingInfo.phone);
billTo.setEmail(Email);
// billTo.faxNumber = undefined;
// billTo.company = undefined;
console.log("bill to",billTo);
const paymentProfile = new APIContracts.CustomerPaymentProfileType();
// paymentProfile.setCustomerType(APIContracts.CustomerTypeEnum.INDIVIDUAL);
paymentProfile.setPayment(payment);
paymentProfile.setBillTo(billTo);
paymentProfile.setDefaultPaymentProfile(true);
console.log("paymentpro",paymentProfile);
const request = new APIContracts.CreateCustomerPaymentProfileRequest();
request.setMerchantAuthentication(merchantAuthentication);
request.setCustomerProfileId(customerProfileId);
request.setPaymentProfile(paymentProfile);
//request.setValidationMode(APIContracts.ValidationModeEnum.LIVEMODE);
request.setValidationMode(APIContracts.ValidationModeEnum.TESTMODE);
console.log("request",request);
const rawRequest = request.getJSON(); // or any object you're building
// console.log("raw request",request.getJSON());
const cleanedRequest = removeNulls(rawRequest);
//const cleanedRequest = rawRequest;
console.log("cleaned request",JSON.stringify(cleanedRequest));
const controller = new APIControllers.CreateCustomerPaymentProfileController(cleanedRequest);
console.log("controller",JSON.stringify(controller));
controller.execute(() => {
try {
const apiResponse = controller.getResponse();
console.log("Raw API Response:", apiResponse);
console.log("API Response:", JSON.stringify(apiResponse));
const response = new APIContracts.CreateCustomerPaymentProfileResponse(apiResponse);
if (
response &&
response.getMessages().getResultCode() === APIContracts.MessageTypeEnum.OK
) {
console.log("Payment Profile ID:", response.getCustomerPaymentProfileId());
resolve(response.getCustomerPaymentProfileId());
} else {
const errorMessages = response.getMessages().getMessage();
errorMessages.forEach((msg, index) => {
console.error(`Error ${index + 1}: Code=${msg.getCode()}, Text=${msg.getText()}`);
});
reject(new Error(errorMessages[0].getText()));
}
} catch (err) {
console.error("Execution Error:", err);
reject(err);
}
});
});
}
function deleteCustomerProfile(customerProfileId) {
return new Promise((resolve) => {
const request = new APIContracts.DeleteCustomerProfileRequest();
request.setMerchantAuthentication(merchantAuthentication);
request.setCustomerProfileId(customerProfileId);
const controller = new APIControllers.DeleteCustomerProfileController(request.getJSON());
// or
controller.execute(() => resolve());
});
}
//used ot remove nulls
function removeNulls(obj) {
if (Array.isArray(obj)) {
return obj
.map(v => removeNulls(v))
.filter(v => v !== null && v !== undefined);
} else if (typeof obj === 'object' && obj !== null) {
const cleaned = {};
for (const key in obj) {
const value = removeNulls(obj[key]);
if (value !== null && value !== undefined) {
cleaned[key] = value;
}
}
return cleaned;
}
return obj;
}
exports.postNewCustomer = async (event) => {
console.log("Start New Billing Profiles");
let body;
try {
body = JSON.parse(event.body || '{}');
} catch (err) {
return {
statusCode: 400,
body: JSON.stringify({ error: 'Invalid JSON in request body' }),
};
}
const { email, opaqueData, billingInfo } = body;
if (
!email ||
!opaqueData ||
!opaqueData.dataDescriptor ||
!opaqueData.dataValue ||
!billingInfo ||
!billingInfo.firstName
) {
return {
statusCode: 400,
body: JSON.stringify({ error: 'Missing required fields' }),
};
}
console.log(email);
console.log(opaqueData);
console.log(billingInfo);
let customerProfileId = null;
try {
customerProfileId = await createCustomerProfile(email);
console.log(customerProfileId);
const paymentProfileId = await createPaymentProfile(customerProfileId, opaqueData, billingInfo,email);
console.log(paymentProfileId);
return {
statusCode: 201,
body: JSON.stringify({
message: 'Customer and payment profile created',
customerProfileId,
paymentProfileId,
}),
};
} catch (error) {
if (customerProfileId) {
await deleteCustomerProfile(customerProfileId);
}
console.error('Error:', error.message);
return {
statusCode: 500,
body: JSON.stringify({ error: error.message || 'Internal error' }),
};
}
};