skip to Main Content

I want to create a custom form for the user to register, because I need the birthday of the customer.

So I need the user to enter his birthday as a REQUIRED field and I need to check if the user is above the age of 18.

Then at the checkout I also want to reconfirm the user is above 18.

I thought it would be the best approach to create a custom Shopify App for that.

I created a cart checkout validation so I can check for the birthday which worked out.

run.graphql:

query RunInput {
  cart {
    buyerIdentity {
      customer {
        metafield(key: "birthday") {
          value
        }
      }
    }
  }
}

run.ts:

export function run(input: RunInput): FunctionRunResult {
  const error = {
    localizedMessage: "Birthday not set.",
    target: "cart"
  };

  const errors: any = [];

  if (input.cart.buyerIdentity?.customer?.metafield?.value === undefined) {
    error.localizedMessage += input.cart.buyerIdentity?.customer?.metafield?.value ?? "{NO}";
    errors.push(error);
  }

  return {
    errors
  }
};

So currently I get this error message inside my cart, because no birthday value is deposited.

Now I needed to create that custom form for the user to register at. I used the main-register.liquid from the dawn theme as a template. I added my birthday input and added a validation method called validateForm().

This is how the script looks:

function validateForm() {
    var firstName = document.getElementById('RegisterForm-FirstName').value;
    var lastName = document.getElementById('RegisterForm-LastName').value;
    var password = document.getElementById('RegisterForm-password').value;
    var email = document.getElementById('RegisterForm-email').value;
    var birthday = document.getElementById('RegisterForm-birthday').value;

    var errorMessage = document.getElementById("error-message");

    errorMessage.hidden = true;
    
    if (!firstName.trim().length) {
      errorMessage.hidden = false;
      return false;
    }
    
    // all other checks if empty ....

    var record=birthday.trim();
    var currentdate=new Date();

    var currDay = currentdate.getDate();
    var currMonth = currentdate.getMonth() + 1;
    var currYear = currentdate.getFullYear() - 17;

    var aighteenStr = currDay + "-" + currMonth + "-" + currYear;
    var aighteen = new Date(aighteenStr);
    
    var birth = new Date(record);      

    console.log(birth);
    console.log(aighteen);

    if(birth > aighteen)
    {
        alert("Du musst über 18 Jahre sein, um einen Account erstellen zu können.");
        return false;
    }
    
    return true;
  }

I did my research and found the createCustomer function / mutation, but I’m not sure how to implement it here.

I’ve also found this tutorial, but it looked strange to put my credentials into the liquid file.

Any advice on how to call that function? Or do I need to follow a different approach?

(Different approach my mind has crossed:
Use the normal create_customer form and add a new field with the id customer[note][birthday].
This worked in the saving process, but without a validation if the user is 18+.
I also didn’t find a method to retrieve that information in the checkout validation because the customer model that gets returned in the cart only has a metafield value and no note value (information here) )

2

Answers


  1. Creating a custom form for user registration and integrating it with Shopify involves a few steps. Here’s a general outline of how you could approach this:

    Create a Custom Registration Form: You’ve already started on this by modifying the main-register.liquid file. Make sure your form includes fields for first name, last name, email, password, and birthday. Ensure that the birthday field is marked as required in your HTML.

    Client-Side Validation: You’re on the right track with your validateForm() function. Make sure it checks that all required fields are filled and that the birthday entered is valid and the user is above 18 years old.

    Server-Side Validation: While client-side validation is important for a smooth user experience, it’s crucial to also validate the data server-side to ensure security and integrity. You can use Shopify’s GraphQL API to perform server-side validation when the form is submitted.

    Integrate with Shopify API to Create Customer: After validating the form data, you need to create a customer using Shopify’s API. You can use the customerCreate mutation from Shopify’s GraphQL Admin API to create a customer account. This should be done server-side, either in a custom app or through server-side scripting.

    Handle Age Verification at Checkout: You’ve already started with your run.ts script to check for the presence of the birthday metafield. You can extend this script to also verify if the customer is above 18 years old. If not, you can display an error message to the user during the checkout process.

    Regarding your concerns about credentials in Liquid files, it’s common to use Liquid variables to pass data from Shopify to JavaScript for client-side processing. However, sensitive information like API keys or passwords should never be exposed in client-side code. If you need to make API requests from client-side JavaScript, you should use Shopify’s Storefront API, which allows you to authenticate requests using a storefront access token.

    In summary, you’re on the right track with creating a custom form and client-side validation. You’ll need to integrate with Shopify’s API to handle server-side validation and customer creation, and then extend your validation script to check for age during checkout.

    Login or Signup to reply.
  2. Set up a Private App on Shopify: First, you need to create a private app in your Shopify admin. This will provide you with the API credentials (API key, password, and store URL) that you’ll use to authenticate your requests.

    Authenticate: Use the API key and password to obtain an access token. This token will be used in subsequent requests to authenticate your app with the Shopify API.

    Make the API Call: Use the access token to make a POST request to the Shopify API’s customers endpoint, including the necessary parameters to create a new customer.

    Here’s an example in Python using the requests library:

    import requests
    
    # Replace these variables with your actual Shopify API credentials
    shopify_store_url = "YOUR_STORE_URL"
    api_key = "YOUR_API_KEY"
    api_password = "YOUR_API_PASSWORD"
    
    # Endpoint for creating a customer
    endpoint = f"https://{api_key}:{api_password}@{shopify_store_url}/admin/api/2021-10/customers.json"
    
    # Customer data to be sent in the request body
    customer_data = {
        "customer": {
            "first_name": "John",
            "last_name": "Doe",
            "email": "[email protected]",
            "phone": "+1234567890",
            "verified_email": True,
            "addresses": [
                {
                    "address1": "123 Oak St",
                    "city": "New York",
                    "province": "NY",
                    "zip": "10001",
                    "country": "United States",
                    "default": True
                }
            ]
        }
    }
    
    # Make the POST request to create the customer
    response = requests.post(endpoint, json=customer_data)
    
    # Check if the request was successful
    if response.status_code == 201:
        print("Customer created successfully.")
        new_customer_id = response.json()["customer"]["id"]
    else:
        print("Failed to create customer. Status code:", response.status_code)
        print("Response:", response.text)

    Make sure to replace "YOUR_STORE_URL", "YOUR_API_KEY", and "YOUR_API_PASSWORD" with your actual Shopify store URL, API key, and password respectively.

    This example assumes you are using the Shopify API version 2021-10. You might need to adjust the endpoint URL according to the API version you’re targeting. Also, ensure that your API permissions include the necessary scopes to create customers.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search