<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" version="2.0">
  <channel>
    <title>topic Create Profile synchronous issues using Node's SDK sample code in Integration and Testing</title>
    <link>https://community.developer.cybersource.com/t5/Integration-and-Testing/Create-Profile-synchronous-issues-using-Node-s-SDK-sample-code/m-p/80617#M50811</link>
    <description>&lt;P&gt;&lt;FONT face="arial,helvetica,sans-serif" size="2"&gt;I am trying to create a customer payment profile with the Node SDK using the sample code. While I am able to create a customer profile successfully and receive a successful response from the API call&amp;nbsp;&lt;/FONT&gt;&lt;/P&gt;&lt;DIV&gt;&lt;DIV&gt;&lt;FONT face="arial,helvetica,sans-serif" size="2"&gt;&lt;SPAN&gt;CustomerProfilesModule&lt;/SPAN&gt;&lt;SPAN&gt;.&lt;/SPAN&gt;&lt;SPAN&gt;createCustomerProfile&lt;/SPAN&gt;&lt;SPAN&gt;, the remainder of my auth.controller.js runs before I get the API result. All of the create-customer-profile.js runs up until the ctrl.execute() runs, then the console.log("xxx") in auth.controller.js runs before grabbing the API result.&amp;nbsp;&lt;/SPAN&gt;&lt;/FONT&gt;&lt;/DIV&gt;&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;&lt;DIV&gt;&lt;FONT face="arial,helvetica,sans-serif" size="2"&gt;&lt;SPAN&gt;I understand this is a synchronous issue with my code, but I don't know how to solve this. I am using the sample code authorize.NET provided, however the code is using the real data from my app rather than the sample data. I am more than happy to provide further information upon request and really appreciate any help!&amp;nbsp;&lt;/SPAN&gt;&lt;/FONT&gt;&lt;/DIV&gt;&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;auth.controller.js&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;PRE&gt;const httpStatus = require("http-status");
const ApiContracts = require("authorizenet").APIContracts;
const ApiControllers = require("authorizenet").APIControllers;
const SDKConstants = require("authorizenet").Constants;
const User = require("../models/user.model");
const RefreshToken = require("../models/refreshToken.model");
const moment = require("moment-timezone");
const { jwtExpirationInterval } = require("../../config/vars");
const sgMail = require("@sendgrid/mail");
const bcrypt = require("bcryptjs");
const CustomerProfilesModule = require("../utils/authorizeNet/CustomerProfiles");

sgMail.setApiKey(process.env.SENDGRID_API_KEY.replace(/\r?\n|\r/g, ""));

exports.register = async (req, res, next) =&amp;gt; {
  try {
    const userData = req.body;

    let customerProfileResult =
      await CustomerProfilesModule.createCustomerProfile(userData);
    console.log(
      "❌ ❌ ❌ ❌ ❌ customerProfile Result ",
      customerProfileResult
    );

    if (!userData || userData.error) {
      return next(error);
    } else {
      const { isTrial } = userData;

      const user = await new User(userData).save();

      const token = generateTokenResponse(user, user.token());


      res.status(httpStatus.CREATED);
      return res.json({ token, user });
    }
  } catch (error) {
    console.log(error.message);
    return next(User.checkDuplicateEmail(error));
  }
};&lt;/PRE&gt;&lt;SPAN&gt;create-customer-profile.js&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;PRE&gt;"use strict";

var ApiContracts = require("authorizenet").APIContracts;
var ApiControllers = require("authorizenet").APIControllers;
var utils = require("../utils.js");

