Advertisement
KoctrX

Untitled

Jan 16th, 2024
841
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const authorizenet = require('authorizenet');
  2. const config = require('../config');
  3. const utils = require('../utils');
  4. const PaymentCard = require('../models/PaymentCard');
  5. const paymentModule = require('../modules/payments');
  6. const permissinFields = require('../helpers/permissinFields');
  7. const _ = require('lodash');
  8. const moment = require('moment');
  9.  
  10. module.exports = class {
  11.     constructor(user) {
  12.         this.paymentSystem = 'Authorize.Net';
  13.         const merchantAuthenticationType = new authorizenet.APIContracts.MerchantAuthenticationType();
  14.         merchantAuthenticationType.setName(config.authorize_net_apiLoginID);
  15.         merchantAuthenticationType.setTransactionKey(config.authorize_net_transactionKey);
  16.  
  17.         this.merchantAuthenticationType = merchantAuthenticationType;
  18.         this.user = user;
  19.  
  20.         this.validationMode = authorizenet.APIContracts.ValidationModeEnum.TESTMODE;
  21.         if (config.authorize_net_mode === 'LIVE') {
  22.             this.validationMode = authorizenet.APIContracts.ValidationModeEnum.LIVEMODE;
  23.         }
  24.  
  25.         console.log('CONSOLE>', this.validationMode);
  26.  
  27.         this.errors = [];
  28.     }
  29.  
  30.     generateErrorResponse(def = '') {
  31.         if ((this.errors || []).filter(text => Boolean((text || '').trim())).length) {
  32.             return this.errors;
  33.         }
  34.         //if(this.errors.length) return this.errors;
  35.  
  36.         return def;
  37.     }
  38.  
  39.     loggingError(error) {
  40.         console.error('Authorizenet error: ', JSON.stringify(error));
  41.  
  42.         if (error && error.messages) {
  43.             //this.errors = error.messages.message || [];
  44.             this.errors = (error.messages.message || []).map(msg => msg.text);
  45.         }
  46.  
  47.         return false;
  48.     }
  49.  
  50.     isErrorAuthorize(response) {
  51.         return response.messages && response.messages.resultCode === authorizenet.APIContracts.MessageTypeEnum.ERROR;
  52.     }
  53.  
  54.     requestAuthorize(authorizeRequest) {
  55.         return new Promise(resolve => authorizeRequest.execute(() => resolve(authorizeRequest.getResponse())));
  56.     }
  57.  
  58.     getCustomerEmail() {
  59.         //return `1aikit_user_${this.user.id}@${config.domainName}`;
  60.         return `${utils.uuidv4()}${this.user.id}@${config.domainName}`;
  61.     }
  62.  
  63.     async getCustomerProfile(customerProfileId = false) {
  64.         if (this.customerProfile) return this.customerProfile;
  65.  
  66.         const getRequest = new authorizenet.APIContracts.GetCustomerProfileRequest();
  67.         if (customerProfileId || this.user.customerProfileId) {
  68.             getRequest.setCustomerProfileId(customerProfileId || this.user.customerProfileId);
  69.         } else {
  70.             getRequest.setEmail(this.getCustomerEmail());
  71.         }
  72.  
  73.         getRequest.setMerchantAuthentication(this.merchantAuthenticationType);
  74.         const ctrl = new authorizenet.APIControllers.GetCustomerProfileController(getRequest.getJSON());
  75.         ctrl.setEnvironment("https://api.authorize.net/xml/v1/request.api");
  76.  
  77.         const responseCustomer = await this.requestAuthorize(ctrl);
  78.         this.customerProfile = responseCustomer.profile || false;
  79.  
  80.         return this.customerProfile;
  81.     }
  82.  
  83.     async validatePaymentMethod(customerPaymentProfileId, cvv) {
  84.         console.log('BEFORE CUST');
  85.         const customerProfile = await this.getCustomerProfile();
  86.         if (!customerProfile) return false;
  87.  
  88.         const validateRequest = new authorizenet.APIContracts.ValidateCustomerPaymentProfileRequest();
  89.         validateRequest.setMerchantAuthentication(this.merchantAuthenticationType);
  90.         validateRequest.setCustomerProfileId(customerProfile.customerProfileId);
  91.         validateRequest.setCustomerPaymentProfileId(customerPaymentProfileId);
  92.         validateRequest.setValidationMode(this.validationMode);
  93.         //validateRequest.setValidationMode(authorizenet.APIContracts.ValidationModeEnum.NONE);
  94.         validateRequest.setCardCode(cvv);
  95.         console.log('WTFFFFFFFF???????');
  96.  
  97.         const ctrl = new authorizenet.APIControllers.ValidateCustomerPaymentProfileController(validateRequest.getJSON());
  98.         ctrl.setEnvironment("https://api.authorize.net/xml/v1/request.api");
  99.  
  100.         const result = await this.requestAuthorize(ctrl);
  101.         if (this.isErrorAuthorize(result)) return this.loggingError(result);
  102.  
  103.         return result.messages.resultCode === authorizenet.APIContracts.MessageTypeEnum.OK;
  104.     }
  105.  
  106.     async getPaymentMethod(customerPaymentProfileId) {
  107.         const customerProfile = await this.getCustomerProfile();
  108.         if (!customerProfile) return false;
  109.  
  110.         const getRequest = new authorizenet.APIContracts.GetCustomerPaymentProfileRequest();
  111.         getRequest.setMerchantAuthentication(this.merchantAuthenticationType);
  112.         getRequest.setCustomerProfileId(customerProfile.customerProfileId);
  113.         getRequest.setCustomerPaymentProfileId(customerPaymentProfileId);
  114.  
  115.         const ctrl = new authorizenet.APIControllers.GetCustomerProfileController(getRequest.getJSON());
  116.         ctrl.setEnvironment("https://api.authorize.net/xml/v1/request.api");
  117.  
  118.         const result = await this.requestAuthorize(ctrl);
  119.         if (this.isErrorAuthorize(result)) return this.loggingError(result);
  120.  
  121.         return result;
  122.     }
  123.  
  124.     async createOrGetProfileCustomer() {
  125.         let customer = await this.getCustomerProfile();
  126.  
  127.         if (!customer) {
  128.             const customerProfileType = new authorizenet.APIContracts.CustomerProfileType();
  129.             customerProfileType.setDescription(`UserID: ${this.user.id}, user email: ${this.user.email}`);
  130.             customerProfileType.setEmail(this.getCustomerEmail());
  131.  
  132.             const createRequest = new authorizenet.APIContracts.CreateCustomerProfileRequest();
  133.             createRequest.setProfile(customerProfileType);
  134.             createRequest.setMerchantAuthentication(this.merchantAuthenticationType);
  135.  
  136.             createRequest.setValidationMode(authorizenet.APIContracts.ValidationModeEnum.NONE);
  137.  
  138.             const ctrl = new authorizenet.APIControllers.CreateCustomerProfileController(createRequest.getJSON());
  139.             ctrl.setEnvironment("https://api.authorize.net/xml/v1/request.api");
  140.  
  141.             const result = await this.requestAuthorize(ctrl);
  142.             if (this.isErrorAuthorize(result)) return this.loggingError(result);
  143.  
  144.             console.log('BEFORE CUST', result);
  145.             customer = await this.getCustomerProfile(result.customerProfileId);
  146.         }
  147.  
  148.         if (!this.user.customerProfileId || this.user.customerProfileId !== customer.customerProfileId) {
  149.             await this.user.update({ customerProfileId: customer.customerProfileId });
  150.         }
  151.  
  152.         return customer;
  153.     }
  154.  
  155.     async deleteCustomerPaymentProfile(customerPaymentProfileId) {
  156.         const customerProfile = await this.createOrGetProfileCustomer();
  157.         if (!customerProfile) return false;
  158.  
  159.         const deleteRequest = new authorizenet.APIContracts.DeleteCustomerPaymentProfileRequest();
  160.         deleteRequest.setMerchantAuthentication(this.merchantAuthenticationType);
  161.         deleteRequest.setCustomerProfileId(customerProfile.customerProfileId);
  162.         deleteRequest.setCustomerPaymentProfileId(customerPaymentProfileId);
  163.         const ctrl = new authorizenet.APIControllers.DeleteCustomerPaymentProfileController(deleteRequest.getJSON());
  164.         ctrl.setEnvironment("https://api.authorize.net/xml/v1/request.api");
  165.         const result = await this.requestAuthorize(ctrl);
  166.         if (this.isErrorAuthorize(result)) return this.loggingError(result);
  167.  
  168.         return result;
  169.     }
  170.  
  171.     generationCustomerAddress() {
  172.         const customerAddress = new authorizenet.APIContracts.CustomerAddressType();
  173.         customerAddress.setFirstName(this.user.first_name || 'John');
  174.         customerAddress.setLastName(this.user.lastName || 'John');
  175.  
  176.         customerAddress.setAddress('');
  177.         customerAddress.setCity('');
  178.         customerAddress.setCity('');
  179.         customerAddress.setCountry('');
  180.         customerAddress.setZip('');
  181.  
  182.         // customerAddress.setAddress(randomStreetNumber + ' Main Street');
  183.         // customerAddress.setCity('Bellevue');
  184.         // customerAddress.setState('WA');
  185.         // customerAddress.setZip('98004');
  186.         // customerAddress.setCountry('USA');
  187.         // customerAddress.setPhoneNumber('000-000-0000');
  188.  
  189.         return customerAddress;
  190.     }
  191.  
  192.     // Create card if not exists
  193.     async createCreditCard(data = {}) {
  194.         const customerProfile = await this.createOrGetProfileCustomer();
  195.         if (!customerProfile) return false;
  196.         const isDefault = data.isDefault || false;
  197.  
  198.         const creditCard = new authorizenet.APIContracts.CreditCardType();
  199.         creditCard.setCardNumber(data.cardNumber);
  200.         creditCard.setExpirationDate(`${data.expMonth}${data.expYear}`);
  201.         creditCard.setCardCode(data.cardCode);
  202.  
  203.         const paymentType = new authorizenet.APIContracts.PaymentType();
  204.         paymentType.setCreditCard(creditCard);
  205.  
  206.         const customerAddress = this.generationCustomerAddress();
  207.  
  208.         const profile = new authorizenet.APIContracts.CustomerPaymentProfileType();
  209.         profile.setBillTo(customerAddress);
  210.         profile.setPayment(paymentType);
  211.         profile.setDefaultPaymentProfile(isDefault);
  212.  
  213.         const createRequest = new authorizenet.APIContracts.CreateCustomerPaymentProfileRequest();
  214.         createRequest.setMerchantAuthentication(this.merchantAuthenticationType);
  215.         createRequest.setCustomerProfileId(customerProfile.customerProfileId);
  216.         createRequest.setPaymentProfile(profile);
  217.  
  218.         const ctrl = new authorizenet.APIControllers.CreateCustomerPaymentProfileController(createRequest.getJSON());
  219.         ctrl.setEnvironment("https://api.authorize.net/xml/v1/request.api");
  220.         const result = await this.requestAuthorize(ctrl);
  221.  
  222.         if (!result.customerPaymentProfileId && this.isErrorAuthorize(result)) return this.loggingError(result);
  223.         const paymentMethod = await this.getPaymentMethod(result.customerPaymentProfileId);
  224.         if (!paymentMethod) return false;
  225.  
  226.         const isValidPayment = await this.validatePaymentMethod(paymentMethod.paymentProfile.customerPaymentProfileId, data.cardCode);
  227.         if (!isValidPayment) {
  228.             console.log('DELETE???');
  229.             await this.deleteCustomerPaymentProfile(paymentMethod.paymentProfile.customerPaymentProfileId);
  230.             return false;
  231.         }
  232.  
  233.         let paymentCard = await PaymentCard.findOne({ where: { paymentId: paymentMethod.paymentProfile.customerPaymentProfileId } });
  234.  
  235.         if (!paymentCard) {
  236.             paymentCard = await PaymentCard.create({
  237.                 userId: this.user.id,
  238.                 is_default: isDefault,
  239.                 exp_month: data.expMonth,
  240.                 exp_year: data.expYear,
  241.                 last4: utils.parseCardNumber(paymentMethod.paymentProfile.payment.creditCard.cardNumber),
  242.                 brand: paymentMethod.paymentProfile.payment.creditCard.cardType,
  243.                 fingerprint: paymentMethod.paymentProfile.customerPaymentProfileId,
  244.                 paymentId: paymentMethod.paymentProfile.customerPaymentProfileId,
  245.                 paymentSystem: this.paymentSystem,
  246.                 country: null
  247.             });
  248.         }
  249.  
  250.         if (isDefault) await paymentModule.setCardDefault(this.user.id, paymentCard.id);
  251.  
  252.         return _.pick(paymentCard || {}, permissinFields.cardAttributes);;
  253.     }
  254.  
  255.     async updatePaymentMethod(customerPaymentProfileId, data) {
  256.         const customerProfile = await this.createOrGetProfileCustomer();
  257.         if (!customerProfile) return false;
  258.  
  259.         const paymentMethod = await this.getPaymentMethod(customerPaymentProfileId);
  260.         if (!paymentMethod) return false;
  261.  
  262.         const creditCardForUpdate = new authorizenet.APIContracts.CreditCardType();
  263.         creditCardForUpdate.setCardNumber(data.cardNumber);
  264.         creditCardForUpdate.setExpirationDate(`${data.expMonth}${data.expYear}`);
  265.  
  266.         const paymentType = new authorizenet.APIContracts.PaymentType();
  267.         paymentType.setCreditCard(creditCardForUpdate);
  268.         const customerForUpdate = new authorizenet.APIContracts.CustomerPaymentProfileExType();
  269.         customerForUpdate.setPayment(paymentType);
  270.         customerForUpdate.setCustomerPaymentProfileId(paymentMethod.paymentProfile.customerPaymentProfileId);
  271.         const updateRequest = new authorizenet.APIContracts.UpdateCustomerPaymentProfileRequest();
  272.  
  273.         updateRequest.setMerchantAuthentication(this.merchantAuthenticationType);
  274.         updateRequest.setCustomerProfileId(customerProfile.customerProfileId);
  275.         updateRequest.setPaymentProfile(customerForUpdate);
  276.         updateRequest.setValidationMode(this.validationMode);
  277.  
  278.         const ctrl = new authorizenet.APIControllers.UpdateCustomerPaymentProfileController(updateRequest.getJSON());
  279.         const result = await this.requestAuthorize(ctrl);
  280.  
  281.         if (!result.customerPaymentProfileId && this.isErrorAuthorize(result)) return this.loggingError(result);
  282.         const paymentCard = await PaymentCard.findOne({
  283.             where: {
  284.                 paymentId: paymentMethod.paymentProfile.customerPaymentProfileId
  285.             }
  286.         });
  287.  
  288.         if (paymentCard) {
  289.             await paymentCard.update({
  290.                 exp_month: data.expMonth,
  291.                 exp_year: data.expYear,
  292.                 last4: utils.parseCardNumber(data.cardNumber)
  293.             });
  294.         }
  295.  
  296.         return _.pick(paymentCard || {}, permissinFields.cardAttributes);
  297.     }
  298.  
  299.     async cancelSubscription(subscriptionId) {
  300.         const cancelRequest = new authorizenet.APIContracts.ARBCancelSubscriptionRequest();
  301.         cancelRequest.setMerchantAuthentication(this.merchantAuthenticationType);
  302.         cancelRequest.setSubscriptionId(subscriptionId);
  303.  
  304.         const ctrl = new authorizenet.APIControllers.ARBCancelSubscriptionController(cancelRequest.getJSON());
  305.         const result = await this.requestAuthorize(ctrl);
  306.         if (!result.customerPaymentProfileId && this.isErrorAuthorize(result)) return this.loggingError(result);
  307.         return result;
  308.     }
  309.  
  310.     async getSubscribtionStatus(subscriptionId) {
  311.         const getRequest = new authorizenet.APIContracts.ARBGetSubscriptionStatusRequest();
  312.         getRequest.setMerchantAuthentication(this.merchantAuthenticationType);
  313.         getRequest.setSubscriptionId(subscriptionId);
  314.  
  315.         const ctrl = new authorizenet.APIControllers.ARBGetSubscriptionStatusController(getRequest.getJSON());
  316.         const result = await this.requestAuthorize(ctrl);
  317.         if (!result.customerPaymentProfileId && this.isErrorAuthorize(result)) return this.loggingError(result);
  318.  
  319.         return result;
  320.     }
  321.  
  322.     async createSubscription(card, plan) {
  323.         const customerProfile = await this.createOrGetProfileCustomer();
  324.         if (!customerProfile) return false;
  325.  
  326.         const paymentMethod = await this.getPaymentMethod(card.paymentId);
  327.         if (!paymentMethod) return false;
  328.  
  329.         const sub = await this.getSubscribtion(this.user.authorizeSubscriptionId);
  330.         if (this.user.authorizeSubscriptionId && sub) {
  331.             const canceled = await this.cancelSubscription(this.user.authorizeSubscriptionId);
  332.             if (this.isErrorAuthorize(canceled)) return this.loggingError(canceled);
  333.  
  334.             await this.user.update({ authorizeSubscriptionId: null });
  335.         }
  336.  
  337.         const result = await this.createNewSubscriptionByPlan(plan, paymentMethod);
  338.         if (!result.customerPaymentProfileId && this.isErrorAuthorize(result)) return this.loggingError(result);
  339.  
  340.         await this.user.update({
  341.             authorizeSubscriptionId: result.subscriptionId,
  342.             plan: plan.id
  343.         });
  344.  
  345.         await this.user.increment('credits', { by: plan.credits });
  346.         return result;
  347.     }
  348.  
  349.     async getAllSubscribes() {
  350.         const refId = utils.uuidv4().substring(0, 6);
  351.  
  352.         const sorting = new authorizenet.APIContracts.ARBGetSubscriptionListSorting();
  353.         sorting.setOrderDescending(true);
  354.         sorting.setOrderBy(authorizenet.APIContracts.ARBGetSubscriptionListOrderFieldEnum.CREATETIMESTAMPUTC);
  355.  
  356.         const paging = new authorizenet.APIContracts.Paging();
  357.         paging.setOffset(1);
  358.         paging.setLimit(100);
  359.  
  360.         const listRequest = new authorizenet.APIContracts.ARBGetSubscriptionListRequest();
  361.         listRequest.setMerchantAuthentication(this.merchantAuthenticationType);
  362.  
  363.         listRequest.setRefId(refId);
  364.         listRequest.setSearchType(authorizenet.APIContracts.ARBGetSubscriptionListSearchTypeEnum.SUBSCRIPTIONACTIVE);
  365.         listRequest.setSorting(sorting);
  366.         listRequest.setPaging(paging);
  367.  
  368.         const ctrl = new authorizenet.APIControllers.ARBGetSubscriptionListController(listRequest.getJSON());
  369.         const result = await this.requestAuthorize(ctrl);
  370.         if (!result.customerPaymentProfileId && this.isErrorAuthorize(result)) return this.loggingError(result);
  371.  
  372.         return result;
  373.     }
  374.  
  375.     async createNewSubscriptionByPlan(plan, paymentMethod) {
  376.         const customerProfile = await this.createOrGetProfileCustomer();
  377.         if (!customerProfile) return false;
  378.  
  379.         const interval = new authorizenet.APIContracts.PaymentScheduleType.Interval();
  380.         interval.setLength(1);
  381.         interval.setUnit(authorizenet.APIContracts.ARBSubscriptionUnitEnum.MONTHS);
  382.  
  383.         const paymentScheduleType = new authorizenet.APIContracts.PaymentScheduleType();
  384.         paymentScheduleType.setInterval(interval);
  385.         paymentScheduleType.setStartDate(moment().format('YYYY-MM-DD'));
  386.         paymentScheduleType.setTotalOccurrences(12);
  387.  
  388.         const customerProfileIdType = new authorizenet.APIContracts.CustomerProfileIdType();
  389.         customerProfileIdType.setCustomerProfileId(customerProfile.customerProfileId);
  390.         customerProfileIdType.setCustomerPaymentProfileId(paymentMethod.paymentProfile.customerPaymentProfileId);
  391.  
  392.         const arbSubscription = new authorizenet.APIContracts.ARBSubscriptionType();
  393.         arbSubscription.setName(plan.name);
  394.         arbSubscription.setPaymentSchedule(paymentScheduleType);
  395.         arbSubscription.setAmount(plan.price);
  396.         arbSubscription.setProfile(customerProfileIdType);
  397.  
  398.         const createRequest = new authorizenet.APIContracts.ARBCreateSubscriptionRequest();
  399.         createRequest.setMerchantAuthentication(this.merchantAuthenticationType);
  400.         createRequest.setSubscription(arbSubscription);
  401.  
  402.         const ctrl = new authorizenet.APIControllers.ARBCreateSubscriptionController(createRequest.getJSON());
  403.         const result = await this.requestAuthorize(ctrl);
  404.         if (!result.customerPaymentProfileId && this.isErrorAuthorize(result)) return this.loggingError(result);
  405.  
  406.         return result;
  407.     }
  408.  
  409.     async getSubscribtion(subscriptionId) {
  410.         const getRequest = new authorizenet.APIContracts.ARBGetSubscriptionRequest();
  411.         getRequest.setMerchantAuthentication(this.merchantAuthenticationType);
  412.         getRequest.setSubscriptionId(subscriptionId);
  413.         const ctrl = new authorizenet.APIControllers.ARBGetSubscriptionController(getRequest.getJSON());
  414.         const result = await this.requestAuthorize(ctrl);
  415.         if (!result.customerPaymentProfileId && this.isErrorAuthorize(result)) return this.loggingError(result);
  416.  
  417.         return result;
  418.     }
  419. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement