Skip to content

Commit

Permalink
Enhancement 2023 (#167)
Browse files Browse the repository at this point in the history
* Jxie/send cart data (#155)

* Implement function to build cart details object in auth request and write unit tests.

* add more needed fields and remove not applicable fields.

* Remove extra call to save payment method (#158)

* Remove unneeded call to save address (#160)

---------

Co-authored-by: Alex Portillo <[email protected]>
  • Loading branch information
justinBolt1987 and alexportillo-bolt authored Jul 6, 2023
1 parent e6d71e5 commit 9c7afe1
Show file tree
Hide file tree
Showing 10 changed files with 1,232 additions and 223 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
var Resource = require('dw/web/Resource');
var Transaction = require('dw/system/Transaction');
var OrderMgr = require('dw/order/OrderMgr');
var StringUtils = require('dw/util/StringUtils');
var Site = require('dw/system/Site');
var HttpResult = require('dw/svc/Result');

// Script includes
Expand All @@ -15,6 +13,7 @@ var oAuth = require('~/cartridge/scripts/services/oAuth');
var constants = require('~/cartridge/scripts/util/constants');
var boltAccountUtils = require('~/cartridge/scripts/util/boltAccountUtils');
var boltPaymentUtils = require('~/cartridge/scripts/util/boltPaymentUtils');
var boltPayAuthRequestBuilder = require('~/cartridge/scripts/util/boltPayAuthRequestBuilder');
var logUtils = require('~/cartridge/scripts/util/boltLogUtils');
var log = logUtils.getLogger('Auth');

Expand Down Expand Up @@ -108,21 +107,12 @@ function authorize(orderNumber, paymentInstrument, paymentProcessor) {
paymentInstrument.paymentTransaction.setPaymentProcessor(paymentProcessor);
});
var order = OrderMgr.getOrder(orderNumber);
// save card to bolt account
// if save card is success, use the new credit card id for authorization
if (boltAccountUtils.loginAsBoltUser() && !empty(paymentInstrument.getCreditCardToken())) {
var saveCardResult = boltAccountUtils.saveCardToBolt(order, paymentInstrument);
if (saveCardResult.success) {
Transaction.wrap(function () {
paymentInstrument.custom.boltPaymentMethodId = saveCardResult.newPaymentMethodID;
});
}
}

// build auth request
var authRequestObj = getAuthRequest(order, paymentInstrument);
var authRequestObj = boltPayAuthRequestBuilder.build(order, paymentInstrument);
if (authRequestObj.error) {
log.error(authRequestObj.errorMsg);
return { error: true, errorCode: '000000', errorMessage: authRequestObj.errorMsg };
}

// only attach oauth token if it is available and the user has not logged out
Expand All @@ -132,7 +122,7 @@ function authorize(orderNumber, paymentInstrument, paymentProcessor) {
bearerToken = 'Bearer '.concat(boltOAuthToken);
}

// send auth call
// Send auth call, note: saves both new address and new payment method.
var response = boltHttpUtils.restAPIClient(
constants.HTTP_METHOD_POST,
constants.AUTH_CARD_URL,
Expand All @@ -157,125 +147,9 @@ function authorize(orderNumber, paymentInstrument, paymentProcessor) {
paymentInstrument.getPaymentTransaction().setTransactionID(orderNumber);
});

// save shipping address to bolt account
if (boltAccountUtils.loginAsBoltUser()) {
boltAccountUtils.saveAddressToBolt(order);
}

return { error: false };
}

/**
* Create Authorization Request Body
* @param {dw.order.Order} order - SFCC order object
* @param {dw.order.PaymentInstrument} paymentInstrument - payment instrument to authorize
* @return {Object} returns an response object
*/
function getAuthRequest(order, paymentInstrument) {
if (empty(paymentInstrument)) {
return { error: true, errorMsg: 'Missing payment instrument.' };
}

if (empty(order.billingAddress)) {
return { error: true, errorMsg: 'SFCC basket has not billing address.' };
}

var billingAddress = order.getBillingAddress();
var userIdentifier = {
email: order.getCustomerEmail(),
phone: billingAddress.getPhone()
};
var userIdentity = {
first_name: billingAddress.getFirstName(),
last_name: billingAddress.getLastName()
};

var boltBillingAddress = {
street_address1: billingAddress.getAddress1() || '',
street_address2: billingAddress.getAddress2() || '',
locality: billingAddress.getCity() || '',
region: billingAddress.getStateCode() || '',
postal_code: billingAddress.getPostalCode() || '',
country_code: billingAddress.getCountryCode() ? billingAddress.getCountryCode().getValue().toUpperCase() : '',
country: billingAddress.getCountryCode() ? billingAddress.getCountryCode().getDisplayValue() : '',
name: billingAddress.getFullName(),
first_name: billingAddress.getFirstName(),
last_name: billingAddress.getLastName(),
phone_number: billingAddress.getPhone(),
email: order.getCustomerEmail(),
phone: billingAddress.getPhone() || ''
};

var request = {
cart: {
order_reference: order.getOrderNo(),
billing_address: boltBillingAddress,
currency: order.currencyCode,
metadata: {
SFCCSessionID: getDwsidCookie()
}
},
division_id:
Site.getCurrent().getCustomPreferenceValue('boltMerchantDivisionID') || '',
source: constants.DIRECT_PAYMENTS,
user_identifier: userIdentifier,
user_identity: userIdentity,
create_bolt_account: paymentInstrument.custom.boltCreateAccount
};

// populate auto capture field if needed
var autoCapture = Site.getCurrent().getCustomPreferenceValue('boltEnableAutoCapture') === true;
if (autoCapture) {
request.auto_capture = true;
}

// use Bolt payment ID for Bolt
if (boltAccountUtils.loginAsBoltUser() && paymentInstrument.custom.boltPaymentMethodId) {
request.credit_card_id = paymentInstrument.custom.boltPaymentMethodId;
} else {
request.credit_card = {
token: paymentInstrument.getCreditCardToken(),
last4: paymentInstrument.getCreditCardNumberLastDigits(),
bin: paymentInstrument.custom.boltCardBin,
billing_address: boltBillingAddress,
number: '',
expiration:
StringUtils.formatNumber(
paymentInstrument.getCreditCardExpirationYear(),
'0000'
)
+ '-'
+ StringUtils.formatNumber(
paymentInstrument.getCreditCardExpirationMonth(),
'00'
),
postal_code: billingAddress.getPostalCode(),
token_type: constants.BOLT_TOKEN_TYPE
};
}

return {
authRequest: request,
error: false
};
}

/**
* getDwsidCookie returns DW Session ID from cookie
* @return {string} DW Session ID
*/
function getDwsidCookie() {
var cookies = request.getHttpCookies();

for (var i = 0; i < cookies.cookieCount; i++) { // eslint-disable-line no-plusplus
if (cookies[i].name === 'dwsid') {
return cookies[i].value;
}
}

return '';
}

/**
* sessionLogoutCookieSet returns true if the bolt_sfcc_session_logout is set
* @return {boolean} true if the cookie is set otherwise false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,57 +178,6 @@ exports.saveCardToBolt = function (order, paymentInstrument) {
}
};

/**
* Save new address to Bolt or update existing Bolt address
* @param {dw.order.Order} order - SFCC order object
* @returns {void} - no return data
*/
exports.saveAddressToBolt = function (order) {
try {
var shippingAddress = order.getDefaultShipment().getShippingAddress();
var errorMsg;
// add bolt address id to endpoint if shopper is updating existing address
var addressUrl = !empty(shippingAddress.custom.boltAddressId) ? (constants.SHOPPER_ADDRESS_URL + '/' + shippingAddress.custom.boltAddressId) : constants.SHOPPER_ADDRESS_URL;
var isGift = order.getDefaultShipment().isGift();

var request = {
street_address1: shippingAddress.address1 || '',
street_address2: shippingAddress.address2 || '',
locality: shippingAddress.city || '',
region: shippingAddress.stateCode || '',
postal_code: shippingAddress.postalCode || '',
country_code: shippingAddress.countryCode.value || '',
first_name: shippingAddress.firstName || '',
last_name: shippingAddress.lastName || '',
phone: shippingAddress.phone || '',
default: !isGift
};

var boltOAuthToken = oAuth.getOAuthToken();
if (empty(boltOAuthToken)) {
errorMsg = 'Bolt OAuth Token is missing';
log.error(errorMsg);
return;
}
var bearerToken = 'Bearer '.concat(boltOAuthToken);

// send save address request to Bolt
var response = boltHttpUtils.restAPIClient(
constants.HTTP_METHOD_POST,
addressUrl,
JSON.stringify(request),
constants.CONTENT_TYPE_JSON,
bearerToken
);
errorMsg = Resource.msg('error.save.address', 'bolt', null);
if (response.status && response.status === HttpResult.ERROR) {
log.error(errorMsg + (!empty(response.errors) && !empty(response.errors[0].message) ? response.errors[0].message : ''));
}
log.info('address successfully saved to bolt');
} catch (e) {
log.error(e.message);
}
};
/**
* Get bolt payment data which is stored in SFCC basket
* @param {dw.order.Basket} basket - the SFCC basket
Expand Down
Loading

0 comments on commit 9c7afe1

Please sign in to comment.