async function createCustomerProfile(user) {
  console.log(" user parameter", user);
  var merchantAuthenticationType =
    new ApiContracts.MerchantAuthenticationType();
  merchantAuthenticationType.setName(process.env.AUTHORIZE_NET_API_LOGIN_KEY);
  merchantAuthenticationType.setTransactionKey(
    process.env.AUTHORIZE_NET_TRANSACTION_KEY
  );

  var creditCard = new ApiContracts.CreditCardType();
  creditCard.setCardNumber(user.cardNumber);
  if (user.cardExpiry.length &amp;gt; 4) {
    creditCard.setExpirationDate(
      `${user.cardExpiry.slice(0, 1)}${user.cardExpiry.slice(3, 4)}`
    );
  } else {
    creditCard.setExpirationDate(user.cardExpiry);
  }

  console.log("creditCard", creditCard);

  var paymentType = new ApiContracts.PaymentType();

  paymentType.setCreditCard(creditCard);

  var customerAddress = new ApiContracts.CustomerAddressType();

  customerAddress.setFirstName(user.firstName);
  customerAddress.setLastName(user.lastName);
  customerAddress.setAddress(user.mailingAddress);
  customerAddress.setCity(user.mailingCity);
  customerAddress.setState(user.mailingState);
  customerAddress.setZip(user.mailingZip);
  customerAddress.setCountry("USA");
  customerAddress.setPhoneNumber(user.userPhone);

  var customerPaymentProfileType =
    new ApiContracts.CustomerPaymentProfileType();
  customerPaymentProfileType.setCustomerType(
    ApiContracts.CustomerTypeEnum.INDIVIDUAL
  );
  customerPaymentProfileType.setPayment(paymentType);
  customerPaymentProfileType.setBillTo(customerAddress);

  var paymentProfilesList = [];
  paymentProfilesList.push(customerPaymentProfileType);
  console.log(
    "paymentProfilesList",
    paymentProfilesList
  );

  var customerProfileType = new ApiContracts.CustomerProfileType();
  customerProfileType.setMerchantCustomerId(
    "M_" + utils.getRandomString("cust")
  );
  customerProfileType.setDescription(
    `${user.firstName} ${user.lastName}'s Account'`
  );
  customerProfileType.setEmail(user.userEmail);
  customerProfileType.setPaymentProfiles(paymentProfilesList);

  var createRequest = new ApiContracts.CreateCustomerProfileRequest();
  createRequest.setProfile(customerProfileType);
  createRequest.setValidationMode(ApiContracts.ValidationModeEnum.TESTMODE);
  createRequest.setMerchantAuthentication(merchantAuthenticationType);

  var ctrl = new ApiControllers.CreateCustomerProfileController(
    createRequest.getJSON()
  );

  // All above code is ran when  CustomerProfilesModule.createCustomerProfile(userData) is executed in auth.controller.js
  // However the following line (line 130 in auth.controller.js) is ran before the below ctrl.execute() code is completed
  //
  //    console.log("❌ ❌ ❌ ❌ ❌ customerProfile Result ", customerProfileResult);
  //
  // All the above code is executed before that console.log("❌ ❌ ❌") statement above, however the below code doesn't run before that console.log
  // I'd like the below code to execute before the remaining register route is finished, but just don't know what is going on!

  ctrl.execute(async function () {
    var apiResponse = await ctrl.getResponse();
    console.log("apiResponse", apiResponse);

    var response = new ApiContracts.CreateCustomerProfileResponse(apiResponse);
    console.log("response", response);

    //pretty print response
    //console.log(JSON.stringify(response, null, 2));

    if (response != null) {
      if (
        response.getMessages().getResultCode() ==
        ApiContracts.MessageTypeEnum.OK
      ) {
        console.log(
          "Successfully created a customer profile with id: " +
            response.getCustomerProfileId()
        );
      } else {
        console.log("Result Code: " + response.getMessages().getResultCode());
        console.log(
          "Error Code: " + response.getMessages().getMessage()[0].getCode()
        );
        console.log(
          "Error message: " + response.getMessages().getMessage()[0].getText()
        );
        return {
          error:
            "Error message: " +
            response.getMessages().getMessage()[0].getText(),
        };
      }
    } else {
      console.log("Null response received");
      return { error: "Null response received" };
    }
  });
}

