{"version":3,"sources":["webpack:///./src/lib/assetsUrl.js","webpack:///./src/pages/integration-builder/integration-builder.module.css","webpack:///./src/components/integration-builder/code-selector/code-snippets/helpers/fundingSourcesAssets.ts","webpack:///./src/components/integration-builder/context/CheckoutSimulatorContext.tsx","webpack:///./src/components/integration-builder/code-selector/code-snippets/helpers/codePreviewParser.ts","webpack:///./src/components/integration-builder/code-selector/code-snippets/checkout/templates.ts","webpack:///./src/pages/integration-builder/sections/Code.tsx"],"names":["codeSamplesUrl","window","location","host","includes","zippedSamplesUrl","module","exports","fundingSourceCodeMap","fundingSource","fundingOrderMap","getSelectedSources","selectedPaymentButtons","Object","keys","map","filter","Boolean","parseSelectedSources","params","selectedButtons","paymentModel","options","find","option","name","value","replace","toLowerCase","join","getUnselectedSources","selectedSources","parseUnselectedSources","unselectedButtons","unselectedButton","toUpperCase","CheckoutSimulatorContext","createContext","orderSubscriptionCode","method","tabs","language","buttons","repeat","codePreviewParser","content","code","unselectedSources","length","fundingSources","funding","forEach","htmlFundingSources","reactFundingSources","reactEnableFunding","param","paramValue","JSON","stringify","Array","isArray","regex","RegExp","type","path","withAnalytics","Code","fptiData","fpti","isCopied","setIsCopied","React","useState","files","setFiles","fileOptions","setFileOptions","selectedFile","setSelectedFile","selectedLanguage","setSelectedLanguage","selectedCodeSample","setSelectedCodeSample","integrationType","snippets","parameters","useContext","backendFiles","setBackendFiles","frontendFiles","setFrontendFiles","getFallbackTemplate","file","templateFileCode","templates","template","_objectSpread","updateCodeSample","fileName","frontEndLanguageSelected","url","urlBuilder","baseUrl","frontEndLaguage","model","fullPath","fetch","redirect","then","res","status","Error","text","catch","useEffect","_find","backend","frontend","concat","_toConsumableArray","snippet","fileTypeOf","primaryText","createElement","className","styles","checkout_simulator__code_container","checkout_simulator__file_selection_wrapper","DropdownMenu","checkout_simulator__file_selector","id","label","onChange","event","target","CopyButton","onClick","async","_window$PAYPAL","_window$PAYPAL$analyt","navigator","clipboard","writeText","err","console","error","PAYPAL","analytics","instance","record","data","component","page","pgrp","e","link","event_action","setTimeout","copySampleFile","Icon","integration_builder__copyIconSuccess","color","integration_builder__copyIcon","CodeBlock","hasOwnCopyBlock"],"mappings":"+EAAA,MAIMA,EACc,oBAAXC,SACNA,OAAOC,SAASC,KAAKC,SAAS,wBADF,GAC2C,oDACP,sFAG7DC,EACc,oBAAXJ,SACNA,OAAOC,SAASC,KAAKC,SAAS,wBADF,GAC2C,mKAI1EE,EAAOC,QAAU,CACfP,iBACAK,qB,qBCjBFC,EAAOC,QAAU,CAAC,2BAA6B,gEAAgE,oCAAsC,yEAAyE,qCAAuC,0EAA0E,oCAAsC,yEAAyE,4BAA8B,iEAAiE,kCAAoC,uEAAuE,yCAA2C,8EAA8E,iCAAmC,sEAAsE,gCAAkC,qEAAqE,iCAAmC,sEAAsE,+BAAiC,oEAAoE,kCAAoC,uEAAuE,+BAAiC,oEAAoE,iCAAmC,sEAAsE,sCAAwC,2EAA2E,iCAAmC,sEAAsE,wCAA0C,6EAA6E,qCAAuC,0EAA0E,sCAAwC,2EAA2E,4BAA8B,iEAAiE,kCAAoC,uEAAuE,kCAAoC,uEAAuE,6CAA+C,kFAAkF,uCAAyC,4EAA4E,qCAAuC,0EAA0E,mCAAqC,wEAAwE,kCAAoC,uEAAuE,yCAA2C,8EAA8E,2CAA6C,gFAAgF,kCAAoC,uEAAuE,oCAAsC,yEAAyE,mCAAqC,wEAAwE,gDAAkD,qFAAqF,qDAAuD,0FAA0F,8BAAgC,mEAAmE,qCAAuC,0EAA0E,kCAAoC,uEAAuE,2CAA6C,gFAAgF,mCAAqC,wEAAwE,6BAA+B,kEAAkE,2BAA6B,gEAAgE,QAAU,6CAA6C,OAAS,4CAA4C,QAAU,6CAA6C,MAAQ,2CAA2C,WAAa,gDAAgD,WAAa,gDAAgD,SAAW,8CAA8C,iBAAmB,sDAAsD,WAAa,gDAAgD,OAAS,4CAA4C,eAAiB,sD,kCCDphK,4MAAO,MAAMC,EAA4B,CAEvC,wBAAyB,uBACzB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ACHnC,UAAWC,IAAOmC,qCAClBvI,KAAK,uBACLwI,MAAM,wBAGR1F,IAAAoD,cAACoC,IAAI,CACHnC,UAAWC,IAAOqC,8BAClBzI,KAAK,oBACLwI,MAAM,0BAKd1F,IAAAoD,cAACwC,IAAS,CAACC,iBAAiB,EAAMxC,UAAW7C,GAC1CE","file":"component---src-pages-integration-builder-sections-code-tsx-a2d6aad520949c7ba4c8.js","sourcesContent":["const overrideStage = true\nconst stageBundleId = 'cb100523153034'\nconst samplesVersion = '1.0.5'\n\nconst codeSamplesUrl =\n typeof window !== 'undefined' &&\n (window.location.host.includes('developer.paypal.com') || overrideStage)\n ? `https://www.paypalobjects.com/ib-codesample/${samplesVersion}`\n : `https://cdn-${stageBundleId}.static.engineering.dev.paypalinc.com/ib-codesample/${samplesVersion}`\n\nconst zippedSamplesUrl =\n typeof window !== 'undefined' &&\n (window.location.host.includes('developer.paypal.com') || overrideStage)\n ? `https://paypalobjects.com/ppdevdocs/static/zipped_samples`\n : `https://cdn-${stageBundleId}.static.engineering.dev.paypalinc.com/timdev/ib_codesamples/zipped_samples`\n\nmodule.exports = {\n codeSamplesUrl,\n zippedSamplesUrl,\n}\n","// extracted by mini-css-extract-plugin\nmodule.exports = {\"checkout_simulator__header\":\"integration-builder-module--checkout_simulator__header--1g5VM\",\"checkout_simulator__header_loggedIn\":\"integration-builder-module--checkout_simulator__header_loggedIn--2UC8M\",\"checkout_simulator__header_loggedOut\":\"integration-builder-module--checkout_simulator__header_loggedOut--3Cc-V\",\"checkout_simulator__go_back_wrapper\":\"integration-builder-module--checkout_simulator__go_back_wrapper--2FtUd\",\"checkout_simulator__go_back\":\"integration-builder-module--checkout_simulator__go_back--1K6_Z\",\"checkout_simulator__go_back_title\":\"integration-builder-module--checkout_simulator__go_back_title--2uofT\",\"checkout_simulator__header_badge_wrapper\":\"integration-builder-module--checkout_simulator__header_badge_wrapper--ctoCN\",\"checkout_simulator__header_title\":\"integration-builder-module--checkout_simulator__header_title--3Bl3W\",\"checkout_simulator__update_date\":\"integration-builder-module--checkout_simulator__update_date--1sHE-\",\"checkout_simulator__card_wrapper\":\"integration-builder-module--checkout_simulator__card_wrapper--1lZxx\",\"checkout_simulator__head_title\":\"integration-builder-module--checkout_simulator__head_title--50MqS\",\"checkout_simulator__cards_wrapper\":\"integration-builder-module--checkout_simulator__cards_wrapper--1W6wG\",\"checkout_simulator__card_title\":\"integration-builder-module--checkout_simulator__card_title--1WfNk\",\"checkout_simulator__card_content\":\"integration-builder-module--checkout_simulator__card_content--2_fje\",\"checkout_simulator__container_content\":\"integration-builder-module--checkout_simulator__container_content--3v3Bh\",\"checkout_simulator__left_section\":\"integration-builder-module--checkout_simulator__left_section--3aQY-\",\"checkout_simulator__accordion_container\":\"integration-builder-module--checkout_simulator__accordion_container--w6noL\",\"checkout_simulator__subtitle_wrapper\":\"integration-builder-module--checkout_simulator__subtitle_wrapper--2nrXB\",\"checkout_simulator__fragment_subtitle\":\"integration-builder-module--checkout_simulator__fragment_subtitle--3JNlm\",\"checkout_simulator__preview\":\"integration-builder-module--checkout_simulator__preview--rVNjs\",\"checkout_simulator__preview_title\":\"integration-builder-module--checkout_simulator__preview_title--3-BOT\",\"checkout_simulator__right_section\":\"integration-builder-module--checkout_simulator__right_section--1r50z\",\"integration_builder__horizontal_btns_wrapper\":\"integration-builder-module--integration_builder__horizontal_btns_wrapper--I-oIi\",\"integration_builder__iframe_horizontal\":\"integration-builder-module--integration_builder__iframe_horizontal--1_tAw\",\"integration_builder__iframe_vertical\":\"integration-builder-module--integration_builder__iframe_vertical--2hy-g\",\"integration_builder__paypal_button\":\"integration-builder-module--integration_builder__paypal_button--220zF\",\"integration_builder__preview_text\":\"integration-builder-module--integration_builder__preview_text--K2szQ\",\"integration_builder__codeblock_container\":\"integration-builder-module--integration_builder__codeblock_container--1FaEP\",\"checkout_simulator__file_selection_wrapper\":\"integration-builder-module--checkout_simulator__file_selection_wrapper--1uU2Y\",\"checkout_simulator__file_selector\":\"integration-builder-module--checkout_simulator__file_selector--1Xerw\",\"checkout_simulator__download_button\":\"integration-builder-module--checkout_simulator__download_button--11QPs\",\"checkout_simulator__card_generator\":\"integration-builder-module--checkout_simulator__card_generator--64ZOU\",\"checkout_simulator__card_generator_text_wrapper\":\"integration-builder-module--checkout_simulator__card_generator_text_wrapper--38lVa\",\"checkout_simulator__card_generator_background_circle\":\"integration-builder-module--checkout_simulator__card_generator_background_circle--2vC5u\",\"integration_builder__copyIcon\":\"integration-builder-module--integration_builder__copyIcon--3nU01\",\"integration_builder__copyIconSuccess\":\"integration-builder-module--integration_builder__copyIconSuccess--1hHxO\",\"checkout_simulator__copyClipboard\":\"integration-builder-module--checkout_simulator__copyClipboard--HwHw6\",\"integration_builder__external_link_wrapper\":\"integration-builder-module--integration_builder__external_link_wrapper--2Oku5\",\"integration_builder__external_link\":\"integration-builder-module--integration_builder__external_link--1KBeB\",\"integration_builder__tooltip\":\"integration-builder-module--integration_builder__tooltip--26mjy\",\"checkout_simulator__banner\":\"integration-builder-module--checkout_simulator__banner--3AScR\",\"wrapper\":\"integration-builder-module--wrapper--3oiKF\",\"header\":\"integration-builder-module--header--2la4S\",\"buttons\":\"integration-builder-module--buttons--3cgNX\",\"title\":\"integration-builder-module--title--1HWFy\",\"titleText1\":\"integration-builder-module--titleText1--3PvmB\",\"titleText2\":\"integration-builder-module--titleText2--3N3-w\",\"errorImg\":\"integration-builder-module--errorImg--3bnnE\",\"searchSuggestion\":\"integration-builder-module--searchSuggestion--i3pm3\",\"searchTerm\":\"integration-builder-module--searchTerm--2Vwia\",\"expand\":\"integration-builder-module--expand--1X_Mq\",\"paypal_payment\":\"integration-builder-module--paypal_payment--3X7ab\"};","export const fundingSourceCodeMap: any = {\n // 'payment-buttons_paypal': 'paypal.FUNDING.PAYPAL',\n 'payment-buttons_venmo': 'paypal.FUNDING.VENMO',\n 'payment-buttons_paylater': 'paypal.FUNDING.PAYLATER',\n 'payment-buttons_credit': 'paypal.FUNDING.CARD',\n 'payment-buttons_card': 'paypal.FUNDING.CARD',\n}\n\nexport const fundingSource: any = {\n // 'payment-buttons_paypal': 'paypal',\n 'payment-buttons_venmo': 'venmo',\n 'payment-buttons_paylater': 'paylater',\n 'payment-buttons_card': 'card',\n}\n\nexport const fundingOrderMap = [\n // 'paypal.FUNDING.PAYPAL',\n 'paypal.FUNDING.PAYLATER',\n 'paypal.FUNDING.VENMO',\n 'paypal.FUNDING.CARD',\n]\n\nexport const getSelectedSources = (selectedPaymentButtons: any) =>\n Object.keys(fundingSourceCodeMap)\n .map((fundingSource) => {\n if (selectedPaymentButtons.includes(fundingSource)) {\n return fundingSourceCodeMap[fundingSource]\n }\n return null\n })\n .filter(Boolean)\n\nexport const parseSelectedSources = (\n params: any,\n selectedButtons: string[],\n) => {\n return fundingOrderMap\n .filter(\n (fundingSource) =>\n selectedButtons.includes(fundingSource) &&\n (params.paymentModel === 'recurring'\n ? fundingSource !== 'paypal.FUNDING.VENMO'\n : true),\n )\n .filter(\n (fundingSource) =>\n params.options.find((option: any) => option.name === 'integration')\n .value === 'standard' || fundingSource !== 'paypal.FUNDING.CARD',\n )\n .map((fundingSource) =>\n fundingSource.replace('paypal.FUNDING.', '').toLowerCase(),\n )\n .join(',')\n}\n\nexport const getUnselectedSources = (selectedSources: string[]) =>\n Object.keys(fundingSourceCodeMap).filter(\n (fundingSource) =>\n !selectedSources.includes(fundingSourceCodeMap[fundingSource]),\n )\n\nexport const parseUnselectedSources = (\n params: any,\n unselectedButtons: string[],\n) => {\n return fundingOrderMap\n .filter(\n (fundingSource) =>\n unselectedButtons\n .map((unselectedButton: string) =>\n unselectedButton\n .toUpperCase()\n .replace('PAYMENT-BUTTONS_', 'paypal.FUNDING.'),\n )\n .includes(fundingSource) &&\n (params.paymentModel === 'recurring'\n ? fundingSource !== 'paypal.FUNDING.VENMO'\n : true),\n )\n .filter(\n (fundingSource) =>\n params.options.find((option: any) => option.name === 'integration')\n .value === 'standard' || fundingSource !== 'paypal.FUNDING.CARD',\n )\n .map((fundingSource) =>\n fundingSource.replace('paypal.FUNDING.', '').toLowerCase(),\n )\n .join(',')\n}\n","import { createContext } from 'react'\nimport { CheckoutSimulatorContextProps } from './interfaces'\n\nexport const CheckoutSimulatorContext = createContext(\n {} as CheckoutSimulatorContextProps,\n)\n","import {\n fundingOrderMap,\n fundingSource,\n getSelectedSources,\n getUnselectedSources,\n} from './fundingSourcesAssets'\n\nconst placeholderMap = ['buttons']\n\nexport const htmlFundingSources = (fundingSources: string[]) => {\n let buttons = ''\n fundingSources\n .filter((funding) => fundingSource[funding])\n .forEach((funding) => {\n buttons += `\n paypal.Buttons({\n fundingSource: '${fundingSource[funding]}',\n \n style: {\n layout: '{{ buttonLayout }}',\n shape: '{{ buttonStyle }}',\n }\n \n createOrder: async (data, actions) => {\n const response = await fetch(\"/orders\", {\n method: \"POST\",\n });\n const details = await response.json();\n return details.id;\n },\n onApprove: async (data, actions) => {\n const response = await fetch(\\`/orders/\\${data.orderID}/capture\\`, {\n method: \"POST\",\n });\n const details = await response.json();\n // Three cases to handle:\n // (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()\n // (2) Other non-recoverable errors -> Show a failure message\n // (3) Successful transaction -> Show confirmation or thank you\n \n // This example reads a v2/checkout/orders capture response, propagated from the server\n // You could use a different API or structure for your 'orderData'\n \n const errorDetail = Array.isArray(details.details) && details.details[0];\n if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {\n return actions.restart(); // Recoverable state, per:\n // https://developer.paypal.com/docs/checkout/integration-features/funding-failure/\n }\n \n if (errorDetail) {\n let msg = 'Sorry, your transaction could not be processed.';\n if (errorDetail.description) msg += '\\n\\n' + errorDetail.description;\n if (details.debug_id) msg += ' (' + details.debug_id + ')';\n return alert(msg); // Show a failure message (try to avoid alerts in production environments)\n }\n \n // Successful capture! For demo purposes:\n console.log('Capture result', details, JSON.stringify(details, null, 2));\n const transaction = details.purchase_units[0].payments.captures[0];\n alert('Transaction '+ transaction.status + ': ' + transaction.id + '\\n\\nSee console for all available details');\n },\n })\n .render(\"#paypal-button-container\");\n `\n })\n return buttons\n}\n\nexport const orderSubscriptionCode = (\n method: string,\n tabs: number = 2,\n language: 'html' | 'react' | 'angular' = 'html',\n) => {\n let buttons = ``\n\n if (method === 'recurring') {\n switch (language) {\n case 'react':\n buttons += `\n${' '.repeat(tabs)}createSubscription={ async (data, actions) => {\n${' '.repeat(tabs)} return actions.subscription.create({\n${' '.repeat(tabs)} plan_id: \"P-3RX065706M3469222L5IFM4I\",\n${' '.repeat(tabs)} });\n${' '.repeat(tabs)}};\n`\n break\n default:\n buttons += `\n${' '.repeat(tabs)}createSubscription: (data, actions) => {\n${' '.repeat(tabs)} return actions.subscription.create({\n${' '.repeat(tabs)} plan_id: \"P-3RX065706M3469222L5IFM4I\",\n${' '.repeat(tabs)} });\n${' '.repeat(tabs)}};\n`\n break\n }\n }\n\n return buttons\n}\n\nexport const reactFundingSources = (fundingSources: string[]) => {\n let buttons = ''\n fundingSources.forEach((funding) => {\n buttons += ` {\n const response = await fetch(\"http://localhost:9597/orders\", {\n method: \"POST\"\n });\n const details = await response.json();\n return details.id;\n }}\n onApprove={async (data, actions) => {\n const response = await fetch(\\`http://localhost:9597/orders/\\${data.orderID}/capture\\`, {\n method: \"POST\"\n });\n const details = await response.json();\n // Three cases to handle:\n // (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()\n // (2) Other non-recoverable errors -> Show a failure message\n // (3) Successful transaction -> Show confirmation or thank you\n \n // This example reads a v2/checkout/orders capture response, propagated from the server\n // You could use a different API or structure for your 'orderData'\n \n const errorDetail = Array.isArray(details.details) && details.details[0];\n if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {\n return actions.restart(); // Recoverable state, per:\n // https://developer.paypal.com/docs/checkout/integration-features/funding-failure/\n }\n \n if (errorDetail) {\n let msg = 'Sorry, your transaction could not be processed.';\n if (errorDetail.description) msg += '\n \n ' + errorDetail.description;\n if (details.debug_id) msg += ' (' + details.debug_id + ')';\n return alert(msg); // Show a failure message (try to avoid alerts in production environments)\n }\n \n // Successful capture! For demo purposes:\n console.log('Capture result', details, JSON.stringify(details, null, 2));\n const transaction = details.purchase_units[0].payments.captures[0];\n alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n \n See console for all available details');\n }}\n />\n `\n })\n return buttons\n}\nexport const reactEnableFunding = (fundingSources: string[]) => {\n let buttons = ''\n fundingSources.forEach((funding) => {\n if (fundingSource[funding])\n buttons += ` \"enable-funding\":\"${fundingSource[funding]}\",\\r\\n`\n })\n return buttons\n}\nexport const angularFundingSources = (fundingSources: string[]) => {\n let buttons = ''\n fundingSources.forEach((funding) => {\n buttons += ` {\n const response = await fetch(\"http://localhost:9597/orders\", {\n method: \"POST\"\n });\n const details = await response.json();\n return details.id;\n }}\n onApprove={async (data, actions) => {\n const response = await fetch(\\`http://localhost:9597/orders/\\${data.orderID}/capture\\`, {\n method: \"POST\"\n });\n const details = await response.json();\n // Three cases to handle:\n // (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()\n // (2) Other non-recoverable errors -> Show a failure message\n // (3) Successful transaction -> Show confirmation or thank you\n \n // This example reads a v2/checkout/orders capture response, propagated from the server\n // You could use a different API or structure for your 'orderData'\n \n const errorDetail = Array.isArray(details.details) && details.details[0];\n if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {\n return actions.restart(); // Recoverable state, per:\n // https://developer.paypal.com/docs/checkout/integration-features/funding-failure/\n }\n \n if (errorDetail) {\n let msg = 'Sorry, your transaction could not be processed.';\n if (errorDetail.description) msg += '\n \n ' + errorDetail.description;\n if (details.debug_id) msg += ' (' + details.debug_id + ')';\n return alert(msg); // Show a failure message (try to avoid alerts in production environments)\n }\n \n // Successful capture! For demo purposes:\n console.log('Capture result', details, JSON.stringify(details, null, 2));\n const transaction = details.purchase_units[0].payments.captures[0];\n alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n \n See console for all available details');\n }}\n />\n `\n })\n return buttons\n}\n\nexport const codePreviewParser = (content: string, params: any) => {\n let code = content\n\n //Buttons\n let buttons = getSelectedSources(params.buttons)\n let unselectedButtons = getUnselectedSources(buttons)\n\n code = code.replace(/{{ fundingSources }}/g, buttons.join())\n\n code = code.replace(\n /{{ unselectedFundingSources }}/g,\n unselectedButtons.join(),\n )\n code = code.replace(\n /{{ unselectedFundingSourcesFull }}/g,\n '&disable-funding=' + unselectedButtons.join(),\n )\n\n code = code.replace(\n /{{ fundingSources, list }}/g,\n '// EDIT FUNDING SOURCES\\r\\n ' +\n fundingOrderMap\n .filter(\n (fundingSource) =>\n buttons.includes(fundingSource) &&\n (params.paymentModel === 'recurring'\n ? fundingSource !== 'paypal.FUNDING.VENMO'\n : true),\n )\n .join(',\\r\\n '),\n )\n code = code.replace(\n /{{ createOrderSubscription }}/g,\n orderSubscriptionCode(params.paymentModel),\n )\n code = code.replace(\n /{{ createOrderSubscription,5 }}/g,\n orderSubscriptionCode(params.paymentModel, 4),\n )\n code = code.replace(\n /{{ createOrderSubscription, 5 }}/g,\n orderSubscriptionCode(params.paymentModel, 4),\n )\n code = code.replace(\n /{{ createOrderSubscription_react,7 }}/g,\n orderSubscriptionCode(params.paymentModel, 7, 'react'),\n )\n code = code.replace(\n /{{ createOrderSubscription_react, 7 }}/g,\n orderSubscriptionCode(params.paymentModel, 7, 'react'),\n )\n code = code.replace(\n /{{ createOrderSubscription_react,8 }}/g,\n orderSubscriptionCode(params.paymentModel, 8, 'react'),\n )\n code = code.replace(\n /{{ createOrderSubscription_react, 8 }}/g,\n orderSubscriptionCode(params.paymentModel, 8, 'react'),\n )\n code = code.replace(\n /{{ createOrderSubscription_angular,3 }}/g,\n orderSubscriptionCode(params.paymentModel, 3, 'angular'),\n )\n\n code = code.replace(\n /{{ fundingSources, list_2 }}/g,\n fundingOrderMap\n .filter(\n (fundingSource) =>\n buttons.includes(fundingSource) &&\n (params.paymentModel === 'recurring'\n ? fundingSource !== 'paypal.FUNDING.VENMO'\n : true),\n )\n .filter(\n (fundingSource) =>\n params.options.find((option: any) => option.name === 'integration')\n .value === 'standard' || fundingSource !== 'paypal.FUNDING.CARD',\n )\n .join(',\\r\\n '),\n )\n code = code.replace(\n /{{ fundingSources, inline_list }}/g,\n fundingOrderMap\n .filter(\n (fundingSource) =>\n buttons.includes(fundingSource) &&\n (params.paymentModel === 'recurring'\n ? fundingSource !== 'paypal.FUNDING.VENMO'\n : true),\n )\n .filter(\n (fundingSource) =>\n params.options.find((option: any) => option.name === 'integration')\n .value === 'standard' || fundingSource !== 'paypal.FUNDING.CARD',\n )\n .map((fundingSource) =>\n fundingSource.replace('paypal.FUNDING.', '').toLowerCase(),\n )\n .join(','),\n )\n\n const unselectedSources = fundingOrderMap\n .filter(\n (fundingSource) =>\n unselectedButtons\n .map((unselectedButton) =>\n unselectedButton\n .toUpperCase()\n .replace('PAYMENT-BUTTONS_', 'paypal.FUNDING.'),\n )\n .includes(fundingSource) &&\n (params.paymentModel === 'recurring'\n ? fundingSource !== 'paypal.FUNDING.VENMO'\n : true),\n )\n .filter(\n (fundingSource) =>\n params.options.find((option: any) => option.name === 'integration')\n .value === 'standard' || fundingSource !== 'paypal.FUNDING.CARD',\n )\n .map((fundingSource) =>\n fundingSource.replace('paypal.FUNDING.', '').toLowerCase(),\n )\n .join(',')\n\n code = code.replace(\n /{{ unselectedFundingSourcesFull, inline_list }}/g,\n unselectedButtons.length > 0 ? `&disable-funding=${unselectedSources}` : '',\n )\n code = code.replace(\n /{{ unselectedFundingSources, inline_list }}/g,\n unselectedSources,\n )\n\n code = code.replace(\n /{{ fundingSources,short_list_2 }}/g,\n fundingOrderMap\n .filter(\n (fundingSource) =>\n buttons.includes(fundingSource) &&\n (params.paymentModel === 'recurring'\n ? fundingSource !== 'paypal.FUNDING.VENMO'\n : true),\n )\n .map((fundingSource) => fundingSource.replace('paypal.', ''))\n .join(',\\r\\n '),\n )\n code = code.replace(\n /{{ fundingSources, html }}/g,\n htmlFundingSources(params.buttons),\n )\n code = code.replace(\n /{{ fundingSources, react }}/g,\n reactFundingSources(params.buttons),\n )\n code = code.replace(\n /{{ enableFunding, react }}/g,\n reactEnableFunding(params.buttons),\n )\n\n Object.keys(params).forEach((param) => {\n const paramType = typeof params[param]\n let paramValue: string = ''\n\n switch (paramType) {\n case 'object':\n paramValue = JSON.stringify(params[param])\n if (Array.isArray(params[param])) {\n switch (param) {\n case 'buttons':\n break\n default:\n paramValue = params[param].join()\n break\n }\n }\n break\n default:\n paramValue = params[param]\n break\n }\n const regex = new RegExp(`{{ ${param} }}`, 'g')\n\n code = code.replace(regex, paramValue)\n })\n return code\n}\n","export default [\n {\n type: 'standard',\n path: '/standard/react-node/client/src/',\n name: 'App.jsx',\n content: `{FALLBACK TEMPLATE CODE}import { PayPalScriptProvider, PayPalButtons, FUNDING } from \"@paypal/react-paypal-js\";\n\nfunction App() {\n const FUNDING_SOURCES = [\n {{ fundingSources,short_list_2 }}\n ];\n \n const initialOptions = {\n \"client-id\": \"{{ clientId }}\",\n \"enable-funding\": \"paylater,venmo\",\n }\n\n return (\n
\n \n {\n FUNDING_SOURCES.map(fundingSource=>{\n return(\n {\n try {\n const response = await fetch(\"http://localhost:9597/orders\", {\n method: \"POST\"\n });\n \n const details = await response.json();\n return details.id;\n } catch (error) {\n console.error(error);\n // Handle the error or display an appropriate error message to the user\n }\n }}\n\n {{ createOrderSubscription_react,8 }}\n \n onApprove={async (data, actions) => {\n try {\n const response = await fetch(\\`http://localhost:9597/orders/\\${data.orderID}/capture\\`, {\n method: \"POST\"\n }); \n \n const details = await response.json();\n // Three cases to handle:\n // (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()\n // (2) Other non-recoverable errors -> Show a failure message\n // (3) Successful transaction -> Show confirmation or thank you message\n\n // This example reads a v2/checkout/orders capture response, propagated from the server\n // You could use a different API or structure for your 'orderData'\n const errorDetail = Array.isArray(details.details) && details.details[0];\n \n if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {\n return actions.restart();\n // https://developer.paypal.com/docs/checkout/integration-features/funding-failure/\n }\n\n if (errorDetail) {\n let msg = 'Sorry, your transaction could not be processed.';\n msg += errorDetail.description ? ' ' + errorDetail.description : '';\n msg += details.debug_id ? ' (' + details.debug_id + ')' : '';\n alert(msg);\n }\n \n // Successful capture! For demo purposes:\n console.log('Capture result', details, JSON.stringify(details, null, 2));\n const transaction = details.purchase_units[0].payments.captures[0];\n alert('Transaction '+ transaction.status + ': ' + transaction.id + 'See console for all available details');\n } catch (error) {\n console.error(error);\n // Handle the error or display an appropriate error message to the user\n }\n }}\n />)\n })\n }\n \n
\n );\n}\n\nexport default App;\n`,\n },\n {\n type: 'standard',\n path: '/standard/html-node/',\n name: 'index.html',\n content: `{FALLBACK TEMPLATE CODE}\n\n \n \n \n PayPal JS SDK Demo\n \n \n \n
\n \n \n \n\n `,\n },\n {\n type: 'standard',\n path: '/standard/angular-node/client/src/app/',\n name: 'app.component.ts',\n content: `{FALLBACK TEMPLATE CODE}import { Component } from \"@angular/core\";\nimport { IPayPalConfig } from \"ngx-paypal\";\n@Component({\n selector: \"app-root\",\n templateUrl: \"./app.component.html\",\n})\nexport class AppComponent {\n title = \"client\";\n public payPalConfig?: IPayPalConfig;\n ngOnInit(): void {\n this.initConfig();\n }\n\n private initConfig(): void {\n this.payPalConfig = {\n fundingSource: [\n {{ fundingSources,list }}\n ],\n style: {\n layout: '{{ buttonLayout }}',\n shape: '{{ buttonStyle }}',\n color: (fundingSource==paypal.FUNDING.PAYLATER) ? 'gold' : '',\n },\n currency: \"USD\",\n clientId: \"{{ clientId }}\",\n\n createOrderOnServer: async (data) => {\n const response = await fetch(\"http://localhost:9597/orders/\", {\n method: \"POST\",\n });\n const details = await response.json();\n return details.id;\n },\n {{ createOrderSubscription_angular,3 }}\n authorizeOnServer: async (approveData, actions) => {\n const response = await fetch(\n \\`http://localhost:9597/orders/\\${approveData.orderID}/capture\\`,\n {\n method: \"POST\",\n }\n );\n const details = await response.json();\n // Three cases to handle:\n // (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()\n // (2) Other non-recoverable errors -> Show a failure message\n // (3) Successful transaction -> Show confirmation or thank you\n\n // This example reads a v2/checkout/orders capture response, propagated from the server\n // You could use a different API or structure for your 'orderData'\n\n const errorDetail = Array.isArray(details.details) && details.details[0];\n if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {\n return actions.restart(); // Recoverable state, per:\n // https://developer.paypal.com/docs/checkout/integration-features/funding-failure/\n }\n\n if (errorDetail) {\n let msg = 'Sorry, your transaction could not be processed.';\n if (errorDetail.description) msg += '' + errorDetail.description;\n if (details.debug_id) msg += ' (' + details.debug_id + ')';\n return alert(msg); // Show a failure message (try to avoid alerts in production environments)\n }\n\n // Successful capture! For demo purposes:\n console.log('Capture result', details, JSON.stringify(details, null, 2));\n const transaction = details.purchase_units[0].payments.captures[0];\n alert('Transaction '+ transaction.status + ': ' + transaction.id + 'See console for all available details');\n },\n\n onCancel: (data, actions) => {\n console.log(\"OnCancel\", data, actions);\n },\n onError: (err) => {\n console.log(\"OnError\", err);\n },\n onClick: (data, actions) => {\n console.log(\"onClick\", data, actions);\n },\n };\n }\n}\n `,\n },\n {\n type: 'standard',\n path: '/standard/html-node/',\n name: 'index.js',\n content: `{FALLBACK TEMPLATE CODE}\nimport express from \"express\";\nimport fetch from \"node-fetch\";\nimport cors from \"cors\";\nimport \"dotenv/config\";\n\nconst { CLIENT_ID, APP_SECRET } = process.env;\nconst app = express();\nconst base = \"https://api-m.sandbox.paypal.com\";\nconst app = express();\napp.use(cors({origin: '*'}));\n\nconst generateAccessToken = async () => {\n try {\n const auth = Buffer.from(CLIENT_ID + \":\" + APP_SECRET).toString(\"base64\");\n const response = await fetch(\\`\\${base}/v1/oauth2/token\\`, {\n method: \"post\",\n body: \"grant_type=client_credentials\",\n headers: {\n Authorization: \\`Basic \\${auth}\\`,\n },\n });\n \n const data = await response.json();\n return data.access_token;\n } catch(error) {\n console.error(\"Failed to generate Access Token:\", error);\n } \n};\n\nconst createOrder = async () => {\n const accessToken = await generateAccessToken();\n const url = \\`\\${base}/v2/checkout/orders\\`;\n const payload = {\n intent: \"CAPTURE\",\n purchase_units: [\n {\n amount: {\n currency_code: \"USD\",\n value: \"0.02\",\n },\n },\n ],\n };\n\n const response = await fetch(url, {\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: \\`Bearer \\${accessToken}\\`,\n },\n method: \"POST\",\n body: JSON.stringify(payload),\n });\n\n return handleResponse(response);\n};\n\n\nconst capturePayment = async (orderID) => {\n const accessToken = await generateAccessToken();\n const url = \\`\\${base}/v2/checkout/orders/\\${orderID}/capture\\`;\n\n const response = await fetch(url, {\n method: \"post\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: \\`Bearer \\${accessToken}\\`,\n }\n });\n \n return handleResponse(response);\n};\n\nasync function handleResponse(response) {\n if (response.status === 200 || response.status === 201) {\n return response.json();\n }\n\n const errorMessage = await response.text();\n throw new Error(errorMessage);\n}\n\n\napp.post(\"/orders\", async (req, res) => {\n try{\n const response = await createOrder();\n res.json(response);\n } catch(error) {\n console.error(\"Failed to create order:\", error);\n res.status(500).json({ error: \"Failed to create order.\" });\n }\n});\n\napp.post(\"/orders/:orderID/capture\", async (req, res) => {\n try {\n const { orderID } = req.params;\n const response = await capturePayment(orderID);\n res.json(response);\n } catch (error){\n console.error(\"Failed to create order:\", error);\n res.status(500).json({ error: \"Failed to capture order.\" });\n }\n});\n\napp.listen(9597, () => {\n console.log(\"listening on http://localhost:9597/\");\n});\n`,\n },\n\n {\n type: 'advanced',\n path: '/advance/3ds-node/public/',\n name: 'app.js',\n content: `{FALLBACK TEMPLATE CODE}\n const FUNDING_SOURCES = [\n {{ fundingSources, list_2 }}\n ];\n \n function handleTransactionCases(details) {\n // Three cases to handle:\n // (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()\n // (2) Other non-recoverable errors -> Show a failure message\n // (3) Successful transaction -> Show confirmation or thank you message\n \n // This example reads a v2/checkout/orders capture response, propagated from the server\n // You could use a different API or structure for your 'orderData'\n const errorDetail = Array.isArray(details.details) && details.details[0];\n \n if (errorDetail && errorDetail.issue === \"INSTRUMENT_DECLINED\") {\n return actions.restart();\n // https://developer.paypal.com/docs/checkout/integration-features/funding-failure/\n }\n \n if (errorDetail) {\n let msg = \"Sorry, your transaction could not be processed.\";\n msg += errorDetail.description ? \" \" + errorDetail.description : \"\";\n msg += details.debug_id ? \" (\" + details.debug_id + \")\" : \"\";\n alert(msg);\n }\n \n const transaction = details.purchase_units[0].payments.captures[0];\n alert(\"Transaction \" + transaction.status + \": \" + transaction.id + \". See console for all available details\");\n }\n \n async function onCreateOrder(data, actions) {\n try {\n const response = await fetch(\"/api/orders\", {\n method: \"POST\",\n });\n \n const details = await response.json();\n return details.id;\n } catch (error) {\n console.error(error);\n }\n }\n \n async function onCaptureOrder(data, actions, orderID) {\n const threedsElement = document.getElementById(\"threeds\");\n threedsElement.innerHTML = \"\";\n const orderId = data ? data.orderID : orderID;\n \n try {\n const response = await fetch(\\`/api/orders/\\${orderId}/capture\\`, {\n method: \"POST\",\n });\n \n const details = await response.json();\n handleTransactionCases(details);\n } catch (error) {\n console.error(error);\n }\n }\n \n //Close 3Ds Dialog\n function onClose() {\n const threedsElement = document.getElementById(\"threeds\");\n threedsElement.innerHTML = \"\";\n }\n \n //Handle 3Ds Payload\n async function onHandle3Ds(payload, orderId) {\n const { liabilityShifted, liabilityShift } = payload;\n \n if (liabilityShift === \"POSSIBLE\") {\n await onCaptureOrder(null, null, orderId);\n } else if (liabilityShifted === false || liabilityShifted === undefined) {\n document.getElementById(\"threeds\").innerHTML = \\`\n

You have the option to complete the payment at your own risk,\n meaning that the liability of any chargeback has not shifted from\n the merchant to the card issuer.

\n \n \n
\n \\`;\n }\n }\n \n FUNDING_SOURCES.forEach((fundingSource) => {\n paypal.Buttons({\n fundingSource,\n style: {\n layout: \"vertical\",\n shape: \"{{ buttonStyle }}\",\n color: (fundingSource==paypal.FUNDING.PAYLATER) ? 'gold' : '',\n },\n createOrder: async (data, actions) => onCreateOrder(data, actions),\n onApprove: async (data, actions) => onCaptureOrder (data, actions, null),\n })\n .render(\"#paypal-button-container\");\n });\n \n // If this returns false or the card fields aren't visible, see Step #1.\n if (paypal.HostedFields.isEligible()) {\n let orderId;\n \n // Renders card fields\n paypal.HostedFields.render({\n // Call your server to set up the transaction\n createOrder: async (data, actions) => {\n orderId = await onCreateOrder(data, actions);\n return orderId;\n },\n styles: {\n \".valid\": {\n color: \"green\",\n },\n \".invalid\": {\n color: \"red\",\n },\n },\n fields: {\n number: {\n selector: \"#card-number\",\n placeholder: \"4111 1111 1111 1111\",\n },\n cvv: {\n selector: \"#cvv\",\n placeholder: \"123\",\n },\n expirationDate: {\n selector: \"#expiration-date\",\n placeholder: \"MM/YY\",\n },\n },\n }).then((cardFields) => {\n document.querySelector(\"#card-form\").addEventListener(\"submit\", async (event) => {\n event.preventDefault();\n try {\n const { value: cardHolderName } = document.getElementById(\"card-holder-name\");\n const { value: postalCode } = document.getElementById(\"card-billing-address-zip\");\n const { value: countryCodeAlpha2 } = document.getElementById(\"card-billing-address-country\");\n \n const payload = await cardFields.submit({\n cardHolderName,\n contingencies: [\"SCA_ALWAYS\"],\n billingAddress: {\n postalCode,\n countryCodeAlpha2,\n },\n });\n \n await onHandle3Ds(payload, orderId);\n } catch (error) {\n alert(\"Payment could not be captured! \" + JSON.stringify(error));\n }\n });\n });\n } else {\n // Hides card fields if the merchant isn't eligible\n document.querySelector(\"#card-form\").style = \"display: none\";\n }\n`,\n },\n {\n type: 'advanced',\n path: '/advance/3ds-node/public/',\n name: 'server.js',\n content: `{FALLBACK TEMPLATE CODE}\nimport \"dotenv/config\";\nimport express from \"express\";\nimport * as paypal from \"./paypal-api.js\";\n\nconst app = express();\napp.set(\"view engine\", \"ejs\");\napp.use(express.static(\"public\"));\n\n// render checkout page with client id & unique client token\napp.get(\"/\", async (req, res) => {\n const clientId = process.env.CLIENT_ID;\n try {\n const clientToken = await paypal.generateClientToken();\n res.render(\"checkout\", { clientId, clientToken });\n } catch (err) {\n res.status(500).send(err.message);\n }\n});\n\n// create order\napp.post(\"/api/orders\", async (req, res) => {\n try {\n const order = await paypal.createOrder();\n res.json(order);\n } catch (err) {\n res.status(500).send(err.message);\n }\n});\n\n// capture payment\napp.post(\"/api/orders/:orderID/capture\", async (req, res) => {\n const { orderID } = req.params;\n try {\n const captureData = await paypal.capturePayment(orderID);\n res.json(captureData);\n } catch (err) {\n res.status(500).send(err.message);\n }\n});\n\napp.listen(9597, () => {\n console.log(\"listening on http://localhost:9597/\");\n});\n`,\n },\n {\n type: 'advanced',\n path: '/advance/3ds-node/public/',\n name: 'index.html',\n content: `{FALLBACK TEMPLATE CODE}\n \n \n \n \n \n \n \n \n \n
\n
\n

OR

\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n \n
\n \n
\n
\n

\n \n
\n
\n
\n \n \n`,\n },\n {\n type: 'advanced',\n path: '/advance/html-node/public/',\n name: 'app.js',\n content: `{FALLBACK TEMPLATE CODE}\n const FUNDING_SOURCES = [\n {{ fundingSources, list_2 }}\n ];\n \n function handleTransactionCases(details) {\n // Three cases to handle:\n // (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()\n // (2) Other non-recoverable errors -> Show a failure message\n // (3) Successful transaction -> Show confirmation or thank you message\n \n // This example reads a v2/checkout/orders capture response, propagated from the server\n // You could use a different API or structure for your 'orderData'\n const errorDetail = Array.isArray(details.details) && details.details[0];\n \n if (errorDetail && errorDetail.issue === \"INSTRUMENT_DECLINED\") {\n return actions.restart();\n // https://developer.paypal.com/docs/checkout/integration-features/funding-failure/\n }\n \n if (errorDetail) {\n let msg = \"Sorry, your transaction could not be processed.\";\n msg += errorDetail.description ? \" \" + errorDetail.description : \"\";\n msg += details.debug_id ? \" (\" + details.debug_id + \")\" : \"\";\n alert(msg);\n }\n \n const transaction = details.purchase_units[0].payments.captures[0];\n alert(\"Transaction \" + transaction.status + \": \" + transaction.id + \". See console for all available details\");\n }\n \n async function onCreateOrder(data, actions) {\n try {\n const response = await fetch(\"/api/orders\", {\n method: \"POST\",\n });\n \n const details = await response.json();\n return details.id;\n } catch (error) {\n console.error(error);\n }\n }\n \n async function onCaptureOrder(data, actions, orderID) {\n const orderId = data ? data.orderID : orderID;\n \n try {\n const response = await fetch(\\`/api/orders/\\${orderId}/capture\\`, {\n method: \"POST\",\n });\n \n const details = await response.json();\n handleTransactionCases(details);\n } catch (error) {\n console.error(error);\n }\n }\n \n \n FUNDING_SOURCES.forEach((fundingSource) => {\n paypal.Buttons({\n fundingSource,\n style: {\n layout: \"vertical\",\n shape: \"{{ buttonStyle }}\",\n color: fundingSource === paypal.FUNDING.PAYLATER ? \"gold\" : \"\",\n },\n createOrder: async (data, actions) => onCreateOrder(data, actions),\n onApprove: async (data, actions) => onCaptureOrder (data, actions, null),\n })\n .render(\"#paypal-button-container\");\n });\n \n // If this returns false or the card fields aren't visible, see Step #1.\n if (paypal.HostedFields.isEligible()) {\n let orderId;\n \n // Renders card fields\n paypal.HostedFields.render({\n // Call your server to set up the transaction\n createOrder: async (data, actions) => {\n orderId = await onCreateOrder(data, actions);\n return orderId;\n },\n styles: {\n \".valid\": {\n color: \"green\",\n },\n \".invalid\": {\n color: \"red\",\n },\n },\n fields: {\n number: {\n selector: \"#card-number\",\n placeholder: \"4111 1111 1111 1111\",\n },\n cvv: {\n selector: \"#cvv\",\n placeholder: \"123\",\n },\n expirationDate: {\n selector: \"#expiration-date\",\n placeholder: \"MM/YY\",\n },\n },\n }).then((cardFields) => {\n document.querySelector(\"#card-form\").addEventListener(\"submit\", async (event) => {\n event.preventDefault();\n try {\n const { value: cardHolderName } = document.getElementById(\"card-holder-name\");\n const { value: postalCode } = document.getElementById(\"card-billing-address-zip\");\n const { value: countryCodeAlpha2 } = document.getElementById(\"card-billing-address-country\");\n \n await cardFields.submit({\n cardHolderName,\n billingAddress: {\n postalCode,\n countryCodeAlpha2,\n },\n });\n \n await onCaptureOrder (null, null, orderId);\n } catch (error) {\n alert(\"Payment could not be captured! \" + JSON.stringify(error));\n }\n });\n });\n } else {\n // Hides card fields if the merchant isn't eligible\n document.querySelector(\"#card-form\").style = \"display: none\";\n }\n`,\n },\n {\n type: 'advanced',\n path: '/advance/html-node/',\n name: 'paypal-api.js',\n content: `{FALLBACK TEMPLATE CODE}\nimport fetch from \"node-fetch\";\n\n// set some important variables\nconst { CLIENT_ID, APP_SECRET } = process.env;\nconst base = \"https://api-m.sandbox.paypal.com\";\n\n// call the create order method\nexport async function createOrder() {\n const purchaseAmount = \"100.00\"; // TODO: pull prices from a database\n const accessToken = await generateAccessToken();\n const url = \\`\\${base}/v2/checkout/orders\\`;\n const response = await fetch(url, {\n method: \"post\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: \\`Bearer \\${accessToken}\\`,\n },\n body: JSON.stringify({\n intent: \"CAPTURE\",\n purchase_units: [\n {\n amount: {\n currency_code: \"USD\",\n value: purchaseAmount,\n },\n },\n ],\n }),\n });\n\n return handleResponse(response);\n}\n\n// capture payment for an order\nexport async function capturePayment(orderId) {\n const accessToken = await generateAccessToken();\n const url = \\`\\${base}/v2/checkout/orders/\\${orderId}/capture\\`;\n const response = await fetch(url, {\n method: \"post\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: \\`Bearer \\${accessToken}\\`,\n },\n });\n\n return handleResponse(response);\n}\n\n// generate access token\nexport async function generateAccessToken() {\n const auth = Buffer.from(CLIENT_ID + \":\" + APP_SECRET).toString(\"base64\");\n const response = await fetch(\\`\\${base}/v1/oauth2/token\\`, {\n method: \"post\",\n body: \"grant_type=client_credentials\",\n headers: {\n Authorization: \\`Basic \\${auth}\\`,\n },\n });\n const jsonData = await handleResponse(response);\n return jsonData.access_token;\n}\n\n// generate client token\nexport async function generateClientToken() {\n const accessToken = await generateAccessToken();\n const response = await fetch(\\`\\${base}/v1/identity/generate-token\\`, {\n method: \"post\",\n headers: {\n Authorization: \\`Bearer \\${accessToken}\\`,\n \"Accept-Language\": \"en_US\",\n \"Content-Type\": \"application/json\",\n },\n });\n console.log('response', response.status)\n const jsonData = await handleResponse(response);\n return jsonData.client_token;\n}\n\nasync function handleResponse(response) {\n if (response.status === 200 || response.status === 201) {\n return response.json();\n }\n\n const errorMessage = await response.text();\n throw new Error(errorMessage);\n}\n`,\n },\n {\n type: 'advanced',\n path: '/advance/html-node/public/',\n name: 'checkout.ejs',\n content: `{FALLBACK TEMPLATE CODE}\n\n\n \n \n \n \"\n >\n\n\n
\n
\n
\n \n
\n \n
\n \n
\n
\n
\n \n
\n
\n
\n \n \n
\n \n
\n
\n \n
\n

\n \n \n \n \n\n`,\n },\n {\n type: 'advanced',\n path: '/advance/3ds-node/public/',\n name: 'checkout.ejs',\n content: `{FALLBACK TEMPLATE CODE} \n\n \n \n \n \n \"\n >\n \n \n
\n
\n
\n \n
\n \n
\n \n
\n
\n
\n \n
\n
\n
\n \n \n
\n \n
\n
\n \n
\n

\n \n \n \n
\n \n \n\n`,\n },\n {\n type: 'advanced',\n path: '/advance/html-node/public/',\n name: 'index.html',\n content: `{FALLBACK TEMPLATE CODE}\n\n \n \n \n \n \n\n \n \n \n
\n
\n

OR

\n
\n \n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n \n
\n \n

\n \n \n
\n
\n \n`,\n },\n {\n type: 'advanced',\n path: '/advance/angular-node/angular/src/app/',\n name: 'app.component.html',\n content: `{FALLBACK TEMPLATE CODE}\n
\n
\n

OR

\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n
\n \n
\n \n
\n
\n

\n \n
\n
\n
`,\n },\n {\n type: 'advanced',\n path: '/advance/angular-node/angular/src/app/',\n name: 'app.component.ts',\n content: `{FALLBACK TEMPLATE CODE}\nimport { Component, ElementRef, ViewChild } from '@angular/core';\nimport { FormGroup, FormControl, FormBuilder, NgForm } from '@angular/forms';\nimport {\n IPayPalConfig,\n ICreateOrderRequest,\n PaypalLandingPage\n} from 'ngx-paypal';\n\ndeclare var paypal:any;\n// hostedFieldsInstance: paypal.hostedFields;\n \n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n title = 'Tour of Heroes';\n cardForm: any;\n cardFields: any;\n hostedForm: any;\n orderID: any;\n name: 'Name';\n country: 'Country Code';\n \n ngOnInit():void {\n hostedFieldsInstance: paypal.hostedFields;\n paypal.Buttons({\n fundingSource: [\n {{ fundingSources,list }}\n ],\n // Sets up the transaction when a payment button is clicked\n style: {\n layout: {{ buttonLayout }},\n shape: {{ buttonStyle }},\n color: (fundingSource==paypal.FUNDING.PAYLATER) ? 'gold' : '',\n }\n createOrder: function (data:any, actions:any) {\n return fetch(\"/api/orders\", {\n method: \"post\",\n // use the \"body\" param to optionally pass additional order information\n // like product ids or amount\n })\n .then((response) => response.json())\n .then((order) => order.id);\n },\n // Finalize the transaction after payer approval\n onApprove: function (data:any, actions:any) {\n return fetch(\\`/api/orders/\\${data.orderID}/capture\\`, {\n method: \"post\",\n })\n .then((response) => response.json())\n .then((orderData) => {\n console.log(\n \"Capture result\",\n orderData,\n JSON.stringify(orderData, null, 2)\n );\n const transaction = orderData.purchase_units[0].payments.captures[0];\n alert(\\`Transaction \\${transaction.status}: \\${transaction.id} See console for all available details\n \\`);\n });\n },\n })\n .render(\"#paypal-button-container\");\n // });\n \n if (paypal.HostedFields.isEligible()) {\n let orderId: any;\n // Renders card fields\n paypal.HostedFields.render({\n // Call your server to set up the transaction\n createOrder: () => {\n return fetch(\"/api/orders\", {\n method: \"post\",\n // use the \"body\" param to optionally pass additional order information like\n // product ids or amount.\n })\n .then((res) => res.json())\n .then((orderData) => {\n orderId = orderData.id; // needed later to complete capture\n this.orderID = orderData.id;\n return orderData.id;\n });\n },\n styles: {\n \".valid\": {\n color: \"green\",\n },\n \".invalid\": {\n color: \"red\",\n },\n },\n fields: {\n number: {\n selector: \"#card-number\",\n name: \"number\",\n placeholder: \"Card Number\",\n formControlName: \"hostedcardNumber\",\n ngModel:\"4111 1111 1111 1111\"\n },\n cvv: {\n selector: \"#cvv\",\n name: \"cvv\",\n placeholder: \"CVV\",\n formControlName: \"cvv\",\n ngModel:\"\"\n },\n expirationDate: {\n selector: \"#expiration-date\",\n placeholder: \"Expiration Date\",\n formControlName: \"expiration\",\n ngModel:\"\"\n },\n },\n }).then((hostedFieldsInstance:any) => {\n this.hostedForm = hostedFieldsInstance;\n console.log(this.hostedForm);\n });\n }\n }\n \n onSubmitForm(data:any){\n this.hostedForm.submit({\n // Cardholder's first and last name\n cardholderName: this.name,\n // Billing Address\n billingAddress: {\n countryCodeAlpha2: this.country,\n },\n }).then(() => {\n fetch(\\`/api/orders/\\${this.orderID}/capture\\`, {\n method: \"post\",\n })\n .then((res) => res.json())\n .then((orderData) => {\n const errorDetail =\n Array.isArray(orderData.details) && orderData.details[0];\n if (errorDetail) {\n var msg = \"Sorry, your transaction could not be processed.\";\n if (errorDetail.description)\n msg += \"\\\\n\\\\n\" + errorDetail.description;\n if (orderData.debug_id) msg += \" (\" + orderData.debug_id + \")\";\n return alert(msg); // Show a failure message\n }\n // Show a success message or redirect\n alert(\"Transaction completed! Transaction ID - \"+orderData.id);\n });\n })\n .catch((err:any) => {\n var msg = err.details[0].description;\n alert(\"Payment could not be captured! \\\\n Error - \"+msg+\" \\\\n Debug ID - \"+err.debug_id);\n });\n }\n}`,\n },\n {\n type: 'advanced',\n path: '/advance/angular-node/angular/src/app/',\n name: 'app.module.ts',\n content: `{FALLBACK TEMPLATE CODE}\nimport { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\n\nimport { AppComponent } from './app.component';\nimport { FormsModule, ReactiveFormsModule } from '@angular/forms';\nimport { NgxPayPalModule } from 'ngx-paypal';\n \n@NgModule({\n declarations: [\n AppComponent\n ],\n imports: [\n BrowserModule,\n FormsModule,\n ReactiveFormsModule,\n NgxPayPalModule\n ],\n providers: [],\n bootstrap: [AppComponent]\n})\nexport class AppModule {\n}`,\n },\n {\n type: 'advanced',\n path: '/advance/angular-node/angular/src/',\n name: 'index.html',\n content: `{FALLBACK TEMPLATE CODE}\n\n\n \n \n Angular Sample\n \n \n \n \n \n \n \n \n`,\n },\n {\n type: 'advanced',\n path: '/advance/angular-node/angular/src/',\n name: 'main.ts',\n content: `{FALLBACK TEMPLATE CODE}\nimport { platformBrowserDynamic } from '@angular/platform-browser-dynamic';\nimport { async } from 'rxjs';\nimport { __values } from 'tslib';\nimport { AppModule } from './app/app.module';\n\nconst script = document.createElement('script');\nconst client_id = '{{ clientId }}';\nlet token = fetch('/api/token', {\n method: \"post\",\n}).then((res) => res.json())\n.then((tokenData) => {\n const token = tokenData.client_token;\n script.src = \"https://www.paypal.com/sdk/js?client-id=\"+client_id+\"&locale=en_US&vault=false&enable-funding=venmo¤cy=USD&buyer-country=US&components=buttons,hosted-fields\";\n script.setAttribute('data-client-token',token);\n document.head.appendChild(script);\n});\nconsole.log(token);\n\nscript.onload = function() {\n platformBrowserDynamic().bootstrapModule(AppModule)\n .catch(err => console.error(err));\n}\n`,\n },\n {\n type: 'advanced',\n path: '/advance/react-node/advanced-integration/src/',\n name: 'App.js',\n content: `{FALLBACK TEMPLATE CODE}\nimport { PaymentForm } from \"./components/PaymentForm\";\nimport \"bootstrap/dist/css/bootstrap.css\";\nimport { useState, useEffect } from \"react\";\n \nconst App = (props) => {\n const [clientToken, setClientToken] = useState(null);\n //Replace Client ID and App Secret\n const clientId = \"{{ clientId }}\";\n useEffect(() => {\n (async () => {\n const response = await fetch(\"/api/token\", {\n method: \"post\",\n });\n const client_token = await response.json();\n setClientToken(client_token);\n })();\n }, []);\n return (\n <>\n
\n
\n {clientToken ? (\n \n ) : (

) }\n
\n
\n \n );\n}\n\nexport default App;`,\n },\n {\n type: 'advanced',\n path: '/advance/react-node/advanced-integration/public/',\n name: 'index.html',\n content: `{FALLBACK TEMPLATE CODE}\n\n \n \n \n \n \n \n \n \n \n \n React App\n \n \n \n \n
\n \n \n`,\n },\n {\n type: 'advanced',\n path: '/advance/react-node/advanced-integration/src/',\n name: 'index.js',\n content: `{FALLBACK TEMPLATE CODE}import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport App from './App';\nimport \"bootstrap/dist/css/bootstrap.css\";\n\nconst root = ReactDOM.createRoot(document.getElementById('root'));\nroot.render(\n \n \n \n);\n\n// If you want to start measuring performance in your app, pass a function\n// to log results (for example: reportWebVitals(console.log))\n// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals`,\n },\n {\n type: 'advanced',\n path: '/advance/react-node/advanced-integration/src/components/',\n name: 'PaymentForm.js',\n content: `{FALLBACK TEMPLATE CODE}\nimport { useState, useRef, useEffect } from \"react\";\nimport styles from \"./PaymentForm.module.css\";\n \nimport {\n PayPalScriptProvider,\n PayPalHostedFieldsProvider,\n PayPalHostedField,\n PayPalButtons,\n usePayPalHostedFields,\n usePayPalScriptReducer,\n} from \"@paypal/react-paypal-js\";\nimport { TailSpin } from \"react-loader-spinner\";\n \nexport const PaymentForm = (props) => {\n const [loader, showLoader] = useState(false);\n const [success, showSuccess] = useState(false);\n const [error, showErrorMsg] = useState(false);\n const [transactionData, setTransactionData] = useState();\n const [errorMsg, setErrorMsg] = useState();\n\n const SubmitPayment = () => {\n // Here declare the variable containing the hostedField instance\n const { cardFields } = usePayPalHostedFields();\n const cardHolderName = useRef(null);\n\n const submitHandler = () => {\n if (typeof cardFields.submit !== \"function\") return; // validate that \\`submit()\\` exists before using it\n if (errorMsg) showErrorMsg(false);\n showLoader(true);\n showSuccess(false);\n cardFields.submit({\n // The full name as shown in the card and billing addresss\n // These fields are optional for Sandbox but mandatory for production integration\n cardholderName: cardHolderName?.current?.value\n })\n .then((order) => {\n const { orderId } = order;\n\n fetch(\\`/api/orders/\\${orderId}/capture\\`, {method: \"post\"})\n .then((response) => response.json())\n .then((data) => {\n showLoader(false);\n showSuccess(true);\n setTransactionData(data);\n alert(\"Transaction Complete. Transaction ID - \"+data.id)\n // Inside the data you can find all the information related to the payment\n })\n .catch((err) => {\n // Handle capture order error\n showLoader(false);\n showErrorMsg(true);\n setErrorMsg(err);\n });\n })\n .catch((err) => {\n // Handle validate card fields error\n showLoader(false);\n showErrorMsg(true);\n setErrorMsg(err);\n });\n };\n\n return (\n \n Pay\n \n );\n };\n return (\n \n
\n \n
\n \n
\n

OR

\n
\n \n {\n // Here define the call to create and order\n return fetch(\"/api/orders\", {method: \"post\"})\n .then((response) => response.json())\n .then((order) => order.id)\n .catch((err) => {\n // Handle order creation error\n showLoader(false);\n showErrorMsg(true);\n setErrorMsg(err);\n });\n }}\n >\n \n
\n
\n
\n
\n \n\n
\n
\n \n
\n
\n \n
\n
\n \n \n\n \n\n {loader && }\n {!loader && }\n
\n
\n \n \n );\n};\n `,\n },\n {\n type: 'advanced',\n path: '/advance/react-node/server/',\n name: 'paypal-api.js',\n content: `{FALLBACK TEMPLATE CODE}\nimport fetch from \"node-fetch\";\nimport \"dotenv/config\";\n \n//Replace Client ID and App secret\nconst APP_CLIENT_ID = \"{{ clientId }}\";\nconst APP_CLIENT_SECRET = \"{{ appSecret }}\";\nconst base = \"https://api-m.sandbox.paypal.com\";\n \nexport async function createOrder() {\n const accessToken = await generateAccessToken();\n const url = \\`\\${base}/v2/checkout/orders\\`;\n const response = await fetch(url, {\n method: \"post\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: \\`Bearer \\${accessToken}\\`,\n },\n body: JSON.stringify({\n intent: \"CAPTURE\",\n purchase_units: [\n {\n amount: {\n currency_code: \"USD\",\n value: \"100.00\",\n },\n },\n ],\n }),\n });\n const data = await response.json();\n return data;\n}\n \nexport async function capturePayment(orderId) {\n const accessToken = await generateAccessToken();\n const url = \\`\\${base}/v2/checkout/orders/\\${orderId}/capture\\`;\n const response = await fetch(url, {\n method: \"post\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: \\`Bearer \\${accessToken}\\`,\n },\n });\n const data = await response.json();\n return data;\n}\n \nexport async function generateAccessToken() {\n const auth = Buffer.from(APP_CLIENT_ID + \":\" + APP_CLIENT_fSECRET).toString(\"base64\");\n const response = await fetch(\\`\\${base}/v1/oauth2/token\\`, {\n method: \"post\",\n body: \"grant_type=client_credentials\",\n headers: {\n Authorization: \\`Basic \\${auth}\\`,\n },\n });\n const { access_token } = await response.json();\n return access_token;\n}\n \nexport async function generateClientToken() {\n const accessToken = await generateAccessToken();\n const response = await fetch(\\`\\${base}/v1/identity/generate-token\\`, {\n method: \"post\",\n headers: {\n Authorization: \\`Bearer \\${accessToken}\\`,\n \"Accept-Language\": \"en_US\",\n \"Content-Type\": \"application/json\",\n },\n });\n console.log('response', response.status)\n const jsonData = await handleResponse(response);\n return jsonData.client_token;\n}`,\n },\n {\n type: 'advanced',\n path: '/advance/react-java/java-server/java-main/src/main/java/com/example/controller/',\n name: 'AcdcController.java',\n content: `{FALLBACK TEMPLATE CODE}\npackage com.example.controller;\nimport org.json.JSONException;\nimport org.json.JSONObject;\nimport org.springframework.http.HttpEntity;\nimport org.springframework.http.HttpHeaders;\nimport org.springframework.http.MediaType;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.util.LinkedMultiValueMap;\nimport org.springframework.util.MultiValueMap;\nimport org.springframework.web.bind.annotation.CrossOrigin;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\nimport org.springframework.web.client.RestTemplate;\n\nimport java.net.BindException;\nimport java.util.Arrays;\nimport java.util.Base64;\n\n@RestController\npublic class AcdcController {\n String client_id = \"{{ clientId }}\";\n String App_secret = \"{{ appSecret }}\";\n @RequestMapping(value = \"/\")\n public String index() {\n return \"/advanced-integration/public/index\";\n }\n\n @RequestMapping(\"/api/token\")\n public String generateClientToken() throws JSONException {\n String accessToken = \"Bearer \"+generateAccessToken();\n String url = \"https://api-m.sandbox.paypal.com/v1/identity/generate-token\";\n RestTemplate restTemplate = new RestTemplate();\n restTemplate = new RestTemplate();\n HttpHeaders headers = new HttpHeaders();\n headers.setContentType(MediaType.APPLICATION_JSON);\n headers.set(\"Authorization\", accessToken);\n headers.set(\"Accept-Language\", \"en_US\");\n String req= \"{}\";\n HttpEntity requestHeader = new HttpEntity(req, headers);\n ResponseEntity response = restTemplate.postForEntity(url, requestHeader, String.class);\n JSONObject jsonResponse = new JSONObject(response.getBody());\n return jsonResponse.toString();\n }\n\n @RequestMapping(\"/api/orders\")\n public String createOrder() throws JSONException {\n String accessToken = \"Bearer \" + generateAccessToken();\n RestTemplate restTemplate = new RestTemplate();\n restTemplate = new RestTemplate();\n HttpHeaders headers = new HttpHeaders();\n headers.setContentType(MediaType.APPLICATION_JSON);\n //PurchaseUnits purchaseJsonObject = new PurchaseUnits();\n headers.set(\"Authorization\", accessToken);\n JSONObject order = new JSONObject();\n JSONObject purchaseUnits = new JSONObject();\n JSONObject amount = new JSONObject();\n amount.put(\"value\", \"100.00\");\n amount.put(\"currency_code\", \"USD\");\n purchaseUnits.put(\"amount\", amount);\n order.put(\"purchaseunits\", Arrays.asList(purchaseUnits));\n order.put(\"intent\", \"capture\");\n\n //JsonObject purchaseJson = new JsonObject();\n String req = \"{\\\"intent\\\": \\\"CAPTURE\\\",\\\\n\" +\n \" \\\"purchase_units\\\": [\\\\n\" +\n \" {\\\\n\" +\n \" \\\"amount\\\": {\\\\n\" +\n \" \\\"currency_code\\\": \\\"USD\\\",\\\\n\" +\n \" \\\"value\\\": \\\"83.04\\\"\\\\n\" +\n \" }\\\\n\" +\n \" }\\\\n\" +\n \" ]\\\\n\" +\n \"}\";\n HttpEntity requestHeader = new HttpEntity(req, headers);\n String url = \"https://api-m.sandbox.paypal.com/v2/checkout/orders\";\n ResponseEntity response = restTemplate.postForEntity(url, requestHeader, String.class);\n //System.out.println(response.toString());\n String responseString = response.toString();\n JSONObject jsonResponse = new JSONObject(response.getBody());\n String orderId = jsonResponse.getString(\"id\");\n return jsonResponse.toString();\n }\n\n @RequestMapping(\"/api/orders/{orderId}/capture\")\n public String capturePayment(@PathVariable(\"orderId\") String orderId) throws JSONException {\n String accessToken = \"Bearer \" + generateAccessToken();\n return capturePayment(accessToken, String.valueOf(orderId));\n }\n \n public String capturePayment(String accessToken,String orderId) throws JSONException {\n RestTemplate restTemplate = new RestTemplate();\n restTemplate = new RestTemplate();\n HttpHeaders headers = new HttpHeaders();\n headers.setContentType(MediaType.APPLICATION_JSON);\n headers.set(\"Authorization\", accessToken);\n String req= \"{}\";\n HttpEntity requestHeader = new HttpEntity(req, headers);\n String url = \"https://api-m.sandbox.paypal.com/v2/checkout/orders/\" + orderId + \"/capture\";\n ResponseEntity response = restTemplate.postForEntity(url, requestHeader, String.class);\n //System.out.println(response.toString());\n String responseString = response.toString();\n JSONObject jsonResponse = new JSONObject(response.getBody());\n String orderIds = jsonResponse.getString(\"id\");\n return jsonResponse.toString();\n }\n\n public String generateAccessToken() throws JSONException {\n String clientIdSecret = client_id + \":\" + App_secret;\n String encodedClientId = Base64.getEncoder().encodeToString(clientIdSecret.getBytes());\n System.out.println(\"Client Id= \" + encodedClientId);\n String template = \"Basic \" + encodedClientId;\n RestTemplate restTemplate = new RestTemplate();\n restTemplate = new RestTemplate();\n HttpHeaders headers = new HttpHeaders();\n headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);\n headers.set(\"Authorization\", template);\n MultiValueMap map = new LinkedMultiValueMap<>();\n map.add(\"grant_type\",\"client_credentials\");\n map.add(\"response_type\",\"token\");\n map.add(\"ignoreCache\",\"true\");\n HttpEntity requestHeader = new HttpEntity( map,headers);\n String url = \"https://api-m.sandbox.paypal.com/v1/oauth2/token\";\n ResponseEntity response = restTemplate.postForEntity(url, requestHeader, String.class);\n //System.out.println(response.toString());\n JSONObject jsonResponse = new JSONObject(response.getBody());\n String accessToken = jsonResponse.getString(\"access_token\");\n return accessToken;\n }\n\n}`,\n },\n {\n type: 'advanced',\n path: '/advance/html-java/',\n name: 'index.java',\n content: `{FALLBACK TEMPLATE CODE}package com.example;\n\nimport org.json.JSONException;\nimport org.json.JSONObject;\nimport org.springframework.http.HttpEntity;\nimport org.springframework.http.HttpHeaders;\nimport org.springframework.http.MediaType;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.util.LinkedMultiValueMap;\nimport org.springframework.util.MultiValueMap;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestBody;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\nimport org.springframework.web.client.RestTemplate;\n\nimport java.util.Arrays;\nimport java.util.Base64;\n\n@RestController\npublic class Index {\n String client_id = \"{{ clientId }}\";\n String App_secret = \"{{ appSecret }}\";\n\n @RequestMapping(\"/api/orders\")\n public String createOrder() throws JSONException {\n String accessToken = \"Bearer \" + generateAccessToken();\n RestTemplate restTemplate = new RestTemplate();\n restTemplate = new RestTemplate();\n HttpHeaders headers = new HttpHeaders();\n headers.setContentType(MediaType.APPLICATION_JSON);\n //PurchaseUnits purchaseJsonObject = new PurchaseUnits();\n headers.set(\"Authorization\", accessToken);\n JSONObject order = new JSONObject();\n JSONObject purchaseUnits = new JSONObject();\n JSONObject amount = new JSONObject();\n amount.put(\"value\", \"100.00\");\n amount.put(\"currency_code\", \"USD\");\n purchaseUnits.put(\"amount\", amount);\n order.put(\"purchaseunits\", Arrays.asList(purchaseUnits));\n order.put(\"intent\", \"capture\");\n\n //JsonObject purchaseJson = new JsonObject();\n String req = \"{\\\\\"intent\\\\\": \\\\\"CAPTURE\\\\\",\\\\n\" +\n \" \\\\\"purchase_units\\\\\": [\\\\n\" +\n \" {\\\\n\" +\n \" \\\\\"amount\\\\\": {\\\\n\" +\n \" \\\\\"currency_code\\\\\": \\\\\"USD\\\\\",\\\\n\" +\n \" \\\\\"value\\\\\": \\\\\"83.04\\\\\"\\\\n\" +\n \" }\\\\n\" +\n \" }\\\\n\" +\n \" ]\\\\n\" +\n \"}\";\n\n\n HttpEntity requestHeader = new HttpEntity(req, headers);\n String url = \"https://api-m.sandbox.paypal.com/v2/checkout/orders\";\n ResponseEntity response = restTemplate.postForEntity(url, requestHeader, String.class);\n //System.out.println(response.toString());\n String responseString = response.toString();\n JSONObject jsonResponse = new JSONObject(response.getBody());\n String orderId = jsonResponse.getString(\"id\");\n return jsonResponse.toString();\n }\n\n @RequestMapping(\"/api/orders/{orderId}/capture\")\n public String capturePayment(@PathVariable(\"orderId\") String orderId) throws JSONException {\n String accessToken = \"Bearer \" + generateAccessToken();\n return capturePayment(accessToken, String.valueOf(orderId));\n\n }\n\n public String capturePayment(String accessToken,String orderId) throws JSONException {\n RestTemplate restTemplate = new RestTemplate();\n restTemplate = new RestTemplate();\n HttpHeaders headers = new HttpHeaders();\n headers.setContentType(MediaType.APPLICATION_JSON);\n headers.set(\"Authorization\", accessToken);\n String req= \"{}\";\n HttpEntity requestHeader = new HttpEntity(req, headers);\n String url = \"https://api-m.sandbox.paypal.com/v2/checkout/orders/\" + orderId + \"/capture\";\n ResponseEntity response = restTemplate.postForEntity(url, requestHeader, String.class);\n //System.out.println(response.toString());\n String responseString = response.toString();\n JSONObject jsonResponse = new JSONObject(response.getBody());\n String orderIds = jsonResponse.getString(\"id\");\n return jsonResponse.toString();\n }\n\n public String generateAccessToken() throws JSONException {\n String clientIdSecret = client_id + \":\" + App_secret;\n String encodedClientId = Base64.getEncoder().encodeToString(clientIdSecret.getBytes());\n System.out.println(\"Client Id= \" + encodedClientId);\n String template = \"Basic \" + encodedClientId;\n RestTemplate restTemplate = new RestTemplate();\n restTemplate = new RestTemplate();\n HttpHeaders headers = new HttpHeaders();\n headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);\n headers.set(\"Authorization\", template);\n MultiValueMap map = new LinkedMultiValueMap<>();\n map.add(\"grant_type\",\"client_credentials\");\n map.add(\"response_type\",\"token\");\n map.add(\"ignoreCache\",\"true\");\n HttpEntity requestHeader = new HttpEntity( map,headers);\n String url = \"https://api-m.sandbox.paypal.com/v1/oauth2/token\";\n ResponseEntity response = restTemplate.postForEntity(url, requestHeader, String.class);\n //System.out.println(response.toString());\n JSONObject jsonResponse = new JSONObject(response.getBody());\n String accessToken = jsonResponse.getString(\"access_token\");\n return accessToken;\n }\n\n @RequestMapping(\"/api/token\")\n public String generateClientToken() throws JSONException {\n String accessToken = \"Bearer \"+generateAccessToken();\n String url = \"https://api-m.sandbox.paypal.com/v1/identity/generate-token\";\n RestTemplate restTemplate = new RestTemplate();\n restTemplate = new RestTemplate();\n HttpHeaders headers = new HttpHeaders();\n headers.setContentType(MediaType.APPLICATION_JSON);\n headers.set(\"Authorization\", accessToken);\n headers.set(\"Accept-Language\", \"en_US\");\n String req= \"{}\";\n HttpEntity requestHeader = new HttpEntity(req, headers);\n ResponseEntity response = restTemplate.postForEntity(url, requestHeader, String.class);\n JSONObject jsonResponse = new JSONObject(response.getBody());\n return jsonResponse.toString();\n }\n\n}`,\n },\n {\n type: 'advanced',\n path: '/advance/react-java/java-server/java-main/src/main/java/com/example/',\n name: 'WebApplication.java',\n content: `{FALLBACK TEMPLATE CODE}\npackage com.example;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n\n@SpringBootApplication\npublic class WebApplication {\n public static void main(String[] args) {\n SpringApplication.run(WebApplication.class, args);\n System.out.println(\"#@# started\");\n }\n}`,\n },\n {\n type: 'advanced',\n path: '/advance/html-node/',\n name: 'index.js',\n content: `{FALLBACK TEMPLATE CODE}\nimport fetch from \"node-fetch\";\n\nconst CLIENT_ID = '{{ clientId }}';\nconst APP_SECRET = '{{ appSecret }}';\nconst base = \"https://api-m.sandbox.paypal.com\";\n\n// call the create order method\nexport async function createOrder() {\n const purchaseAmount = \"100.00\";\n const accessToken = await generateAccessToken();\n const url = \\`\\${base}/v2/checkout/orders\\`;\n const response = await fetch(url, {\n method: \"post\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: \\`Bearer \\${accessToken}\\`,\n },\n body: JSON.stringify({\n intent: \"CAPTURE\",\n purchase_units: [\n {\n amount: {\n currency_code: \"USD\",\n value: purchaseAmount,\n },\n },\n ],\n }),\n });\n\n return handleResponse(response);\n}\n\n// capture payment for an order\nexport async function capturePayment(orderId) {\n const accessToken = await generateAccessToken();\n const url = \\`\\${base}/v2/checkout/orders/\\${orderId}/capture\\`;\n const response = await fetch(url, {\n method: \"post\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: \\`Bearer \\${accessToken}\\`,\n },\n });\n\n return handleResponse(response);\n}\n\n// generate access token\nexport async function generateAccessToken() {\n const auth = Buffer.from(CLIENT_ID + \":\" + APP_SECRET).toString(\"base64\");\n const response = await fetch(\\`\\${base}/v1/oauth2/token\\`, {\n method: \"post\",\n body: \"grant_type=client_credentials\",\n headers: {\n Authorization: \\`Basic \\${auth}\\`,\n },\n });\n const jsonData = await handleResponse(response);\n return jsonData.access_token;\n}\n\n// generate client token\nexport async function generateClientToken() {\n const accessToken = await generateAccessToken();\n const response = await fetch(\\`\\${base}/v1/identity/generate-token\\`, {\n method: \"post\",\n headers: {\n Authorization: \\`Bearer \\${accessToken}\\`,\n \"Accept-Language\": \"en_US\",\n \"Content-Type\": \"application/json\",\n },\n });\n console.log('response', response.status)\n const jsonData = await handleResponse(response);\n return jsonData.client_token;\n}\n\nasync function handleResponse(response) {\n if (response.status === 200 || response.status === 201) {\n return response.json();\n }\n\n const errorMessage = await response.text();\n throw new Error(errorMessage);\n}`,\n },\n {\n type: 'advanced',\n path: '/advance/html-node/',\n name: 'server.js',\n content: `{FALLBACK TEMPLATE CODE}\nimport \"dotenv/config\";\nimport express from \"express\";\nimport * as paypal from \"./paypal-api.js\";\n\nconst app = express();\napp.set(\"view engine\", \"ejs\");\napp.use(express.static(\"public\"));\n\n// render checkout page with client id & unique client token\napp.get(\"/\", async (req, res) => {\n const clientId = process.env.CLIENT_ID;\n try {\n const clientToken = await paypal.generateClientToken();\n res.render(\"checkout\", { clientId, clientToken });\n } catch (err) {\n res.status(500).send(err.message);\n }\n});\n\n// create order\napp.post(\"/api/orders\", async (req, res) => {\n try {\n const order = await paypal.createOrder();\n res.json(order);\n } catch (err) {\n res.status(500).send(err.message);\n }\n});\n\n// capture payment\napp.post(\"/api/orders/:orderID/capture\", async (req, res) => {\n const { orderID } = req.params;\n try {\n const captureData = await paypal.capturePayment(orderID);\n res.json(captureData);\n } catch (err) {\n res.status(500).send(err.message);\n }\n});\n\napp.listen(9597, () => {\n console.log(\"listening on http://localhost:9597/\");\n});\n `,\n },\n {\n type: 'standard',\n path: '/standard/html-python/',\n name: 'server.py',\n content: `{FALLBACK TEMPLATE CODE}from flask import Flask, send_file\n import requests\n import json\n app = Flask(__name__)\n \n # https://developer.paypal.com/api/rest/authentication/\n def get_access_token():\n client_id = '{{ clientId }}'\n app_secret = '{{ appSecret }}'\n url = \"https://api-m.sandbox.paypal.com/v1/oauth2/token\"\n response = requests.post(url, data={\"grant_type\": \"client_credentials\"}, auth=(client_id,app_secret))\n data = response.json()\n if data.get('error'):\n raise Exception(data)\n return data['access_token']\n \n # https://developer.paypal.com/docs/api/orders/v2/#orders_create\n def create_order():\n url = \"https://api-m.sandbox.paypal.com/v2/checkout/orders\"\n payload = {\n 'intent': 'CAPTURE',\n 'purchase_units': [{\n \"amount\": {\n \"currency_code\": \"USD\",\n \"value\": \"0.02\"\n }\n }]\n }\n headers = {\n 'Authorization': f\"Bearer {get_access_token()}\",\n 'Content-Type': 'application/json'\n }\n response = requests.post(url, headers = headers, data = json.dumps(payload))\n data = response.json()\n if data.get('error'):\n raise Exception(data)\n return data\n \n # https://developer.paypal.com/docs/api/orders/v2/#orders_capture\n def capture_payment(order_id):\n url = f\"https://api-m.sandbox.paypal.com/v2/checkout/orders/{order_id}/capture\"\n headers = {\n 'Authorization': f\"Bearer {get_access_token()}\",\n 'Content-Type': 'application/json'\n }\n response = requests.post(url, headers = headers)\n data = response.json()\n if data.get('error'):\n raise Exception(data)\n return data\n \n @app.route('/')\n def index():\n return send_file(\"./index.html\")\n \n @app.route('/orders', methods = ['POST'])\n def process_create_order():\n return create_order()\n \n @app.route('/orders//capture', methods = ['POST'])\n def process_capture_payment(order_id): \n return capture_payment(order_id)\n \n if __name__ == '__main__':\n app.run()`,\n },\n {\n type: 'standard',\n path: '/standard/html-php/',\n name: 'server.php',\n content: `{FALLBACK TEMPLATE CODE} 'client_credentials',\n ]);\n $ch = curl_init();\n curl_setopt($ch, CURLOPT_URL, $url);\n curl_setopt($ch, CURLOPT_USERPWD, $client_id . \":\" . $app_secret);\n curl_setopt($ch, CURLOPT_POST, true);\n curl_setopt($ch, CURLOPT_POSTFIELDS, $data);\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); \n $result = json_decode(curl_exec($ch));\n if(isset($result->error)){\n throw new Exception($result->error_description);\n }\n return $result->access_token;\n }\n\n // https://developer.paypal.com/docs/api/orders/v2/#orders_create\n function create_order(){\n $url = \"https://api-m.sandbox.paypal.com/v2/checkout/orders\";\n $data = json_encode([\n 'intent' => 'CAPTURE',\n 'purchase_units' => [\n [\n \"amount\" => [\n \"currency_code\" => \"USD\",\n \"value\" => \"0.02\"\n ]\n ]\n ]\n ]);\n $ch = curl_init();\n curl_setopt($ch, CURLOPT_URL, $url);\n curl_setopt($ch, CURLOPT_POST, true);\n curl_setopt($ch, CURLOPT_POSTFIELDS, $data);\n curl_setopt($ch, CURLOPT_HTTPHEADER, [\n 'Content-Type:application/json',\n 'Authorization: Bearer ' . get_access_token()\n ]);\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); \n $result = json_decode(curl_exec($ch));\n if(isset($result->error)){\n throw new Exception($result->error_description);\n }\n return $result;\n }\n\n // https://developer.paypal.com/docs/api/orders/v2/#orders_capture\n function capture_payment($orderID){\n $url = \"https://api-m.sandbox.paypal.com/v2/checkout/orders/\" . $orderID . \"/capture\";\n $ch = curl_init();\n curl_setopt($ch, CURLOPT_URL, $url);\n curl_setopt($ch, CURLOPT_POST, true);\n curl_setopt($ch, CURLOPT_HTTPHEADER, [\n 'Content-Type:application/json',\n 'Authorization: Bearer ' . get_access_token()\n ]);\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); \n $result = json_decode(curl_exec($ch));\n if(isset($result->error)){\n throw new Exception($result->error_description);\n }\n return $result;\n }\n\n $json = json_decode(file_get_contents('php://input'));\n if(isset($json->orderID)){\n // capture the order\n echo json_encode(capture_payment($json->orderID));\n // echo json_encode();\n } else {\n // create the order\n echo json_encode(create_order());\n }\n?>`,\n },\n {\n type: 'advanced',\n path: '/advance/html-python/',\n name: 'index.py',\n content: `{FALLBACK TEMPLATE CODE}import http.server\n # from aioflask import Flask, request, jsonify, after_this_request, send_file, render_template\n from flask import Flask, request, jsonify, after_this_request, send_file, render_template\n import socketserver\n import requests\n import base64\n \n PORT = 8000\n app = Flask(__name__)\n base = \"https://api-m.sandbox.paypal.com\"\n \n CLIENT_ID = '{{ clientId }}'\n APP_SECRET = '{{ appSecret }}'\n \n \n @app.route('/')\n async def index():\n token = await generateClientToken()\n return render_template(\"index.html\", token=token)\n \n \n @app.route('/api/orders', methods=['POST'])\n async def createOrder():\n purchase_amount = \"100.00\"\n access_token = await generateAccessToken()\n # access_token = \"Bearer {{ appSecret }}\"\n URL = base+\"/v2/checkout/orders\"\n headers = {\"Content-Type\": \"application/json\", \"Authorization\": \"Bearer \"+access_token}\n data = {\"intent\": \"CAPTURE\", \"purchase_units\": [{\"amount\": {\"currency_code\": \"USD\", \"value\": purchase_amount}}]}\n response = requests.post(url=URL, headers=headers, json=data)\n resp = await handleResponse(response)\n return resp\n \n \n @app.route('/api/orders//capture', methods=['POST'])\n async def captureOrder(orderID):\n # access_token = \"{{ appSecret }}\"\n access_token = await generateAccessToken()\n URL = base+\"/v2/checkout/orders/\"+orderID+\"/capture\"\n headers = {\"Content-Type\": \"application/json\", \"Authorization\": \"Bearer \"+access_token}\n response = requests.post(url=URL, headers=headers)\n resp = await handleResponse(response)\n return resp\n \n \n async def generateClientToken():\n access_token = await generateAccessToken()\n URL = base+\"/v1/identity/generate-token\"\n headers = {\"Authorization\": \"Bearer \"+access_token, \"Accept-Language\": \"en_US\", \"Content-Type\": \"application/json\"}\n response = requests.post(url=URL, headers=headers)\n data = response.json()\n if data.get('error'):\n raise Exception(data)\n return data['client_token']\n \n \n async def generateAccessToken():\n url = \"https://api-m.sandbox.paypal.com/v1/oauth2/token\"\n response = requests.post(url, data={\"grant_type\": \"client_credentials\"}, auth=(CLIENT_ID, APP_SECRET))\n data = response.json()\n if data.get('error'):\n raise Exception(data)\n return data['access_token']\n \n \n async def handleResponse(response):\n if response.status_code == 200 or response.status_code == 201:\n return response.json()\n error_message = response.text\n raise Exception(error_message)\n \n \n app.run(host='localhost', port=8000)`,\n },\n {\n type: 'advanced',\n path: '/advance/angular-python/',\n name: 'server.py',\n content: `{FALLBACK TEMPLATE CODE}import http.server\n # from aioflask import Flask, request, jsonify, send_file\n from flask import Flask, request, jsonify, after_this_request, send_file\n import socketserver\n import requests\n import base64\n \n PORT = 8000\n app = Flask(__name__)\n base = \"https://api-m.sandbox.paypal.com\"\n \n CLIENT_ID = '{{ clientId }}'\n APP_SECRET = '{{ appSecret }}'\n \n \n @app.route('/')\n def index():\n return send_file(\"templates/index.html\")\n \n \n @app.route('/api/orders', methods=['POST'])\n async def createOrder():\n purchase_amount = \"100.00\"\n access_token = await generateAccessToken()\n # access_token = \"Bearer {{ appSecret }}\"\n URL = base+\"/v2/checkout/orders\"\n headers = {\"Content-Type\": \"application/json\", \"Authorization\": \"Bearer \"+access_token}\n data = {\"intent\": \"CAPTURE\", \"purchase_units\": [{\"amount\": {\"currency_code\": \"USD\", \"value\": purchase_amount}}]}\n response = requests.post(url=URL, headers=headers, json=data)\n print(response)\n resp = await handleResponse(response)\n print(resp)\n return resp\n \n \n @app.route('/api/orders//capture', methods=['POST'])\n async def captureOrder(orderID):\n # access_token = \"{{ appSecret }}\"\n access_token = await generateAccessToken()\n URL = base+\"/v2/checkout/orders/\"+orderID+\"/capture\"\n headers = {\"Content-Type\": \"application/json\", \"Authorization\": \"Bearer \"+access_token}\n response = requests.post(url=URL, headers=headers)\n resp = await handleResponse(response)\n return resp\n \n @app.route('/api/token', methods=['POST'])\n async def generateClientToken():\n access_token = await generateAccessToken()\n URL = \"https://api-m.sandbox.paypal.com/v1/identity/generate-token\"\n headers = {\"Authorization\": \"Bearer \"+access_token, \"Accept-Language\": \"en_US\", \"Content-Type\": \"application/json\"}\n response = requests.post(url=URL, headers=headers)\n json_data = await handleResponse(response)\n return json_data\n \n \n async def generateAccessToken():\n url = \"https://api-m.sandbox.paypal.com/v1/oauth2/token\"\n response = requests.post(url, data={\"grant_type\": \"client_credentials\"}, auth=(CLIENT_ID, APP_SECRET))\n data = response.json()\n if data.get('error'):\n raise Exception(data)\n return data['access_token']\n \n \n async def handleResponse(response):\n print(response.status_code)\n if response.status_code == 200 or response.status_code == 201:\n return response.json()\n error_message = response.text\n raise Exception(error_message)\n \n \n app.run(host='localhost', port=8000)`,\n },\n {\n type: 'advanced',\n path: '/advance/html-php/',\n name: 'index.php',\n content: `{FALLBACK TEMPLATE CODE} 'client_credentials',\n ]);\n $ch = curl_init();\n curl_setopt($ch, CURLOPT_URL, $url);\n curl_setopt($ch, CURLOPT_USERPWD, $client_id . \":\" . $app_secret);\n curl_setopt($ch, CURLOPT_POST, true);\n curl_setopt($ch, CURLOPT_POSTFIELDS, $data);\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); \n $result = json_decode(curl_exec($ch));\n if(isset($result->error)){\n throw new Exception($result->error_description);\n }\n return $result->access_token;\n }\n\n // https://developer.paypal.com/docs/api/orders/v2/#orders_create\n function create_order(){\n $url = \"https://api-m.sandbox.paypal.com/v2/checkout/orders\";\n $data = json_encode([\n 'intent' => 'CAPTURE',\n 'purchase_units' => [\n [\n \"amount\" => [\n \"currency_code\" => \"USD\",\n \"value\" => \"0.02\"\n ]\n ]\n ]\n ]);\n $ch = curl_init();\n curl_setopt($ch, CURLOPT_URL, $url);\n curl_setopt($ch, CURLOPT_POST, true);\n curl_setopt($ch, CURLOPT_POSTFIELDS, $data);\n curl_setopt($ch, CURLOPT_HTTPHEADER, [\n 'Content-Type:application/json',\n 'Authorization: Bearer {{ appSecret }}' \n ]);\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); \n $result = json_decode(curl_exec($ch));\n if(isset($result->error)){\n throw new Exception($result->error_description);\n }\n return $result;\n }\n\n // https://developer.paypal.com/docs/api/orders/v2/#orders_capture\n function capture_payment($orderID){\n $url = \"https://api-m.sandbox.paypal.com/v2/checkout/orders/\" . $orderID . \"/capture\";\n $ch = curl_init();\n curl_setopt($ch, CURLOPT_URL, $url);\n curl_setopt($ch, CURLOPT_POST, true);\n curl_setopt($ch, CURLOPT_HTTPHEADER, [\n 'Content-Type:application/json',\n 'Authorization: Bearer ' . get_access_token()\n ]);\n curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); \n $result = json_decode(curl_exec($ch));\n if(isset($result->error)){\n throw new Exception($result->error_description);\n }\n return $result;\n }\n\n $json = json_decode(file_get_contents('php://input'));\n if(isset($json->orderID)){\n // capture the order\n echo json_encode(capture_payment($json->orderID));\n // echo json_encode();\n } else {\n // create the order\n echo json_encode(create_order());\n }\n?>`,\n },\n // {\n // type: 'advanced',\n // path: '/advance/html-node/public/',\n // name: 'index.html',\n // content: `{FALLBACK TEMPLATE CODE}`,\n // },\n]\n","import { DropdownMenu, Icon } from '@paypalcorp/pp-react'\nimport React, {\n EventHandler,\n FunctionComponent,\n useContext,\n useEffect,\n useState,\n} from 'react'\nimport CodeBlock from '../../../components/layout/CodeBlock/CodeBlock'\nimport styles from '../integration-builder.module.css'\nimport { CheckoutSimulatorContext } from '../../../components/integration-builder/context/CheckoutSimulatorContext'\nimport { SnippetSchemaEnvironmentSampleFile } from '../../../components/integration-builder/code-selector/code-snippets/interfaces'\nimport withAnalytics from '../../../utils/withAnalytics'\nimport { CopyButton } from '../../../components/layout'\nimport { fileTypeOf } from '../../../utils'\nimport { codePreviewParser } from '../../../components/integration-builder/code-selector/code-snippets/helpers/codePreviewParser'\nimport templates from '../../../components/integration-builder/code-selector/code-snippets/checkout/templates'\nimport { codeSamplesUrl } from '../../../lib/assetsUrl'\nimport { File } from '../../../components/integration-builder/code-selector/code-snippets/interfaces/File'\nimport { CodeSelectorOption } from '../../../components/integration-builder/code-selector/interfaces'\n\nconst Code: FunctionComponent = () => {\n type FileOption = {\n value: string\n primaryText: string\n }\n\n const fptiData = typeof window !== `undefined` && window.fpti\n const [isCopied, setIsCopied] = React.useState(false)\n\n const [files, setFiles] = useState([])\n const [fileOptions, setFileOptions] = useState([])\n const [selectedFile, setSelectedFile] = useState('')\n\n const [selectedLanguage, setSelectedLanguage] = useState('html')\n const [selectedCodeSample, setSelectedCodeSample] = useState('')\n const {\n integrationType,\n snippets = {},\n parameters,\n options,\n } = useContext(CheckoutSimulatorContext)\n\n const [backendFiles, setBackendFiles] =\n useState()\n const [frontendFiles, setFrontendFiles] =\n useState()\n\n const getFallbackTemplate = (file: SnippetSchemaEnvironmentSampleFile) => {\n let templateFileCode = templates.find(\n (template) =>\n template.type === file?.type &&\n template.path === file?.path &&\n template.name === file?.name,\n )\n\n if (!templateFileCode) {\n setSelectedCodeSample('TEMPLATE NOT FOUND')\n return\n }\n\n setSelectedCodeSample(\n codePreviewParser(templateFileCode?.content!, { ...parameters, options }),\n )\n }\n\n /**\n * Function that builds the URL based on the integration,\n * option, and language buttons\n * @param baseUrl\n * @param paymentModel\n * @param file\n * @return url\n */\n const urlBuilder = (\n baseUrl: string,\n paymentModel: string,\n frontEndLaguage: string,\n buttons: string[],\n file: File,\n ): string => {\n let model = ''\n if (file.type === 'standard') {\n model =\n paymentModel === 'onetime-payment'\n ? 'one-time-payment/'\n : 'subscription-payment/'\n return `${baseUrl}/templates/${file.type}/${model}${file.fullPath}`\n }\n\n //If the type is advanced, check if 3DS option is selected or not. (Edge Case)\n if (file.name === 'checkout.ejs') {\n const path =\n buttons.includes('payment-buttons_3ds') && frontEndLaguage === 'html'\n ? `card-fields-with-3ds/server/html/views/${file.name}`\n : `card-fields/server/nodejs/html/views/${file.name}`\n return `${baseUrl}/templates/${file.type}/${path}`\n }\n\n model =\n buttons.includes('payment-buttons_3ds') && frontEndLaguage === 'html'\n ? 'card-fields-with-3ds/'\n : 'card-fields/'\n return `${baseUrl}/templates/${file.type}/${model}${file.fullPath}`\n }\n\n /**\n * This function is incharge of updating the code samples based on\n * the options and parameters selected.\n * @param fileName\n * @param option Takes the frontend language passed\n * @returns\n */\n const updateCodeSample = (fileName: string, option: CodeSelectorOption) => {\n const file = files.find((file) => file.name === fileName)\n if (!file) return\n const { value } = option\n const frontEndLanguageSelected: string | undefined = value as string\n const url = urlBuilder(\n codeSamplesUrl,\n parameters?.paymentModel,\n frontEndLanguageSelected,\n parameters?.buttons,\n file,\n )\n\n fetch(url, { method: 'GET', redirect: 'follow' })\n .then((res) => {\n if (res.status === 404) {\n getFallbackTemplate(file)\n throw new Error('CDN template not found')\n }\n return res.text()\n })\n .then((content) => {\n setSelectedCodeSample(\n codePreviewParser(content, { ...parameters, options }),\n )\n })\n .catch(() => {\n getFallbackTemplate(file)\n })\n }\n\n useEffect(() => {\n if (!snippets.backend || !snippets.frontend) return\n setBackendFiles(snippets.backend)\n setFrontendFiles(snippets.frontend)\n\n let file: string\n\n file =\n [...snippets.frontend, ...snippets.backend].find(\n (snippet) => snippet.name === selectedFile,\n )?.name || ''\n\n if (!file && snippets.frontend[0]) file = snippets.frontend[0].name\n if (!file && snippets.backend[0]) file = snippets.backend[0].name\n\n updateCodeSample(file, options[1])\n setSelectedFile(file)\n setSelectedLanguage(fileTypeOf(file))\n }, [snippets])\n\n useEffect(() => {\n if (!frontendFiles || !backendFiles) return\n setFiles([...frontendFiles!, ...backendFiles!])\n }, [backendFiles, frontendFiles, parameters])\n\n useEffect(() => {\n setFileOptions(\n files.map((file) => ({\n value: file.name,\n primaryText: file.name,\n file,\n })),\n )\n updateCodeSample(selectedFile, options[1])\n }, [files])\n\n const handleOnChangeFile: EventHandler = (event: any) => {\n setSelectedFile(event.target.value)\n setSelectedLanguage(fileTypeOf(event.target.value))\n updateCodeSample(event.target.value, options[1])\n }\n\n const copySampleFile = async (selectedFile: string) => {\n setIsCopied(true)\n try {\n await navigator.clipboard.writeText(selectedCodeSample)\n } catch (err) {\n console.error('Failed to copy to clipboard')\n }\n if (fptiData && window.PAYPAL?.analytics?.instance) {\n const event = `code:${selectedFile}_${\n integrationType === 'standard' ? 'sc' : 'ac'\n }`\n window.PAYPAL.analytics.instance.record({\n data: {\n component: 'devdiscoverynodeweb',\n page: 'main:developer:integration-builder',\n pgrp: 'main:developer:integration-builder',\n e: 'cl',\n link: event,\n event_action: event,\n ...fptiData,\n },\n })\n }\n setTimeout(() => setIsCopied(false), 3000)\n }\n\n return (\n
\n
\n \n copySampleFile(selectedFile)}>\n {isCopied ? (\n \n ) : (\n \n )}\n \n
\n \n {selectedCodeSample}\n \n
\n )\n}\n\nexport default withAnalytics(Code)\n"],"sourceRoot":""}