Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support for braintree payments #261

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions packages/api-client/src/api/getBraintreeToken/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import axios from 'axios';
import { ApiContext, BraintreeToken } from '../../types';
import getCurrentBearerOrCartToken from '../authentication/getCurrentBearerOrCartToken';
import getAuthorizationHeaders from '../authentication/getAuthorizationHeaders';
import { Logger } from '@vue-storefront/core';

export default async function getBraintreeToken({ client, config }: ApiContext, methodId: number): Promise<BraintreeToken> {
try {
const token = await getCurrentBearerOrCartToken({ client, config });
const currency = await config.internationalization.getCurrency();
const endpoint = config.backendUrl.concat('/api/v2/braintree_client_token');
const response = await axios.post(
endpoint, {
currency: currency,
payment_method_id: methodId
},
{
headers: getAuthorizationHeaders(token)
}
);
return {
clientToken: response.data.client_token
};
} catch (e) {
Logger.error(e);
throw e;
}
}
3 changes: 2 additions & 1 deletion packages/api-client/src/api/savePaymentMethod/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ export default async function savePaymentMethod({ client, config }: ApiContext,
order: {
payments_attributes: [
{
payment_method_id: methodId.toString()
payment_method_id: methodId.toString(),
braintree_nonce: payload.braintree_nonce.toString()
}
]
},
Expand Down
4 changes: 3 additions & 1 deletion packages/api-client/src/index.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import deleteWishlist from './api/deleteWishlist';
import forgotPassword from './api/forgotPassword';
import getAddresses from './api/getAddresses';
import getAvailableCountries from './api/getAvailableCountries';
import getBraintreeToken from './api/getBraintreeToken';
import getCMSPage from './api/getCMSPage';
import getCart from './api/getCart';
import getCategory from './api/getCategory';
Expand Down Expand Up @@ -131,7 +132,8 @@ const { createApiClient } = apiClientFactory<any, any>({
changeCurrency,
deleteAddress,
getMenus,
getCMSPage
getCMSPage,
getBraintreeToken
},
extensions: [tokenExtension]
});
Expand Down
3 changes: 3 additions & 0 deletions packages/api-client/src/types/braintreetoken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export type BraintreeToken = {
clientToken: string;
};
1 change: 1 addition & 0 deletions packages/api-client/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export * from './wishlist';
export * from './user';
export * from './menu';
export * from './page';
export * from './braintreetoken';

export type CategoryFilter = Record<string, unknown>;
export type ShippingMethod = Record<string, unknown>;
Expand Down
106 changes: 106 additions & 0 deletions packages/theme/components/Checkout/PaymentMethod/Braintree.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
<template>
<div>
<div ref="paymentRef" />
<div
ref="errorRef"
role="alert"
class="sf-alert color-danger"
/>
</div>
</template>

<script>
import { onMounted, ref } from '@nuxtjs/composition-api';
import { useVSFContext, Logger } from '@vue-storefront/core';
import dropIn from 'braintree-web-drop-in';

export default {
props: {
method: {
type: Object,
default: () => {}
}
},

setup(props, { emit }) {
const { $spree } = useVSFContext();
const payment = ref(null);
const paymentRef = ref(null);
const errorRef = ref(null);
const fieldCount = ref(null);
const validFields = ref(0);

const savePayment = async () => {
try {
const methodId = props.method.id;
await payment.value.requestPaymentMethod(
async (error, braintreeResponse) => {
if (error) {
Logger.error(error);
errorRef.value.textContent = error;
payment.value.clearSelectedPaymentMethod();
return;
}

const payload = {
braintree_last_two: braintreeResponse.details.lastTwo,
braintree_card_type: braintreeResponse.details.cardType.replace(/\s/g, ''),
braintree_nonce: braintreeResponse.nonce
};

await $spree.api.savePaymentMethod(methodId, payload);
}
);
return true;
} catch (error) {
Logger.error(error);
return false;
}
};

const handleCardChange = (ev) => {
fieldCount.value ??= Object.keys(ev.fields).length;
const field = ev.fields[ev.emittedBy];
if (field.isValid) {
validFields.value = validFields.value + 1;
} else {
validFields.value = validFields.value - 1;
}
if (validFields.value === fieldCount.value) {
const isPaymentReady = true;
emit('change:payment', { isPaymentReady, savePayment });
} else {
const isPaymentReady = false;
emit('change:payment', { isPaymentReady, savePayment });
}
};

onMounted(async () => {
try {
const methodId = props.method.id;
const response = await $spree.api.getBraintreeToken(methodId);

dropIn.create({
container: paymentRef.value,
authorization: response.clientToken
}, (createError, dropInInstance) => {
if (createError) {
Logger.error(createError);
}
payment.value = dropInInstance;
payment.value.on('card:validityChange', handleCardChange);
});
} catch (e) {
Logger.error(e);
}
});

return {
paymentRef,
errorRef
};
}
};
</script>

<style></style>
4 changes: 4 additions & 0 deletions packages/theme/components/Checkout/VsfPaymentProvider.vue
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { SfButton, SfRadio } from '@storefront-ui/vue';
import { ref, onMounted, computed } from '@nuxtjs/composition-api';
import { useVSFContext } from '@vue-storefront/core';
import Stripe from '~/components/Checkout/PaymentMethod/Stripe';
import Braintree from '~/components/Checkout/PaymentMethod/Braintree';
import Check from '~/components/Checkout/PaymentMethod/Check';
import { Logger } from '@vue-storefront/core';

Expand All @@ -38,6 +39,7 @@ export default {
SfButton,
SfRadio,
Stripe,
Braintree,
Check
},

Expand All @@ -55,6 +57,8 @@ export default {
switch (selectedMethod.value) {
case 'Spree::Gateway::StripeElementsGateway':
return 'Stripe';
case 'Spree::Gateway::BraintreeVzeroDropInUi':
return 'Braintree';
case 'Spree::PaymentMethod::Check':
return 'Check';
}
Expand Down
8 changes: 5 additions & 3 deletions packages/theme/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,28 @@
"test": "jest"
},
"dependencies": {
"@nuxtjs/pwa": "^3.3.5",
"@nuxtjs/google-fonts": "^1.3.0",
"@nuxtjs/pwa": "^3.3.5",
"@nuxtjs/style-resources": "^1.2.1",
"@storefront-ui/vue": "^0.11.0",
"@stripe/stripe-js": "^1.20.3",
"@vue-storefront/middleware": "^2.5.0",
"@vue-storefront/nuxt": "^2.5.0",
"@vue-storefront/nuxt-theme": "^2.5.0",
"@vue-storefront/spree": "1.3.0",
"braintree-web-drop-in": "^1.33.4",
"cookie-universal-nuxt": "^2.1.5",
"nuxt": "^2.15.8",
"nuxt-i18n": "^6.28.0",
"vue-server-renderer": "^2.6.14",
"vee-validate": "^3.4.13",
"vue-demi": "latest",
"vue-scrollto": "^2.20.0"
"vue-scrollto": "^2.20.0",
"vue-server-renderer": "^2.6.14"
},
"devDependencies": {
"@nuxt/types": "latest",
"@nuxt/typescript-build": "latest",
"@types/braintree-web-drop-in": "^1.28.0",
"@vue/test-utils": "^1.2.2",
"babel-core": "7.0.0-bridge.0",
"babel-jest": "^27.3.0",
Expand Down
Loading