RecurlyWrapper.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  1. const OError = require('@overleaf/o-error')
  2. const {
  3. fetchStringWithResponse,
  4. RequestFailedError,
  5. } = require('@overleaf/fetch-utils')
  6. const Settings = require('@overleaf/settings')
  7. const xml2js = require('xml2js')
  8. const logger = require('@overleaf/logger')
  9. const Errors = require('../Errors/Errors')
  10. const SubscriptionErrors = require('./Errors')
  11. const { callbackify } = require('@overleaf/promise-utils')
  12. /**
  13. * @param accountId
  14. * @param newEmail
  15. */
  16. async function updateAccountEmailAddress(accountId, newEmail) {
  17. const data = {
  18. email: newEmail,
  19. }
  20. let requestBody
  21. try {
  22. requestBody = RecurlyWrapper._buildXml('account', data)
  23. } catch (error) {
  24. throw OError.tag(error, 'error building xml', { accountId, newEmail })
  25. }
  26. const { body } = await RecurlyWrapper.promises.apiRequest({
  27. url: `accounts/${accountId}`,
  28. method: 'PUT',
  29. body: requestBody,
  30. })
  31. return await RecurlyWrapper.promises._parseAccountXml(body)
  32. }
  33. const promises = {
  34. _paypal: {
  35. async checkAccountExists(cache) {
  36. const { user } = cache
  37. logger.debug(
  38. { userId: user._id },
  39. 'checking if recurly account exists for user'
  40. )
  41. let response, body
  42. try {
  43. ;({ response, body } = await RecurlyWrapper.promises.apiRequest({
  44. url: `accounts/${user._id}`,
  45. method: 'GET',
  46. expect404: true,
  47. }))
  48. } catch (error) {
  49. OError.tag(
  50. error,
  51. 'error response from recurly while checking account',
  52. {
  53. user_id: user._id,
  54. }
  55. )
  56. throw error
  57. }
  58. if (response.status === 404) {
  59. // actually not an error in this case, just no existing account
  60. logger.debug(
  61. { userId: user._id },
  62. 'user does not currently exist in recurly, proceed'
  63. )
  64. cache.userExists = false
  65. return cache
  66. }
  67. logger.debug({ userId: user._id }, 'user appears to exist in recurly')
  68. try {
  69. const account = await RecurlyWrapper.promises._parseAccountXml(body)
  70. cache.userExists = true
  71. cache.account = account
  72. return cache
  73. } catch (err) {
  74. OError.tag(err, 'error parsing account', {
  75. user_id: user._id,
  76. })
  77. throw err
  78. }
  79. },
  80. async createAccount(cache) {
  81. const { user } = cache
  82. const { subscriptionDetails } = cache
  83. if (cache.userExists) {
  84. return cache
  85. }
  86. const address = getAddressFromSubscriptionDetails(
  87. subscriptionDetails,
  88. false
  89. )
  90. const data = {
  91. account_code: user._id,
  92. email: user.email,
  93. first_name: user.first_name,
  94. last_name: user.last_name,
  95. address,
  96. }
  97. let requestBody
  98. try {
  99. requestBody = RecurlyWrapper._buildXml('account', data)
  100. } catch (error) {
  101. throw OError.tag(error, 'error building xml', { user_id: user._id })
  102. }
  103. let body
  104. try {
  105. ;({ body } = await RecurlyWrapper.promises.apiRequest({
  106. url: 'accounts',
  107. method: 'POST',
  108. body: requestBody,
  109. }))
  110. } catch (error) {
  111. OError.tag(
  112. error,
  113. 'error response from recurly while creating account',
  114. { user_id: user._id }
  115. )
  116. throw error
  117. }
  118. try {
  119. cache.account = await RecurlyWrapper.promises._parseAccountXml(body)
  120. return cache
  121. } catch (err) {
  122. OError.tag(err, 'error creating account', {
  123. user_id: user._id,
  124. })
  125. throw err
  126. }
  127. },
  128. async createBillingInfo(cache) {
  129. const { user } = cache
  130. const { recurlyTokenIds } = cache
  131. logger.debug({ userId: user._id }, 'creating billing info in recurly')
  132. const accountCode = cache?.account?.account_code
  133. if (!accountCode) {
  134. throw new Error('no account code at createBillingInfo stage')
  135. }
  136. const data = { token_id: recurlyTokenIds.billing }
  137. let requestBody
  138. try {
  139. requestBody = RecurlyWrapper._buildXml('billing_info', data)
  140. } catch (error) {
  141. throw OError.tag(error, 'error building xml', { user_id: user._id })
  142. }
  143. let body
  144. try {
  145. ;({ body } = await RecurlyWrapper.promises.apiRequest({
  146. url: `accounts/${accountCode}/billing_info`,
  147. method: 'POST',
  148. body: requestBody,
  149. }))
  150. } catch (error) {
  151. OError.tag(
  152. error,
  153. 'error response from recurly while creating billing info',
  154. { user_id: user._id }
  155. )
  156. throw error
  157. }
  158. try {
  159. cache.billingInfo =
  160. await RecurlyWrapper.promises._parseBillingInfoXml(body)
  161. return cache
  162. } catch (err) {
  163. OError.tag(err, 'error creating billing info', {
  164. user_id: user._id,
  165. accountCode,
  166. })
  167. throw err
  168. }
  169. },
  170. async setAddressAndCompanyBillingInfo(cache) {
  171. const { user } = cache
  172. const { subscriptionDetails } = cache
  173. logger.debug(
  174. { userId: user._id },
  175. 'setting billing address and company info in recurly'
  176. )
  177. const accountCode = cache?.account?.account_code
  178. if (!accountCode) {
  179. throw new Error(
  180. 'no account code at setAddressAndCompanyBillingInfo stage'
  181. )
  182. }
  183. const addressAndCompanyBillingInfo = getAddressFromSubscriptionDetails(
  184. subscriptionDetails,
  185. true
  186. )
  187. let requestBody
  188. try {
  189. requestBody = RecurlyWrapper._buildXml(
  190. 'billing_info',
  191. addressAndCompanyBillingInfo
  192. )
  193. } catch (error) {
  194. throw OError.tag(error, 'error building xml', { user_id: user._id })
  195. }
  196. let body
  197. try {
  198. ;({ body } = await RecurlyWrapper.promises.apiRequest({
  199. url: `accounts/${accountCode}/billing_info`,
  200. method: 'PUT',
  201. body: requestBody,
  202. }))
  203. } catch (error) {
  204. OError.tag(error, 'error response from recurly while setting address', {
  205. user_id: user._id,
  206. })
  207. throw error
  208. }
  209. try {
  210. cache.billingInfo =
  211. await RecurlyWrapper.promises._parseBillingInfoXml(body)
  212. return cache
  213. } catch (err) {
  214. if (err) {
  215. OError.tag(err, 'error updating billing info', {
  216. user_id: user._id,
  217. })
  218. throw err
  219. }
  220. }
  221. },
  222. async createSubscription(cache) {
  223. const { user } = cache
  224. const { subscriptionDetails } = cache
  225. logger.debug({ userId: user._id }, 'creating subscription in recurly')
  226. const data = {
  227. plan_code: subscriptionDetails.plan_code,
  228. currency: subscriptionDetails.currencyCode,
  229. coupon_code: subscriptionDetails.coupon_code,
  230. account: {
  231. account_code: user._id,
  232. },
  233. }
  234. if (subscriptionDetails.subscription_add_ons) {
  235. data.subscription_add_ons = subscriptionDetails.subscription_add_ons
  236. }
  237. const customFields =
  238. getCustomFieldsFromSubscriptionDetails(subscriptionDetails)
  239. if (customFields) {
  240. data.custom_fields = customFields
  241. }
  242. let requestBody
  243. try {
  244. requestBody = RecurlyWrapper._buildXml('subscription', data)
  245. } catch (error) {
  246. throw OError.tag(error, 'error building xml', { user_id: user._id })
  247. }
  248. let body
  249. try {
  250. ;({ body } = await RecurlyWrapper.promises.apiRequest({
  251. url: 'subscriptions',
  252. method: 'POST',
  253. body: requestBody,
  254. }))
  255. } catch (error) {
  256. OError.tag(
  257. error,
  258. 'error response from recurly while creating subscription',
  259. { user_id: user._id }
  260. )
  261. throw error
  262. }
  263. try {
  264. cache.subscription =
  265. await RecurlyWrapper.promises._parseSubscriptionXml(body)
  266. return cache
  267. } catch (err) {
  268. OError.tag(err, 'error creating subscription', {
  269. user_id: user._id,
  270. })
  271. throw err
  272. }
  273. },
  274. },
  275. async _createPaypalSubscription(user, subscriptionDetails, recurlyTokenIds) {
  276. logger.debug(
  277. { userId: user._id },
  278. 'starting process of creating paypal subscription'
  279. )
  280. // We use waterfall through each of these actions in sequence
  281. // passing a `cache` object along the way. The cache is initialized
  282. // with required data, and `async.apply` to pass the cache to the first function
  283. const cache = { user, recurlyTokenIds, subscriptionDetails }
  284. let result
  285. try {
  286. result = await RecurlyWrapper.promises._paypal.checkAccountExists(cache)
  287. result = await RecurlyWrapper.promises._paypal.createAccount(result)
  288. result = await RecurlyWrapper.promises._paypal.createBillingInfo(result)
  289. result =
  290. await RecurlyWrapper.promises._paypal.setAddressAndCompanyBillingInfo(
  291. result
  292. )
  293. result = await RecurlyWrapper.promises._paypal.createSubscription(result)
  294. } catch (err) {
  295. OError.tag(err, 'error in paypal subscription creation process', {
  296. user_id: user._id,
  297. })
  298. throw err
  299. }
  300. if (!result.subscription) {
  301. const err = new Error('no subscription object in result')
  302. OError.tag(err, 'error in paypal subscription creation process', {
  303. user_id: user._id,
  304. })
  305. throw err
  306. }
  307. logger.debug(
  308. { userId: user._id },
  309. 'done creating paypal subscription for user'
  310. )
  311. return result.subscription
  312. },
  313. async _createCreditCardSubscription(
  314. user,
  315. subscriptionDetails,
  316. recurlyTokenIds
  317. ) {
  318. const data = {
  319. plan_code: subscriptionDetails.plan_code,
  320. currency: subscriptionDetails.currencyCode,
  321. coupon_code: subscriptionDetails.coupon_code,
  322. account: {
  323. account_code: user._id,
  324. email: user.email,
  325. first_name: subscriptionDetails.first_name || user.first_name,
  326. last_name: subscriptionDetails.last_name || user.last_name,
  327. billing_info: {
  328. token_id: recurlyTokenIds.billing,
  329. },
  330. },
  331. }
  332. if (recurlyTokenIds.threeDSecureActionResult) {
  333. data.account.billing_info.three_d_secure_action_result_token_id =
  334. recurlyTokenIds.threeDSecureActionResult
  335. }
  336. if (subscriptionDetails.subscription_add_ons) {
  337. data.subscription_add_ons = subscriptionDetails.subscription_add_ons
  338. }
  339. const customFields =
  340. getCustomFieldsFromSubscriptionDetails(subscriptionDetails)
  341. if (customFields) {
  342. data.custom_fields = customFields
  343. }
  344. let requestBody
  345. try {
  346. requestBody = RecurlyWrapper._buildXml('subscription', data)
  347. } catch (error) {
  348. throw OError.tag(error, 'error building xml', { user_id: user._id })
  349. }
  350. const { response, body } = await RecurlyWrapper.promises.apiRequest({
  351. url: 'subscriptions',
  352. method: 'POST',
  353. body: requestBody,
  354. expect422: true,
  355. })
  356. if (response.status === 422) {
  357. return await RecurlyWrapper.promises._handle422Response(body)
  358. } else {
  359. return await RecurlyWrapper.promises._parseSubscriptionXml(body)
  360. }
  361. },
  362. async createSubscription(user, subscriptionDetails, recurlyTokenIds) {
  363. const { isPaypal } = subscriptionDetails
  364. logger.debug(
  365. { userId: user._id, isPaypal },
  366. 'setting up subscription in recurly'
  367. )
  368. const fn = isPaypal
  369. ? RecurlyWrapper.promises._createPaypalSubscription
  370. : RecurlyWrapper.promises._createCreditCardSubscription
  371. return fn(user, subscriptionDetails, recurlyTokenIds)
  372. },
  373. /**
  374. * @param options - the options to pass to the request library
  375. * @returns {Promise<{ response: unknown, body: string}>}
  376. */
  377. async apiRequest({ expect404, expect422, url, qs, ...fetchOptions }) {
  378. const fetchUrl = new URL(RecurlyWrapper.apiUrl)
  379. fetchUrl.pathname =
  380. fetchUrl.pathname !== '/' ? `${fetchUrl.pathname}/${url}` : url
  381. if (qs) {
  382. for (const [key, value] of Object.entries(qs)) {
  383. fetchUrl.searchParams.set(key, value)
  384. }
  385. }
  386. fetchOptions.headers = {
  387. Authorization: `Basic ${Buffer.from(
  388. Settings.apis.recurly.apiKey
  389. ).toString('base64')}`,
  390. Accept: 'application/xml',
  391. 'Content-Type': 'application/xml; charset=utf-8',
  392. 'X-Api-Version': Settings.apis.recurly.apiVersion,
  393. }
  394. try {
  395. return await fetchStringWithResponse(fetchUrl, fetchOptions)
  396. } catch (error) {
  397. if (error instanceof RequestFailedError) {
  398. if (error.response.status === 404 && expect404) {
  399. return { response: error.response, body: null }
  400. } else if (error.response.status === 422 && expect422) {
  401. return { response: error.response, body: error.body }
  402. }
  403. if (fetchOptions.headers.Authorization) {
  404. fetchOptions.headers.Authorization = 'REDACTED'
  405. }
  406. logger.warn(
  407. {
  408. err: error,
  409. body: error.body,
  410. options: fetchOptions,
  411. url: fetchUrl.href,
  412. statusCode: error.response?.status,
  413. },
  414. 'error returned from recurly'
  415. )
  416. throw new OError(
  417. `Recurly API returned with status code: ${error.response.status}`,
  418. { statusCode: error.response.status }
  419. )
  420. } else {
  421. throw error
  422. }
  423. }
  424. },
  425. async getSubscriptions(accountId) {
  426. const { body } = await RecurlyWrapper.promises.apiRequest({
  427. url: `accounts/${accountId}/subscriptions`,
  428. })
  429. return await RecurlyWrapper.promises._parseXml(body)
  430. },
  431. async getSubscription(subscriptionId, options) {
  432. let url
  433. if (!options) {
  434. options = {}
  435. }
  436. if (options.recurlyJsResult) {
  437. url = `recurly_js/result/${subscriptionId}`
  438. } else {
  439. url = `subscriptions/${subscriptionId}`
  440. }
  441. const { body } = await RecurlyWrapper.promises.apiRequest({
  442. url,
  443. })
  444. const recurlySubscription =
  445. await RecurlyWrapper.promises._parseSubscriptionXml(body)
  446. if (options.includeAccount) {
  447. let accountId
  448. if (recurlySubscription.account && recurlySubscription.account.url) {
  449. accountId = recurlySubscription.account.url.match(/accounts\/(.*)/)[1]
  450. } else {
  451. throw new Error("I don't understand the response from Recurly")
  452. }
  453. recurlySubscription.account =
  454. await RecurlyWrapper.promises.getAccount(accountId)
  455. return recurlySubscription
  456. } else {
  457. return recurlySubscription
  458. }
  459. },
  460. /**
  461. * @typedef {{getNextPage: () => Promise<PageData>, items: any[]}} PageData
  462. */
  463. async getPaginatedEndpoint(resource, queryParams) {
  464. let allItems = []
  465. let items
  466. /** @type {() => Promise<PageData>} */
  467. let getNextPage = promises.getPaginatedEndpointIterator(
  468. resource,
  469. queryParams
  470. )
  471. while (getNextPage) {
  472. ;({ items, getNextPage } = await getNextPage())
  473. allItems = allItems.concat(items)
  474. logger.debug(`total now ${allItems.length}`)
  475. }
  476. return allItems
  477. },
  478. /**
  479. * @returns {() => Promise<PageData>}
  480. */
  481. getPaginatedEndpointIterator(resource, queryParams) {
  482. queryParams.per_page = queryParams.per_page || 200
  483. const getPage = async (cursor = null) => {
  484. const opts = {
  485. url: resource,
  486. qs: queryParams,
  487. }
  488. if (cursor) {
  489. opts.qs.cursor = cursor
  490. }
  491. const { response, body } = await RecurlyWrapper.promises.apiRequest(opts)
  492. const data = await RecurlyWrapper.promises._parseXml(body)
  493. const items = data[resource]
  494. logger.debug(`got ${items.length} items in this page`)
  495. const match = response.headers.link?.match(/cursor=([0-9.]+%3A[0-9.]+)&/)
  496. const nextCursor = match && match[1]
  497. return {
  498. items,
  499. getNextPage:
  500. nextCursor && (() => getPage(decodeURIComponent(nextCursor))),
  501. }
  502. }
  503. return getPage
  504. },
  505. async getAccount(accountId) {
  506. const { body } = await RecurlyWrapper.promises.apiRequest({
  507. url: `accounts/${accountId}`,
  508. })
  509. return await RecurlyWrapper.promises._parseAccountXml(body)
  510. },
  511. updateAccountEmailAddress,
  512. async getAccountActiveCoupons(accountId) {
  513. const { body } = await RecurlyWrapper.promises.apiRequest({
  514. url: `accounts/${accountId}/redemptions`,
  515. })
  516. const redemptions = await RecurlyWrapper.promises._parseRedemptionsXml(body)
  517. const activeRedemptions = redemptions.filter(
  518. redemption => redemption.state === 'active'
  519. )
  520. const couponCodes = activeRedemptions.map(
  521. redemption => redemption.coupon_code
  522. )
  523. return await Promise.all(
  524. couponCodes.map(couponCode =>
  525. RecurlyWrapper.promises.getCoupon(couponCode)
  526. )
  527. )
  528. },
  529. async getCoupon(couponCode) {
  530. const opts = { url: `coupons/${couponCode}` }
  531. const { body } = await RecurlyWrapper.promises.apiRequest(opts)
  532. return await RecurlyWrapper.promises._parseCouponXml(body)
  533. },
  534. async getBillingInfo(accountId) {
  535. const { body } = await RecurlyWrapper.promises.apiRequest({
  536. url: `accounts/${accountId}/billing_info`,
  537. })
  538. return await RecurlyWrapper.promises._parseXml(body)
  539. },
  540. async getAccountPastDueInvoices(accountId) {
  541. const { body } = await RecurlyWrapper.promises.apiRequest({
  542. url: `accounts/${accountId}/invoices`,
  543. qs: { state: 'past_due' },
  544. })
  545. return await RecurlyWrapper.promises._parseInvoicesXml(body)
  546. },
  547. async attemptInvoiceCollection(invoiceId) {
  548. return await RecurlyWrapper.promises.apiRequest({
  549. url: `invoices/${invoiceId}/collect`,
  550. method: 'PUT',
  551. })
  552. },
  553. async updateSubscription(subscriptionId, options) {
  554. logger.debug(
  555. { subscriptionId, options },
  556. 'telling recurly to update subscription'
  557. )
  558. const data = {
  559. plan_code: options.plan_code,
  560. timeframe: options.timeframe,
  561. }
  562. let requestBody
  563. try {
  564. requestBody = RecurlyWrapper._buildXml('subscription', data)
  565. } catch (error) {
  566. throw OError.tag(error, 'error building xml', { subscriptionId })
  567. }
  568. const { body } = await RecurlyWrapper.promises.apiRequest({
  569. url: `subscriptions/${subscriptionId}`,
  570. method: 'PUT',
  571. body: requestBody,
  572. })
  573. return await RecurlyWrapper.promises._parseSubscriptionXml(body)
  574. },
  575. async createFixedAmountCoupon(
  576. couponCode,
  577. name,
  578. currencyCode,
  579. discountInCents,
  580. planCode
  581. ) {
  582. const data = {
  583. coupon_code: couponCode,
  584. name,
  585. discount_type: 'dollars',
  586. discount_in_cents: {},
  587. plan_codes: {
  588. plan_code: planCode,
  589. },
  590. applies_to_all_plans: false,
  591. }
  592. data.discount_in_cents[currencyCode] = discountInCents
  593. let requestBody
  594. try {
  595. requestBody = RecurlyWrapper._buildXml('coupon', data)
  596. } catch (error) {
  597. throw OError.tag(error, 'error building xml', {
  598. couponCode,
  599. name,
  600. })
  601. }
  602. logger.debug({ couponCode, requestBody }, 'creating coupon')
  603. try {
  604. await RecurlyWrapper.promises.apiRequest({
  605. url: 'coupons',
  606. method: 'POST',
  607. body: requestBody,
  608. })
  609. } catch (error) {
  610. logger.warn({ err: error, couponCode }, 'error creating coupon')
  611. throw error
  612. }
  613. },
  614. async lookupCoupon(couponCode) {
  615. const { body } = await RecurlyWrapper.promises.apiRequest({
  616. url: `coupons/${couponCode}`,
  617. })
  618. return await RecurlyWrapper.promises._parseCouponXml(body)
  619. },
  620. async redeemCoupon(accountCode, couponCode) {
  621. const data = {
  622. account_code: accountCode,
  623. currency: 'USD',
  624. }
  625. let requestBody
  626. try {
  627. requestBody = RecurlyWrapper._buildXml('redemption', data)
  628. } catch (error) {
  629. throw OError.tag(error, 'error building xml', {
  630. accountCode,
  631. couponCode,
  632. })
  633. }
  634. logger.debug(
  635. { accountCode, couponCode, requestBody },
  636. 'redeeming coupon for user'
  637. )
  638. try {
  639. await RecurlyWrapper.promises.apiRequest({
  640. url: `coupons/${couponCode}/redeem`,
  641. method: 'POST',
  642. body: requestBody,
  643. })
  644. } catch (error) {
  645. logger.warn(
  646. { err: error, accountCode, couponCode },
  647. 'error redeeming coupon'
  648. )
  649. throw error
  650. }
  651. },
  652. async extendTrial(subscriptionId, daysUntilExpire) {
  653. if (daysUntilExpire == null) {
  654. daysUntilExpire = 7
  655. }
  656. const nextRenewalDate = new Date()
  657. nextRenewalDate.setDate(nextRenewalDate.getDate() + daysUntilExpire)
  658. logger.debug(
  659. { subscriptionId, daysUntilExpire },
  660. 'Exending Free trial for user'
  661. )
  662. try {
  663. await RecurlyWrapper.promises.apiRequest({
  664. url: `subscriptions/${subscriptionId}/postpone`,
  665. qs: { bulk: false, next_bill_date: nextRenewalDate },
  666. method: 'PUT',
  667. })
  668. } catch (error) {
  669. logger.warn(
  670. { err: error, subscriptionId, daysUntilExpire },
  671. 'error extending trial'
  672. )
  673. throw error
  674. }
  675. },
  676. async listAccountActiveSubscriptions(accountId) {
  677. const { response, body } = await RecurlyWrapper.promises.apiRequest({
  678. url: `accounts/${accountId}/subscriptions`,
  679. qs: {
  680. state: 'active',
  681. },
  682. expect404: true,
  683. })
  684. if (response.status === 404) {
  685. return []
  686. } else {
  687. return await RecurlyWrapper.promises._parseSubscriptionsXml(body)
  688. }
  689. },
  690. async _handle422Response(body) {
  691. const data = await RecurlyWrapper.promises._parseErrorsXml(body)
  692. let errorData = {}
  693. if (data.transaction_error) {
  694. errorData = {
  695. message: data.transaction_error.merchant_message,
  696. info: {
  697. category: data.transaction_error.error_category,
  698. gatewayCode: data.transaction_error.gateway_error_code,
  699. public: {
  700. code: data.transaction_error.error_code,
  701. message: data.transaction_error.customer_message,
  702. },
  703. },
  704. }
  705. if (data.transaction_error.three_d_secure_action_token_id) {
  706. errorData.info.public.threeDSecureActionTokenId =
  707. data.transaction_error.three_d_secure_action_token_id
  708. }
  709. } else if (data.error && data.error._) {
  710. // fallback for errors that don't have a `transaction_error` field, but
  711. // instead a `error` field with a message (e.g. VATMOSS errors)
  712. errorData = {
  713. info: {
  714. public: {
  715. message: data.error._,
  716. },
  717. },
  718. }
  719. }
  720. throw new SubscriptionErrors.RecurlyTransactionError(errorData)
  721. },
  722. async _parseSubscriptionsXml(xml) {
  723. return await RecurlyWrapper.promises._parseXmlAndGetAttribute(
  724. xml,
  725. 'subscriptions'
  726. )
  727. },
  728. async _parseSubscriptionXml(xml) {
  729. return await RecurlyWrapper.promises._parseXmlAndGetAttribute(
  730. xml,
  731. 'subscription'
  732. )
  733. },
  734. async _parseAccountXml(xml) {
  735. return await RecurlyWrapper.promises._parseXmlAndGetAttribute(
  736. xml,
  737. 'account'
  738. )
  739. },
  740. async _parseBillingInfoXml(xml) {
  741. return await RecurlyWrapper.promises._parseXmlAndGetAttribute(
  742. xml,
  743. 'billing_info'
  744. )
  745. },
  746. async _parseRedemptionsXml(xml) {
  747. return await RecurlyWrapper.promises._parseXmlAndGetAttribute(
  748. xml,
  749. 'redemptions'
  750. )
  751. },
  752. async _parseCouponXml(xml) {
  753. return await RecurlyWrapper.promises._parseXmlAndGetAttribute(xml, 'coupon')
  754. },
  755. async _parseErrorsXml(xml) {
  756. return await RecurlyWrapper.promises._parseXmlAndGetAttribute(xml, 'errors')
  757. },
  758. async _parseInvoicesXml(xml) {
  759. return await RecurlyWrapper.promises._parseXmlAndGetAttribute(
  760. xml,
  761. 'invoices'
  762. )
  763. },
  764. async _parseXmlAndGetAttribute(xml, attribute) {
  765. const data = await RecurlyWrapper.promises._parseXml(xml)
  766. if (data && data[attribute] != null) {
  767. return data[attribute]
  768. } else {
  769. throw new Error("I don't understand the response from Recurly")
  770. }
  771. },
  772. /**
  773. * @param xml
  774. */
  775. _parseXml(xml) {
  776. function convertDataTypes(data) {
  777. let key, value
  778. if (data && data.$) {
  779. if (data.$.nil === 'nil') {
  780. data = null
  781. } else if (data.$.href) {
  782. data.url = data.$.href
  783. delete data.$
  784. } else if (data.$.type === 'integer') {
  785. data = parseInt(data._, 10)
  786. } else if (data.$.type === 'datetime') {
  787. data = new Date(data._)
  788. } else if (data.$.type === 'array') {
  789. delete data.$
  790. let array = []
  791. for (key in data) {
  792. value = data[key]
  793. if (value instanceof Array) {
  794. array = array.concat(convertDataTypes(value))
  795. } else {
  796. array.push(convertDataTypes(value))
  797. }
  798. }
  799. data = array
  800. }
  801. }
  802. if (data instanceof Array) {
  803. data = data.map(entry => convertDataTypes(entry))
  804. } else if (typeof data === 'object') {
  805. for (key in data) {
  806. value = data[key]
  807. data[key] = convertDataTypes(value)
  808. }
  809. }
  810. return data
  811. }
  812. const parser = new xml2js.Parser({
  813. explicitRoot: true,
  814. explicitArray: false,
  815. emptyTag: '',
  816. })
  817. return new Promise((resolve, reject) =>
  818. parser.parseString(xml, function (error, data) {
  819. if (error) {
  820. return reject(error)
  821. }
  822. const result = convertDataTypes(data)
  823. resolve(result)
  824. })
  825. )
  826. },
  827. }
  828. function _buildXml(rootName, data) {
  829. const options = {
  830. headless: true,
  831. renderOpts: {
  832. pretty: true,
  833. indent: '\t',
  834. },
  835. rootName,
  836. }
  837. const builder = new xml2js.Builder(options)
  838. return builder.buildObject(data)
  839. }
  840. const RecurlyWrapper = {
  841. apiUrl: Settings.apis.recurly.url || 'https://api.recurly.com/v2',
  842. _buildXml,
  843. _parseXml: callbackify(promises._parseXml),
  844. createFixedAmountCoupon: callbackify(promises.createFixedAmountCoupon),
  845. getAccountActiveCoupons: callbackify(promises.getAccountActiveCoupons),
  846. getBillingInfo: callbackify(promises.getBillingInfo),
  847. getPaginatedEndpoint: callbackify(promises.getPaginatedEndpoint),
  848. getSubscription: callbackify(promises.getSubscription),
  849. getSubscriptions: callbackify(promises.getSubscriptions),
  850. updateAccountEmailAddress: callbackify(promises.updateAccountEmailAddress),
  851. }
  852. RecurlyWrapper.promises = {
  853. ...promises,
  854. updateAccountEmailAddress,
  855. }
  856. module.exports = RecurlyWrapper
  857. function getCustomFieldsFromSubscriptionDetails(subscriptionDetails) {
  858. if (!subscriptionDetails.ITMCampaign) {
  859. return null
  860. }
  861. const customFields = [
  862. {
  863. name: 'itm_campaign',
  864. value: subscriptionDetails.ITMCampaign,
  865. },
  866. ]
  867. if (subscriptionDetails.ITMContent) {
  868. customFields.push({
  869. name: 'itm_content',
  870. value: subscriptionDetails.ITMContent,
  871. })
  872. }
  873. if (subscriptionDetails.ITMReferrer) {
  874. customFields.push({
  875. name: 'itm_referrer',
  876. value: subscriptionDetails.ITMReferrer,
  877. })
  878. }
  879. return { custom_field: customFields }
  880. }
  881. function getAddressFromSubscriptionDetails(
  882. subscriptionDetails,
  883. includeCompanyInfo
  884. ) {
  885. const { address } = subscriptionDetails
  886. if (!address || !address.country) {
  887. throw new Errors.InvalidError({
  888. message: 'Invalid country',
  889. info: {
  890. public: {
  891. message: 'Invalid country',
  892. },
  893. },
  894. })
  895. }
  896. const addressObject = {
  897. address1: address.address1,
  898. address2: address.address2 || '',
  899. city: address.city || '',
  900. state: address.state || '',
  901. zip: address.zip || '',
  902. country: address.country,
  903. }
  904. if (
  905. includeCompanyInfo &&
  906. subscriptionDetails.billing_info &&
  907. subscriptionDetails.billing_info.company &&
  908. subscriptionDetails.billing_info.company !== ''
  909. ) {
  910. addressObject.company = subscriptionDetails.billing_info.company
  911. if (
  912. subscriptionDetails.billing_info.vat_number &&
  913. subscriptionDetails.billing_info.vat_number !== ''
  914. ) {
  915. addressObject.vat_number = subscriptionDetails.billing_info.vat_number
  916. }
  917. }
  918. return addressObject
  919. }