module.exports.createCustomerProfile = createCustomerProfile;&lt;/PRE&gt;&lt;/DIV&gt;&lt;/DIV&gt;</description>
    <pubDate>Wed, 29 Dec 2021 23:00:57 GMT</pubDate>
    <dc:creator>Bolmstead3</dc:creator>
    <dc:date>2021-12-29T23:00:57Z</dc:date>
    <item>
      <title>Create Profile synchronous issues using Node's SDK sample code</title>
      <link>https://community.developer.cybersource.com/t5/Integration-and-Testing/Create-Profile-synchronous-issues-using-Node-s-SDK-sample-code/m-p/80617#M50811</link>
      <description>&lt;P&gt;&lt;FONT face="arial,helvetica,sans-serif" size="2"&gt;I am trying to create a customer payment profile with the Node SDK using the sample code. While I am able to create a customer profile successfully and receive a successful response from the API call&amp;nbsp;&lt;/FONT&gt;&lt;/P&gt;&lt;DIV&gt;&lt;DIV&gt;&lt;FONT face="arial,helvetica,sans-serif" size="2"&gt;&lt;SPAN&gt;CustomerProfilesModule&lt;/SPAN&gt;&lt;SPAN&gt;.&lt;/SPAN&gt;&lt;SPAN&gt;createCustomerProfile&lt;/SPAN&gt;&lt;SPAN&gt;, the remainder of my auth.controller.js runs before I get the API result. All of the create-customer-profile.js runs up until the ctrl.execute() runs, then the console.log("xxx") in auth.controller.js runs before grabbing the API result.&amp;nbsp;&lt;/SPAN&gt;&lt;/FONT&gt;&lt;/DIV&gt;&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;&lt;DIV&gt;&lt;FONT face="arial,helvetica,sans-serif" size="2"&gt;&lt;SPAN&gt;I understand this is a synchronous issue with my code, but I don't know how to solve this. I am using the sample code authorize.NET provided, however the code is using the real data from my app rather than the sample data. I am more than happy to provide further information upon request and really appreciate any help!&amp;nbsp;&lt;/SPAN&gt;&lt;/FONT&gt;&lt;/DIV&gt;&lt;DIV&gt;&amp;nbsp;&lt;/DIV&gt;&lt;DIV&gt;&lt;SPAN&gt;auth.controller.js&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;PRE&gt;const httpStatus = require("http-status");
const ApiContracts = require("authorizenet").APIContracts;
const ApiControllers = require("authorizenet").APIControllers;
const SDKConstants = require("authorizenet").Constants;
const User = require("../models/user.model");
const RefreshToken = require("../models/refreshToken.model");
const moment = require("moment-timezone");
const { jwtExpirationInterval } = require("../../config/vars");
const sgMail = require("@sendgrid/mail");
const bcrypt = require("bcryptjs");
const CustomerProfilesModule = require("../utils/authorizeNet/CustomerProfiles");

sgMail.setApiKey(process.env.SENDGRID_API_KEY.replace(/\r?\n|\r/g, ""));

exports.register = async (req, res, next) =&amp;gt; {
  try {
    const userData = req.body;

    let customerProfileResult =
      await CustomerProfilesModule.createCustomerProfile(userData);
    console.log(
      "❌ ❌ ❌ ❌ ❌ customerProfile Result ",
      customerProfileResult
    );

    if (!userData || userData.error) {
      return next(error);
    } else {
      const { isTrial } = userData;

      const user = await new User(userData).save();

      const token = generateTokenResponse(user, user.token());


      res.status(httpStatus.CREATED);
      return res.json({ token, user });
    }
  } catch (error) {
    console.log(error.message);
    return next(User.checkDuplicateEmail(error));
  }
};&lt;/PRE&gt;&lt;SPAN&gt;create-customer-profile.js&lt;/SPAN&gt;&lt;/DIV&gt;&lt;DIV&gt;&lt;PRE&gt;"use strict";

var ApiContracts = require("authorizenet").APIContracts;
var ApiControllers = require("authorizenet").APIControllers;
var utils = require("../utils.js");

