Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const authorizenet = require('authorizenet');
- const config = require('../config');
- const utils = require('../utils');
- const PaymentCard = require('../models/PaymentCard');
- const paymentModule = require('../modules/payments');
- const permissinFields = require('../helpers/permissinFields');
- const _ = require('lodash');
- const moment = require('moment');
- module.exports = class {
- constructor(user) {
- this.paymentSystem = 'Authorize.Net';
- const merchantAuthenticationType = new authorizenet.APIContracts.MerchantAuthenticationType();
- merchantAuthenticationType.setName(config.authorize_net_apiLoginID);
- merchantAuthenticationType.setTransactionKey(config.authorize_net_transactionKey);
- this.merchantAuthenticationType = merchantAuthenticationType;
- this.user = user;
- this.validationMode = authorizenet.APIContracts.ValidationModeEnum.TESTMODE;
- if (config.authorize_net_mode === 'LIVE') {
- this.validationMode = authorizenet.APIContracts.ValidationModeEnum.LIVEMODE;
- }
- console.log('CONSOLE>', this.validationMode);
- this.errors = [];
- }
- generateErrorResponse(def = '') {
- if ((this.errors || []).filter(text => Boolean((text || '').trim())).length) {
- return this.errors;
- }
- //if(this.errors.length) return this.errors;
- return def;
- }
- loggingError(error) {
- console.error('Authorizenet error: ', JSON.stringify(error));
- if (error && error.messages) {
- //this.errors = error.messages.message || [];
- this.errors = (error.messages.message || []).map(msg => msg.text);
- }
- return false;
- }
- isErrorAuthorize(response) {
- return response.messages && response.messages.resultCode === authorizenet.APIContracts.MessageTypeEnum.ERROR;
- }
- requestAuthorize(authorizeRequest) {
- return new Promise(resolve => authorizeRequest.execute(() => resolve(authorizeRequest.getResponse())));
- }
- getCustomerEmail() {
- //return `1aikit_user_${this.user.id}@${config.domainName}`;
- return `${utils.uuidv4()}${this.user.id}@${config.domainName}`;
- }
- async getCustomerProfile(customerProfileId = false) {
- if (this.customerProfile) return this.customerProfile;
- const getRequest = new authorizenet.APIContracts.GetCustomerProfileRequest();
- if (customerProfileId || this.user.customerProfileId) {
- getRequest.setCustomerProfileId(customerProfileId || this.user.customerProfileId);
- } else {
- getRequest.setEmail(this.getCustomerEmail());
- }
- getRequest.setMerchantAuthentication(this.merchantAuthenticationType);
- const ctrl = new authorizenet.APIControllers.GetCustomerProfileController(getRequest.getJSON());
- ctrl.setEnvironment("https://api.authorize.net/xml/v1/request.api");
- const responseCustomer = await this.requestAuthorize(ctrl);
- this.customerProfile = responseCustomer.profile || false;
- return this.customerProfile;
- }
- async validatePaymentMethod(customerPaymentProfileId, cvv) {
- console.log('BEFORE CUST');
- const customerProfile = await this.getCustomerProfile();
- if (!customerProfile) return false;
- const validateRequest = new authorizenet.APIContracts.ValidateCustomerPaymentProfileRequest();
- validateRequest.setMerchantAuthentication(this.merchantAuthenticationType);
- validateRequest.setCustomerProfileId(customerProfile.customerProfileId);
- validateRequest.setCustomerPaymentProfileId(customerPaymentProfileId);
- validateRequest.setValidationMode(this.validationMode);
- //validateRequest.setValidationMode(authorizenet.APIContracts.ValidationModeEnum.NONE);
- validateRequest.setCardCode(cvv);
- console.log('WTFFFFFFFF???????');
- const ctrl = new authorizenet.APIControllers.ValidateCustomerPaymentProfileController(validateRequest.getJSON());
- ctrl.setEnvironment("https://api.authorize.net/xml/v1/request.api");
- const result = await this.requestAuthorize(ctrl);
- if (this.isErrorAuthorize(result)) return this.loggingError(result);
- return result.messages.resultCode === authorizenet.APIContracts.MessageTypeEnum.OK;
- }
- async getPaymentMethod(customerPaymentProfileId) {
- const customerProfile = await this.getCustomerProfile();
- if (!customerProfile) return false;
- const getRequest = new authorizenet.APIContracts.GetCustomerPaymentProfileRequest();
- getRequest.setMerchantAuthentication(this.merchantAuthenticationType);
- getRequest.setCustomerProfileId(customerProfile.customerProfileId);
- getRequest.setCustomerPaymentProfileId(customerPaymentProfileId);
- const ctrl = new authorizenet.APIControllers.GetCustomerProfileController(getRequest.getJSON());
- ctrl.setEnvironment("https://api.authorize.net/xml/v1/request.api");
- const result = await this.requestAuthorize(ctrl);
- if (this.isErrorAuthorize(result)) return this.loggingError(result);
- return result;
- }
- async createOrGetProfileCustomer() {
- let customer = await this.getCustomerProfile();
- if (!customer) {
- const customerProfileType = new authorizenet.APIContracts.CustomerProfileType();
- customerProfileType.setDescription(`UserID: ${this.user.id}, user email: ${this.user.email}`);
- customerProfileType.setEmail(this.getCustomerEmail());
- const createRequest = new authorizenet.APIContracts.CreateCustomerProfileRequest();
- createRequest.setProfile(customerProfileType);
- createRequest.setMerchantAuthentication(this.merchantAuthenticationType);
- createRequest.setValidationMode(authorizenet.APIContracts.ValidationModeEnum.NONE);
- const ctrl = new authorizenet.APIControllers.CreateCustomerProfileController(createRequest.getJSON());
- ctrl.setEnvironment("https://api.authorize.net/xml/v1/request.api");
- const result = await this.requestAuthorize(ctrl);
- if (this.isErrorAuthorize(result)) return this.loggingError(result);
- console.log('BEFORE CUST', result);
- customer = await this.getCustomerProfile(result.customerProfileId);
- }
- if (!this.user.customerProfileId || this.user.customerProfileId !== customer.customerProfileId) {
- await this.user.update({ customerProfileId: customer.customerProfileId });
- }
- return customer;
- }
- async deleteCustomerPaymentProfile(customerPaymentProfileId) {
- const customerProfile = await this.createOrGetProfileCustomer();
- if (!customerProfile) return false;
- const deleteRequest = new authorizenet.APIContracts.DeleteCustomerPaymentProfileRequest();
- deleteRequest.setMerchantAuthentication(this.merchantAuthenticationType);
- deleteRequest.setCustomerProfileId(customerProfile.customerProfileId);
- deleteRequest.setCustomerPaymentProfileId(customerPaymentProfileId);
- const ctrl = new authorizenet.APIControllers.DeleteCustomerPaymentProfileController(deleteRequest.getJSON());
- ctrl.setEnvironment("https://api.authorize.net/xml/v1/request.api");
- const result = await this.requestAuthorize(ctrl);
- if (this.isErrorAuthorize(result)) return this.loggingError(result);
- return result;
- }
- generationCustomerAddress() {
- const customerAddress = new authorizenet.APIContracts.CustomerAddressType();
- customerAddress.setFirstName(this.user.first_name || 'John');
- customerAddress.setLastName(this.user.lastName || 'John');
- customerAddress.setAddress('');
- customerAddress.setCity('');
- customerAddress.setCity('');
- customerAddress.setCountry('');
- customerAddress.setZip('');
- // customerAddress.setAddress(randomStreetNumber + ' Main Street');
- // customerAddress.setCity('Bellevue');
- // customerAddress.setState('WA');
- // customerAddress.setZip('98004');
- // customerAddress.setCountry('USA');
- // customerAddress.setPhoneNumber('000-000-0000');
- return customerAddress;
- }
- // Create card if not exists
- async createCreditCard(data = {}) {
- const customerProfile = await this.createOrGetProfileCustomer();
- if (!customerProfile) return false;
- const isDefault = data.isDefault || false;
- const creditCard = new authorizenet.APIContracts.CreditCardType();
- creditCard.setCardNumber(data.cardNumber);
- creditCard.setExpirationDate(`${data.expMonth}${data.expYear}`);
- creditCard.setCardCode(data.cardCode);
- const paymentType = new authorizenet.APIContracts.PaymentType();
- paymentType.setCreditCard(creditCard);
- const customerAddress = this.generationCustomerAddress();
- const profile = new authorizenet.APIContracts.CustomerPaymentProfileType();
- profile.setBillTo(customerAddress);
- profile.setPayment(paymentType);
- profile.setDefaultPaymentProfile(isDefault);
- const createRequest = new authorizenet.APIContracts.CreateCustomerPaymentProfileRequest();
- createRequest.setMerchantAuthentication(this.merchantAuthenticationType);
- createRequest.setCustomerProfileId(customerProfile.customerProfileId);
- createRequest.setPaymentProfile(profile);
- const ctrl = new authorizenet.APIControllers.CreateCustomerPaymentProfileController(createRequest.getJSON());
- ctrl.setEnvironment("https://api.authorize.net/xml/v1/request.api");
- const result = await this.requestAuthorize(ctrl);
- if (!result.customerPaymentProfileId && this.isErrorAuthorize(result)) return this.loggingError(result);
- const paymentMethod = await this.getPaymentMethod(result.customerPaymentProfileId);
- if (!paymentMethod) return false;
- const isValidPayment = await this.validatePaymentMethod(paymentMethod.paymentProfile.customerPaymentProfileId, data.cardCode);
- if (!isValidPayment) {
- console.log('DELETE???');
- await this.deleteCustomerPaymentProfile(paymentMethod.paymentProfile.customerPaymentProfileId);
- return false;
- }
- let paymentCard = await PaymentCard.findOne({ where: { paymentId: paymentMethod.paymentProfile.customerPaymentProfileId } });
- if (!paymentCard) {
- paymentCard = await PaymentCard.create({
- userId: this.user.id,
- is_default: isDefault,
- exp_month: data.expMonth,
- exp_year: data.expYear,
- last4: utils.parseCardNumber(paymentMethod.paymentProfile.payment.creditCard.cardNumber),
- brand: paymentMethod.paymentProfile.payment.creditCard.cardType,
- fingerprint: paymentMethod.paymentProfile.customerPaymentProfileId,
- paymentId: paymentMethod.paymentProfile.customerPaymentProfileId,
- paymentSystem: this.paymentSystem,
- country: null
- });
- }
- if (isDefault) await paymentModule.setCardDefault(this.user.id, paymentCard.id);
- return _.pick(paymentCard || {}, permissinFields.cardAttributes);;
- }
- async updatePaymentMethod(customerPaymentProfileId, data) {
- const customerProfile = await this.createOrGetProfileCustomer();
- if (!customerProfile) return false;
- const paymentMethod = await this.getPaymentMethod(customerPaymentProfileId);
- if (!paymentMethod) return false;
- const creditCardForUpdate = new authorizenet.APIContracts.CreditCardType();
- creditCardForUpdate.setCardNumber(data.cardNumber);
- creditCardForUpdate.setExpirationDate(`${data.expMonth}${data.expYear}`);
- const paymentType = new authorizenet.APIContracts.PaymentType();
- paymentType.setCreditCard(creditCardForUpdate);
- const customerForUpdate = new authorizenet.APIContracts.CustomerPaymentProfileExType();
- customerForUpdate.setPayment(paymentType);
- customerForUpdate.setCustomerPaymentProfileId(paymentMethod.paymentProfile.customerPaymentProfileId);
- const updateRequest = new authorizenet.APIContracts.UpdateCustomerPaymentProfileRequest();
- updateRequest.setMerchantAuthentication(this.merchantAuthenticationType);
- updateRequest.setCustomerProfileId(customerProfile.customerProfileId);
- updateRequest.setPaymentProfile(customerForUpdate);
- updateRequest.setValidationMode(this.validationMode);
- const ctrl = new authorizenet.APIControllers.UpdateCustomerPaymentProfileController(updateRequest.getJSON());
- const result = await this.requestAuthorize(ctrl);
- if (!result.customerPaymentProfileId && this.isErrorAuthorize(result)) return this.loggingError(result);
- const paymentCard = await PaymentCard.findOne({
- where: {
- paymentId: paymentMethod.paymentProfile.customerPaymentProfileId
- }
- });
- if (paymentCard) {
- await paymentCard.update({
- exp_month: data.expMonth,
- exp_year: data.expYear,
- last4: utils.parseCardNumber(data.cardNumber)
- });
- }
- return _.pick(paymentCard || {}, permissinFields.cardAttributes);
- }
- async cancelSubscription(subscriptionId) {
- const cancelRequest = new authorizenet.APIContracts.ARBCancelSubscriptionRequest();
- cancelRequest.setMerchantAuthentication(this.merchantAuthenticationType);
- cancelRequest.setSubscriptionId(subscriptionId);
- const ctrl = new authorizenet.APIControllers.ARBCancelSubscriptionController(cancelRequest.getJSON());
- const result = await this.requestAuthorize(ctrl);
- if (!result.customerPaymentProfileId && this.isErrorAuthorize(result)) return this.loggingError(result);
- return result;
- }
- async getSubscribtionStatus(subscriptionId) {
- const getRequest = new authorizenet.APIContracts.ARBGetSubscriptionStatusRequest();
- getRequest.setMerchantAuthentication(this.merchantAuthenticationType);
- getRequest.setSubscriptionId(subscriptionId);
- const ctrl = new authorizenet.APIControllers.ARBGetSubscriptionStatusController(getRequest.getJSON());
- const result = await this.requestAuthorize(ctrl);
- if (!result.customerPaymentProfileId && this.isErrorAuthorize(result)) return this.loggingError(result);
- return result;
- }
- async createSubscription(card, plan) {
- const customerProfile = await this.createOrGetProfileCustomer();
- if (!customerProfile) return false;
- const paymentMethod = await this.getPaymentMethod(card.paymentId);
- if (!paymentMethod) return false;
- const sub = await this.getSubscribtion(this.user.authorizeSubscriptionId);
- if (this.user.authorizeSubscriptionId && sub) {
- const canceled = await this.cancelSubscription(this.user.authorizeSubscriptionId);
- if (this.isErrorAuthorize(canceled)) return this.loggingError(canceled);
- await this.user.update({ authorizeSubscriptionId: null });
- }
- const result = await this.createNewSubscriptionByPlan(plan, paymentMethod);
- if (!result.customerPaymentProfileId && this.isErrorAuthorize(result)) return this.loggingError(result);
- await this.user.update({
- authorizeSubscriptionId: result.subscriptionId,
- plan: plan.id
- });
- await this.user.increment('credits', { by: plan.credits });
- return result;
- }
- async getAllSubscribes() {
- const refId = utils.uuidv4().substring(0, 6);
- const sorting = new authorizenet.APIContracts.ARBGetSubscriptionListSorting();
- sorting.setOrderDescending(true);
- sorting.setOrderBy(authorizenet.APIContracts.ARBGetSubscriptionListOrderFieldEnum.CREATETIMESTAMPUTC);
- const paging = new authorizenet.APIContracts.Paging();
- paging.setOffset(1);
- paging.setLimit(100);
- const listRequest = new authorizenet.APIContracts.ARBGetSubscriptionListRequest();
- listRequest.setMerchantAuthentication(this.merchantAuthenticationType);
- listRequest.setRefId(refId);
- listRequest.setSearchType(authorizenet.APIContracts.ARBGetSubscriptionListSearchTypeEnum.SUBSCRIPTIONACTIVE);
- listRequest.setSorting(sorting);
- listRequest.setPaging(paging);
- const ctrl = new authorizenet.APIControllers.ARBGetSubscriptionListController(listRequest.getJSON());
- const result = await this.requestAuthorize(ctrl);
- if (!result.customerPaymentProfileId && this.isErrorAuthorize(result)) return this.loggingError(result);
- return result;
- }
- async createNewSubscriptionByPlan(plan, paymentMethod) {
- const customerProfile = await this.createOrGetProfileCustomer();
- if (!customerProfile) return false;
- const interval = new authorizenet.APIContracts.PaymentScheduleType.Interval();
- interval.setLength(1);
- interval.setUnit(authorizenet.APIContracts.ARBSubscriptionUnitEnum.MONTHS);
- const paymentScheduleType = new authorizenet.APIContracts.PaymentScheduleType();
- paymentScheduleType.setInterval(interval);
- paymentScheduleType.setStartDate(moment().format('YYYY-MM-DD'));
- paymentScheduleType.setTotalOccurrences(12);
- const customerProfileIdType = new authorizenet.APIContracts.CustomerProfileIdType();
- customerProfileIdType.setCustomerProfileId(customerProfile.customerProfileId);
- customerProfileIdType.setCustomerPaymentProfileId(paymentMethod.paymentProfile.customerPaymentProfileId);
- const arbSubscription = new authorizenet.APIContracts.ARBSubscriptionType();
- arbSubscription.setName(plan.name);
- arbSubscription.setPaymentSchedule(paymentScheduleType);
- arbSubscription.setAmount(plan.price);
- arbSubscription.setProfile(customerProfileIdType);
- const createRequest = new authorizenet.APIContracts.ARBCreateSubscriptionRequest();
- createRequest.setMerchantAuthentication(this.merchantAuthenticationType);
- createRequest.setSubscription(arbSubscription);
- const ctrl = new authorizenet.APIControllers.ARBCreateSubscriptionController(createRequest.getJSON());
- const result = await this.requestAuthorize(ctrl);
- if (!result.customerPaymentProfileId && this.isErrorAuthorize(result)) return this.loggingError(result);
- return result;
- }
- async getSubscribtion(subscriptionId) {
- const getRequest = new authorizenet.APIContracts.ARBGetSubscriptionRequest();
- getRequest.setMerchantAuthentication(this.merchantAuthenticationType);
- getRequest.setSubscriptionId(subscriptionId);
- const ctrl = new authorizenet.APIControllers.ARBGetSubscriptionController(getRequest.getJSON());
- const result = await this.requestAuthorize(ctrl);
- if (!result.customerPaymentProfileId && this.isErrorAuthorize(result)) return this.loggingError(result);
- return result;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement