{"templateId":"markdown","sharedDataIds":{"sidebar":"sidebar-sidebars.yaml"},"props":{"metadata":{"markdoc":{"tagList":["code-walkthrough","step","admonition"]},"redocly_category":"Documentation","type":"markdown"},"seo":{"title":"Create a customer","description":"Learn how to create a customer using the Rebilly JS SDK.","siteUrl":"https://www.rebilly.com","image":"/assets/rebillysocial.94fb32fc280c9e84b963c440ec462771d25f4e6fdaaa6c59de41e8135113b46b.db81178d.png","lang":"en-US","llmstxt":{"hide":false,"sections":[{"title":"Table of contents","includeFiles":["**/*"],"excludeFiles":[]}],"excludeFiles":[]}},"dynamicMarkdocComponents":[],"compilationErrors":[],"ast":{"$$mdtype":"Tag","name":"article","attributes":{},"children":[{"$$mdtype":"Tag","name":"CodeWalkthrough","attributes":{"__idx":1,"filters":{},"filesets":[{"files":[{"path":"docs/dev-docs/_code-samples/create-a-customer/server.js","content":[{"start":0,"condition":{"steps":["install-and-initialize-dependencies"]},"children":["import express from \"express\";","import RebillyAPI from \"rebilly-js-sdk\";","","const app = express();","","app.use(express.json());"]},"",{"start":9,"condition":{"steps":["provide-credentials"]},"children":["const API_SECRET_KEY = \"SECRET_KEY\";","const ORGANIZATION_ID = \"ORGANIZATION_ID\";","const WEBSITE_ID = \"WEBSITE_ID\";"]},"",{"start":15,"condition":{"steps":["initialize-rebilly-js-sdk"]},"children":["const rebilly = RebillyAPI({","    organizationId: ORGANIZATION_ID,","    sandbox: true,","    apiKey: API_SECRET_KEY,","    timeout: 5000,","});"]},"","app.use(express.static(\"public\"));","",{"start":26,"condition":{"steps":["define-route-for-post-requests"]},"children":["app.post(\"/create-customer\", async (req, res) => {",{"start":28,"condition":{"steps":["build-customer-data"]},"children":["    try {","        const { customerId, firstName, lastName, email, phone } = req.body;","        const customerData = {","            data: {","                id: customerId,","                websiteId: WEBSITE_ID,","                primaryAddress: {","                    firstName,","                    lastName,","                    emails: [{ label: \"primary\", value: email, primary: true }],","                    ...(phone && {","                        phoneNumbers: [{ label: \"primary\", value: phone, primary: true }],","                    }),","                },","            },","        };"]},{"start":46,"condition":{"steps":["call-upsert-api"]},"children":["        const response = await rebilly.customers.upsert(customerData);","        res.status(200).json({ success: true, customer: response.fields });"]},{"start":50,"condition":{"steps":["error-handling"]},"children":["    } catch (error) {","        console.error(\"Error creating customer:\", error);","        res.status(error?.response?.status || 500).json({","            error: \"Failed to create customer\",","            details: error?.response?.data || error.message,","        });"]},"    }"]},"});","","app.listen(8080, () => console.log(\"Running on port 8080\"));",""],"metadata":{"steps":["install-and-initialize-dependencies","provide-credentials","initialize-rebilly-js-sdk","define-route-for-post-requests","build-customer-data","call-upsert-api","error-handling"]},"basename":"server.js","language":"javascript"}],"downloadAssociatedFiles":[]},{"files":[{"path":"docs/dev-docs/_code-samples/create-a-customer/public/index.html","content":[{"start":0,"condition":{"steps":["create-html-form"]},"children":["<!doctype html>","<html lang=\"en\">","    <head>","        <meta charset=\"UTF-8\" />","        <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />","        <link rel=\"stylesheet\" href=\"style.css\" />","        <title>Create a customer using the Rebilly SDK</title>","    </head>","    <body>","        <div class=\"container\">","            <h1>Create a customer</h1>","            <form id=\"customerForm\">","                <div class=\"form-group\">","                    <label for=\"customerId\">Customer ID <span>*</span></label>","                    <input","                        type=\"text\"","                        id=\"customerId\"","                        name=\"customerId\"","                        required","                        placeholder=\"cus_01HDP7FFX2PGDVH1995EA4QY95\"","                    />","                </div>","                <div class=\"form-group\">","                    <label for=\"firstName\">First Name <span>*</span></label>","                    <input type=\"text\" id=\"firstName\" name=\"firstName\" required placeholder=\"John\" />","                </div>","                <div class=\"form-group\">","                    <label for=\"lastName\">Last Name <span>*</span></label>","                    <input type=\"text\" id=\"lastName\" name=\"lastName\" required placeholder=\"Doe\" />","                </div>","                <div class=\"form-group\">","                    <label for=\"email\">Email <span>*</span></label>","                    <input type=\"email\" id=\"email\" name=\"email\" required placeholder=\"john.doe@example.com\" />","                </div>","                <div class=\"form-group\">","                    <label for=\"phone\">Phone</label>","                    <input type=\"text\" id=\"phone\" name=\"phone\" placeholder=\"+1-555-123-4567\" />","                </div>","                <button type=\"submit\">Create customer</button>","            </form>","            <div id=\"result\" class=\"result\"></div>","        </div>","        <script src=\"script.js\"></script>","    </body>","</html>"]},""],"metadata":{"steps":["create-html-form"]},"basename":"index.html","language":"html"}],"downloadAssociatedFiles":[]},{"files":[{"path":"docs/dev-docs/_code-samples/create-a-customer/public/script.js","content":[{"start":0,"condition":{"steps":["add-javascript-handler"]},"children":["document.getElementById(\"customerForm\").addEventListener(\"submit\", async (e) => {","    e.preventDefault();","","    const resultDiv = document.getElementById(\"result\");","    const submitButton = document.querySelector('button[type=\"submit\"]');","","    resultDiv.className = \"result loading\";","    resultDiv.style.display = \"block\";","    resultDiv.textContent = \"Creating customer...\";","    submitButton.disabled = true;","","    try {","        const response = await fetch(\"/create-customer\", {","            method: \"POST\",","            headers: { \"Content-Type\": \"application/json\" },","            body: JSON.stringify(Object.fromEntries(new FormData(e.target))),","        });","","        resultDiv.className = `result ${response.ok ? \"success\" : \"error\"}`;","        resultDiv.innerHTML = `<strong>${response.ok ? \"Success!\" : \"Fail\"}</strong>`;","    } catch (error) {","        resultDiv.className = \"result error\";","        resultDiv.innerHTML = `<strong>Network Error:</strong><br>${error.message}`;","    } finally {","        submitButton.disabled = false;","    }"]},"});",""],"metadata":{"steps":["add-javascript-handler"]},"basename":"script.js","language":"javascript"}],"downloadAssociatedFiles":[]},{"downloadAssociatedFiles":[{"path":"docs/dev-docs/_code-samples/create-a-customer/public/style.css","content":[{"start":0,"condition":{"steps":["add-form-styling"]},"children":["body {","    font-family: sans-serif;","    padding: 20px;","    background: #f5f5f5;","}","",".container {","    max-width: 600px;","    margin: 0 auto;","    background: white;","    padding: 30px;","    border-radius: 8px;","}","","h1 {","    text-align: center;","    margin-bottom: 30px;","}","",".form-group {","    margin-bottom: 20px;","}","","label {","    margin-bottom: 5px;","}","","input {","    width: 95%;","    padding: 12px;","    border: 1px solid #136530;","    border-radius: 4px;","}","","button {","    width: 100%;","    padding: 12px;","    background: #007bff;","    color: white;","    border: none;","    border-radius: 4px;","    cursor: pointer;","}","button:disabled {","    background: #ccc;","}","",".result {","    display: none;","    margin-top: 20px;","    padding: 15px;","    border-radius: 4px;","}",".result.success {","    background: #d4edda;","    color: #155724;","}",".result.error {","    background: #f8d7da;","    color: #721c24;","}"]},""],"metadata":{"steps":["add-form-styling"]},"basename":"style.css","language":"css"}],"files":[]},{"downloadAssociatedFiles":[{"path":"docs/dev-docs/_code-samples/create-a-customer/package.json","content":["{","  \"name\": \"rebilly-create-a-customer-example\",","  \"version\": \"1.0.0\",","  \"main\": \"server.js\",","  \"scripts\": {","    \"dev\": \"node server.js\"","  },","  \"author\": \"Rebilly\",","  \"license\": \"MIT\",","  \"dependencies\": {","    \"express\": \"^4.21.2\",","    \"rebilly-js-sdk\": \"^60.10.1\"","  },","  \"type\": \"module\"","}",""],"metadata":{"steps":[]},"basename":"package.json","language":"text"}],"files":[]},{"downloadAssociatedFiles":[{"path":"docs/dev-docs/_code-samples/create-a-customer/README.md","content":["# Create a customer","","This example describes how to create a customer using the Rebilly JS SDK.","","## Define your secret key, organization ID, and website ID","","In the server-side code (`server.js`), assign values for `API_SECRET_KEY`,","`ORGANIZATION_ID`, and `WEBSITE_ID`.","","## Run the sample application","","To run the sample application, execute the following commands in this directory:","","1. Install dependencies:","","```bash","npm install","```","","2. Run the server","","```bash","node server.js","```","","3. Open [http://localhost:8080](http://localhost:8080)","","## Error handling","","Errors from the server are logged to your console.",""],"metadata":{"steps":[]},"basename":"README.md","language":"markdoc"}],"files":[]}],"steps":[{"id":"install-and-initialize-dependencies","heading":"Install and initialize dependencies"},{"id":"provide-credentials","heading":"Provide credentials"},{"id":"initialize-rebilly-js-sdk","heading":"Initialize Rebilly JS SDK"},{"id":"define-route-for-post-requests","heading":"Define route for POST requests"},{"id":"build-customer-data","heading":"Build customer data structure"},{"id":"call-upsert-api","heading":"Call the upsert API"},{"id":"error-handling","heading":"Handle errors"},{"id":"create-html-form","heading":"Create HTML form"},{"id":"add-javascript-handler","heading":"Add JavaScript handler"},{"id":"run-the-example","heading":"Run the example"}],"inputs":{},"toggles":{}},"children":[{"$$mdtype":"Tag","name":"Heading","attributes":{"level":1,"id":"create-a-customer","__idx":0},"children":["Create a customer"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["This guide describes how to create a customer using the ",{"$$mdtype":"Tag","name":"MarkdownLink","attributes":{"href":"https://www.npmjs.com/package/rebilly-js-sdk"},"children":["Rebilly JS SDK"]},", ",{"$$mdtype":"Tag","name":"MarkdownLink","attributes":{"href":"https://expressjs.com/en/starter/installing.html"},"children":["Express JS"]},", and the ",{"$$mdtype":"Tag","name":"MarkdownLink","attributes":{"href":"/catalog/all/customers/putcustomer"},"children":["Upsert a customer API operation"]},"."]},{"$$mdtype":"Tag","name":"details","attributes":{},"children":[{"$$mdtype":"Tag","name":"summary","attributes":{},"children":["Prerequisites"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["To complete this guide, you must have a website ID, an organization ID, and a secret API key."]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["If you already have your IDs and API keys, continue to ",{"$$mdtype":"Tag","name":"MarkdownLink","attributes":{"href":"#step-1-set-up-the-server"},"children":["Step 1: Set up the server"]},"."," ","If you do not, get your IDs and API key in ",{"$$mdtype":"Tag","name":"MarkdownLink","attributes":{"href":"/docs/dev-docs/set-up-environment"},"children":["Set up your environment"]},"."]}]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"step-1-set-up-the-server","__idx":1},"children":["Step 1: Set up the server"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["This section describes how to set up your server-side code to create customers using the Rebilly JS SDK."]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"install-and-initialize-dependencies","heading":"Install and initialize dependencies"},"children":[{"$$mdtype":"Tag","name":"ol","attributes":{},"children":[{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Install the required dependencies in your project directory:"]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"bash","header":{"controls":{"copy":{}}},"source":"npm install express rebilly-js-sdk@latest --save\n","lang":"bash"},"children":[]}]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Initialize Express and the Rebilly SDK as dependencies."]}]}]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"provide-credentials","heading":"Provide credentials"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Provide your secret key, website ID, and organization ID."," ","For more information, see ",{"$$mdtype":"Tag","name":"MarkdownLink","attributes":{"href":"/docs/dev-docs/set-up-environment"},"children":["Prerequisites"]},"."]},{"$$mdtype":"Tag","name":"Admonition","attributes":{"type":"warning"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Store your secret key in a secrets manager, not in your code."]}]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"initialize-rebilly-js-sdk","heading":"Initialize Rebilly JS SDK"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Set up the Rebilly JS SDK and provide your secret API key."," ","Set ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["sandbox"]}," to ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["true"]}," to test in the sandbox environment."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"define-route-for-post-requests","heading":"Define route for POST requests"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Define a route for handling HTTP POST requests to the ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["/create-customer"]}," endpoint."]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["This endpoint uses the Rebilly SDK ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["customers.upsert()"]}," method to create or update customers."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"build-customer-data","heading":"Build customer data structure"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Create the customer data object with the required structure for the Rebilly API, including the customer ID, website ID, and primary address information."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"call-upsert-api","heading":"Call the upsert API"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Use the Rebilly SDK ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["customers.upsert()"]}," method to create or update the customer."," ","This method creates a new customer if the ID does not exist, or updates an existing customer if it does."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"error-handling","heading":"Handle errors"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Implement error handling to catch and respond to any errors that occur during customer creation."," ","This includes API errors, validation errors, and network issues."]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["The error response includes the HTTP status code and detailed error information from the Rebilly API."]}]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"step-2-set-up-the-form","__idx":2},"children":["Step 2: Set up the form"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["This section describes how to create a form that collects customer information and simulates a customer registration or authentication."," ","Customer information is sent to the server to create or update a customer."]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"create-html-form","heading":"Create HTML form"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Create an HTML form with fields for customer information:"]},{"$$mdtype":"Tag","name":"ul","attributes":{},"children":[{"$$mdtype":"Tag","name":"li","attributes":{},"children":["Customer ID (required) - Enter your external identifier for the customer."," ","If the ID already exists in Rebilly, the API updates the customer's information."," ","If the ID does not exist, a new customer is created."]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":["First name (required)"]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":["Last name (required)"]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":["Email (required)"]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":["Phone (optional)"]}]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["You can also provide other fields that are supported by the ",{"$$mdtype":"Tag","name":"MarkdownLink","attributes":{"href":"/catalog/all/customers/putcustomer"},"children":["Upsert a customer API operation"]},", such as address and date of birth."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"add-javascript-handler","heading":"Add JavaScript handler"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Add JavaScript to handle form submission and send the data to your server endpoint."]}]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"step-3-test-the-customer-creation","__idx":3},"children":["Step 3: Test the customer creation"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["This section describes how to test the customer creation functionality."]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"run-the-example","heading":"Run the example"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Run ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["server.js"]},". When the server is running, open a browser and visit ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["http://localhost:8080"]},"."]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"bash","header":{"controls":{"copy":{}}},"source":"node server.js\n","lang":"bash"},"children":[]}]}]}]},"headings":[{"value":"Create a customer","id":"create-a-customer","depth":1},{"value":"Step 1: Set up the server","id":"step-1-set-up-the-server","depth":2},{"value":"Step 2: Set up the form","id":"step-2-set-up-the-form","depth":2},{"value":"Step 3: Test the customer creation","id":"step-3-test-the-customer-creation","depth":2}],"frontmatter":{"seo":{"title":"Create a customer","description":"Learn how to create a customer using the Rebilly JS SDK."},"markdown":{"toc":{"hide":true}},"footer":{"hide":true}},"lastModified":"2026-04-07T20:03:22.000Z","pagePropGetterError":{"message":"","name":""}},"slug":"/docs/dev-docs/create-a-customer","userData":{"isAuthenticated":false,"teams":["anonymous"]},"isPublic":true}