async function createCustomerProfile(user) {
  console.log(" user parameter", user);
  var merchantAuthenticationType =
    new ApiContracts.MerchantAuthenticationType();
  merchantAuthenticationType.setName(process.env.AUTHORIZE_NET_API_LOGIN_KEY);
  merchantAuthenticationType.setTransactionKey(
    process.env.AUTHORIZE_NET_TRANSACTION_KEY
  );

  var creditCard = new ApiContracts.CreditCardType();
  creditCard.setCardNumber(user.cardNumber);
  if (user.cardExpiry.length &amp;gt; 4) {
    creditCard.setExpirationDate(
      `${user.cardExpiry.slice(0, 1)}${user.cardExpiry.slice(3, 4)}`
    );
  } else {
    creditCard.setExpirationDate(user.cardExpiry);
  }

  console.log("creditCard", creditCard);

  var paymentType = new ApiContracts.PaymentType();

  paymentType.setCreditCard(creditCard);

  var customerAddress = new ApiContracts.CustomerAddressType();

  customerAddress.setFirstName(user.firstName);
  customerAddress.setLastName(user.lastName);
  customerAddress.setAddress(user.mailingAddress);
  customerAddress.setCity(user.mailingCity);
  customerAddress.setState(user.mailingState);
  customerAddress.setZip(user.mailingZip);
  customerAddress.setCountry("USA");
  customerAddress.setPhoneNumber(user.userPhone);

  var customerPaymentProfileType =
    new ApiContracts.CustomerPaymentProfileType();
  customerPaymentProfileType.setCustomerType(
    ApiContracts.CustomerTypeEnum.INDIVIDUAL
  );
  customerPaymentProfileType.setPayment(paymentType);
  customerPaymentProfileType.setBillTo(customerAddress);

  var paymentProfilesList = [];
  paymentProfilesList.push(customerPaymentProfileType);
  console.log(
    "paymentProfilesList",
    paymentProfilesList
  );

  var customerProfileType = new ApiContracts.CustomerProfileType();
  customerProfileType.setMerchantCustomerId(
    "M_" + utils.getRandomString("cust")
  );
  customerProfileType.setDescription(
    `${user.firstName} ${user.lastName}'s Account'`
  );
  customerProfileType.setEmail(user.userEmail);
  customerProfileType.setPaymentProfiles(paymentProfilesList);

  var createRequest = new ApiContracts.CreateCustomerProfileRequest();
  createRequest.setProfile(customerProfileType);
  createRequest.setValidationMode(ApiContracts.ValidationModeEnum.TESTMODE);
  createRequest.setMerchantAuthentication(merchantAuthenticationType);

  var ctrl = new ApiControllers.CreateCustomerProfileController(
    createRequest.getJSON()
  );

  // All above code is ran when  CustomerProfilesModule.createCustomerProfile(userData) is executed in auth.controller.js
  // However the following line (line 130 in auth.controller.js) is ran before the below ctrl.execute() code is completed
  //
  //    console.log("❌ ❌ ❌ ❌ ❌ customerProfile Result ", customerProfileResult);
  //
  // All the above code is executed before that console.log("❌ ❌ ❌") statement above, however the below code doesn't run before that console.log
  // I'd like the below code to execute before the remaining register route is finished, but just don't know what is going on!

  ctrl.execute(async function () {
    var apiResponse = await ctrl.getResponse();
    console.log("apiResponse", apiResponse);

    var response = new ApiContracts.CreateCustomerProfileResponse(apiResponse);
    console.log("response", response);

    //pretty print response
    //console.log(JSON.stringify(response, null, 2));

    if (response != null) {
      if (
        response.getMessages().getResultCode() ==
        ApiContracts.MessageTypeEnum.OK
      ) {
        console.log(
          "Successfully created a customer profile with id: " +
            response.getCustomerProfileId()
        );
      } else {
        console.log("Result Code: " + response.getMessages().getResultCode());
        console.log(
          "Error Code: " + response.getMessages().getMessage()[0].getCode()
        );
        console.log(
          "Error message: " + response.getMessages().getMessage()[0].getText()
        );
        return {
          error:
            "Error message: " +
            response.getMessages().getMessage()[0].getText(),
        };
      }
    } else {
      console.log("Null response received");
      return { error: "Null response received" };
    }
  });
}

module.exports.createCustomerProfile = createCustomerProfile;&lt;/PRE&gt;&lt;/DIV&gt;&lt;/DIV&gt;</description>
      <pubDate>Wed, 29 Dec 2021 23:00:57 GMT</pubDate>
      <guid>https://community.developer.cybersource.com/t5/Integration-and-Testing/Create-Profile-synchronous-issues-using-Node-s-SDK-sample-code/m-p/80617#M50811</guid>
      <dc:creator>Bolmstead3</dc:creator>
      <dc:date>2021-12-29T23:00:57Z</dc:date>
    </item>
  </channel>
</rss>

