Unverified Commit af739ed8 authored by Hassan El Mghari's avatar Hassan El Mghari Committed by GitHub

Added example with salesforce commerce cloud (#41376)

Adding a Next.js example with Salesforce Commerce Cloud
Co-authored-by: 's avatarJJ Kasper <22380829+ijjk@users.noreply.github.com>
parent e1cb7f74
SFDC_CLIENT_ID=
SFDC_SECRET=
SFDC_ORGANIZATIONID=
SFDC_SHORTCODE=
SFDC_SITEID=
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
# Example Next.js app with Salesforce Commerce Cloud
This example shows how to create a headless ecommerce application using Next.js, [Salesforce commerce cloud](https://www.salesforce.com/products/commerce-cloud/overview/), and [Tailwind](https://tailwindcss.com).
## Deploy your own
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example) or view the demo [here](https://salesforce-cloud-commerce.vercel.app/)
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-sfcc&project-name=with-sfcc&repository-name=with-sfcc&env=SFDC_CLIENT_ID,SFDC_SECRET,SFDC_ORGANIZATIONID,SFDC_SHORTCODE,SFDC_SITEID&envDescription=API%20Keys%20from%20SFCC%20needed%20to%20run%20this%20application.)
Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/with-sfcc) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example::
```bash
npx create-next-app --example with-sfcc nextjs-sfcc-app
```
```bash
yarn create next-app --example with-sfcc nextjs-sfcc-app
```
```bash
pnpm create next-app --example with-sfcc nextjs-sfcc-app
```
## References
- SDK: https://github.com/SalesforceCommerceCloud/commerce-sdk
import Image from 'next/future/image'
export default function Header({ scrollHandler }) {
return (
<header className="relative">
<div className="absolute inset-x-0 bottom-0 h-1/2 bg-gray-100" />
<div className="mx-auto">
<div className="relative shadow-xl sm:overflow-hidden">
<div className="absolute inset-0">
<Image
priority
fill
className="h-full w-full object-cover"
src="/hero.jpg"
alt="Coffee grinder"
/>
<div className="absolute inset-0 bg-orange-100 mix-blend-multiply" />
</div>
<div className="relative px-4 py-16 sm:px-6 sm:py-24 lg:py-32 lg:px-8">
<p className="relative left-0 right-0 mx-auto mt-5 max-w-xl text-center text-xl font-semibold uppercase tracking-wide text-orange-600">
The Coffee House
</p>
<h1 className="mt-1 text-center font-bold uppercase text-gray-900 sm:text-5xl sm:tracking-tight lg:text-7xl">
<span className="block text-white">Life is better with</span>
<span className="block text-orange-500">coffee</span>
</h1>
<div className="mx-auto mt-10 max-w-xs sm:flex sm:max-w-none sm:justify-center">
<button
className="flex items-center justify-center rounded-md border border-transparent bg-white px-4 py-3 text-base font-medium text-orange-600 shadow-sm hover:bg-orange-100 sm:px-8"
onClick={scrollHandler}
>
Shop coffees
</button>
</div>
</div>
</div>
</div>
</header>
)
}
import Image from 'next/future/image'
import Link from 'next/link'
import { useState } from 'react'
function cn(...classes) {
return classes.filter(Boolean).join(' ')
}
export default function ProductCard({ product }) {
const [isLoading, setLoading] = useState(true)
return (
<Link href={`/products/${product.id}`}>
<a className="group">
<div className="aspect-w-1 aspect-h-1 w-full overflow-hidden rounded-lg bg-gray-200 xl:aspect-w-7 xl:aspect-h-8">
<Image
alt=""
src={product.imageGroups[0].images[0].link}
fill
className={cn(
'object-cover duration-700 ease-in-out group-hover:opacity-75 ',
isLoading
? 'scale-110 blur-2xl grayscale'
: 'scale-100 blur-0 grayscale-0'
)}
onLoadingComplete={() => setLoading(false)}
/>
</div>
<div className="mt-4 flex items-center justify-between text-base font-medium text-gray-900">
<h3>{product.name}</h3>
<p>${product.price}</p>
</div>
<p className="mt-1 text-sm italic text-gray-500">
{product.shortDescription}
</p>
</a>
</Link>
)
}
export default function Layout({ children }) {
return (
<>
<main>{children}</main>
<footer className="center mt-5 flex justify-center space-x-4 bg-[#E7E8EF] p-4 text-xs">
<p>Powered by Next.js, Salesforce Commerce Cloud, and Vercel </p>
<span>|</span>
<a
href="https://github.com/vercel/next.js/tree/canary/examples/with-sfcc"
className="font-medium text-orange-600"
>
Source code
</a>
</footer>
</>
)
}
module.exports = {
reactStrictMode: true,
images: {
domains: ['zzte-003.sandbox.us02.dx.commercecloud.salesforce.com'],
},
}
{
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"commerce-sdk": "^2.8.0",
"next": "latest",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@tailwindcss/aspect-ratio": "^0.4.0",
"@types/node": "17.0.4",
"@types/react": "17.0.38",
"autoprefixer": "^10.4.0",
"postcss": "^8.4.5",
"tailwindcss": "^3.0.7",
"typescript": "4.5.4"
}
}
import '../styles/globals.css'
import Layout from '../components/layout'
import Head from 'next/head'
function MyApp({ Component, pageProps }) {
return (
<>
<Head>
<title>The Coffee House</title>
</Head>
<Layout>
<Component {...pageProps} />
</Layout>
</>
)
}
export default MyApp
import { Head, Html, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html lang="en">
<Head>
<meta
name="description"
content="The premiere coffee delivery service."
/>
<link
href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap"
rel="stylesheet"
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
import { useRef } from 'react'
import Header from '../components/Header'
import ProductCard from '../components/ProductCard'
import getProducts from '../sfcc.js'
export default function Gallery({ data }) {
let coffeeRef = useRef()
const scrollHandler = (e) => {
e.preventDefault()
coffeeRef.scrollIntoView({
behavior: 'smooth',
block: 'start',
})
}
return (
<>
<Header scrollHandler={scrollHandler} />
<div className="mx-auto max-w-2xl px-4 sm:px-6 lg:max-w-7xl lg:px-8">
<div className="sm:py-15 mx-auto max-w-7xl py-16 px-4 sm:px-6 lg:px-8">
<div className="text-center">
<p
className="mt-1 text-4xl font-bold uppercase text-gray-900 sm:text-5xl sm:tracking-tight lg:text-5xl"
ref={(element) => (coffeeRef = element)}
>
Crafted by us, for you
</p>
</div>
</div>
<div className="grid grid-cols-1 gap-y-10 gap-x-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 xl:gap-x-8">
{data &&
data.map((product) => (
<ProductCard product={product} key={product.id} />
))}
</div>
</div>
</>
)
}
export async function getStaticProps() {
const searchResults = await getProducts('coffee')
return {
props: {
data: searchResults,
},
}
}
import Image from 'next/future/image'
import getProducts from '../../sfcc.js'
export default function Product({ product }) {
return (
<div className="flex h-screen flex-col justify-between">
<div className="mx-auto mt-16 max-w-2xl px-4 sm:px-6 lg:max-w-7xl lg:px-8">
<div className="mx-auto flex flex-col sm:flex-row">
<Image
alt="coffee"
className="rounded-lg"
src={product.imageGroups[0].images[0].link}
width={560}
height={640}
/>
<div className="mt-10 flex flex-col sm:mt-0 sm:ml-10">
<h1 className="mt-1 text-4xl font-bold uppercase text-gray-900 sm:text-5xl sm:tracking-tight lg:text-5xl">
{product.name}
</h1>
<h1 className="mt-3 text-4xl font-bold text-gray-500 sm:text-3xl sm:tracking-tight lg:text-3xl">
${product.price}
</h1>
<div className="mt-10 mb-5 border-t border-gray-200 pt-10 font-bold">
Description
</div>
<p className="max-w-xl">{product.longDescription}</p>
</div>
</div>
</div>
</div>
)
}
export async function getStaticProps({ params }) {
const searchResults = await getProducts(params.slug)
console.log('search Results are: ', searchResults)
const coffeeProduct = searchResults[0]
return {
props: {
product: coffeeProduct,
},
}
}
export async function getStaticPaths() {
const searchResults = await getProducts('coffee')
let coffeeProducts = searchResults
let fullPaths = []
for (let product of coffeeProducts) {
fullPaths.push({ params: { slug: product.id } })
}
return {
paths: fullPaths,
fallback: 'blocking',
}
}
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
<svg width="283" height="64" viewBox="0 0 283 64" fill="none"
xmlns="http://www.w3.org/2000/svg">
<path d="M141.04 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.46 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM248.72 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.45 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM200.24 34c0 6 3.92 10 10 10 4.12 0 7.21-1.87 8.8-4.92l7.68 4.43c-3.18 5.3-9.14 8.49-16.48 8.49-11.05 0-19-7.2-19-18s7.96-18 19-18c7.34 0 13.29 3.19 16.48 8.49l-7.68 4.43c-1.59-3.05-4.68-4.92-8.8-4.92-6.07 0-10 4-10 10zm82.48-29v46h-9V5h9zM36.95 0L73.9 64H0L36.95 0zm92.38 5l-27.71 48L73.91 5H84.3l17.32 30 17.32-30h10.39zm58.91 12v9.69c-1-.29-2.06-.49-3.2-.49-5.81 0-10 4-10 10V51h-9V17h9v9.2c0-5.08 5.91-9.2 13.2-9.2z" fill="#000"/>
</svg>
\ No newline at end of file
import { Customer, Product, Search } from 'commerce-sdk'
export default async function getProducts(searchQuery) {
const clientConfig = {
headers: {
authorization: ``,
},
parameters: {
clientId: process.env.SFDC_CLIENT_ID,
secret: process.env.SFDC_SECRET,
organizationId: process.env.SFDC_ORGANIZATIONID,
shortCode: process.env.SFDC_SHORTCODE,
siteId: process.env.SFDC_SITEID,
},
}
const credentials = `${clientConfig.parameters.clientId}:${clientConfig.parameters.secret}`
const base64data = Buffer.from(credentials).toString('base64')
const headers = { Authorization: `Basic ${base64data}` }
const client = new Customer.ShopperLogin(clientConfig)
const shopperToken = await client.getAccessToken({
headers,
body: {
grant_type: 'client_credentials',
},
})
const configWithAuth = {
...clientConfig,
headers: { authorization: `Bearer ${shopperToken.access_token}` },
}
const searchClient = new Search.ShopperSearch(configWithAuth)
const searchResults = await searchClient.productSearch({
parameters: { q: searchQuery },
})
const results = []
const productsClient = new Product.ShopperProducts(configWithAuth)
await Promise.all(
searchResults.hits.map(async (product) => {
const productResults = await productsClient.getProduct({
parameters: {
organizationId: clientConfig.parameters.organizationId,
siteId: clientConfig.parameters.siteId,
id: product.productId,
},
})
results.push(productResults)
})
)
return results
}
@tailwind base;
@tailwind components;
@tailwind utilities;
* {
font-family: Montserrat, sans-serif;
}
module.exports = {
content: [
'./pages/**/*.{js,ts,jsx,tsx}',
'./components/**/*.{js,ts,jsx,tsx}',
],
plugins: [require('@tailwindcss/aspect-ratio')],
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment