1

I've been told by BC support that this isn't possible, but I would be surprised if there really wasn't a way.

I need to be able to automatically assign a customer to a specific customer group when they create an account. My thought:

  • I would add an extra field to the sign-up form
  • Provide a user with a code (a string or number)
  • User enters code when creating new account
  • User hits submit
  • On form submit I would grab the value of the extra field:
var codeInput = document.getElementById('code-input').value;

I would then compare that value to a pre-defined string, and if there is a match, I would assign that customer to groupX (with a group id of 8):

 if ( codeInput === "codeIGaveToTheUser" ) {
    currentUserGroupID = 8;
 }

Is it possible to assign a customer to a specific group on sign-up like this (or any other way)?

Any help is much appreciated.

Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
Tron
  • 167
  • 12
  • To be clear, when support tells you something can't be done, it means there isn't a setting. This can be accomplished through customization. It requires your own web server that is configured to listen for webhooks and assign the created customer based on your own business/code logic. – Alyss May 13 '16 at 04:28
  • Thanks Alyssa, can you give me an idea of how complicated that is, or maybe explain it in slightly simpler terms? I'm not a complete noob, but this type of project is a bit foreign to me. Note - Are BCs Server Settings of any use? – Tron May 13 '16 at 04:57
  • There's a typo. My name is Alyss, not Alyssa :) . BC server settings are not of use. You'd need to have an external server or something like heroku that could. Javascript would likely be insufficient. – Alyss May 13 '16 at 05:17

2 Answers2

5

Although using BigCommerce webhooks would ensure the highest success rate of executing your customer group assignment app, it requires quite a bit of setup on BigCommerce (creating a draft app, getting an oAuth key, jumping jacks, etc), and may be a bit of overkill for your requirements.

Here's an easier way, in my {mostly} humble opinion, that takes advantage of much of what you included in your original question. Any solution though will nonetheless require an external server to handle the customer group assignment through the BigCommerce API.

  1. Within the BigCommerce control panel, add in the extra field to the user sign up form like you mentioned. enter image description here

  2. So as you can see, this new input field has been added natively to the default registration page: enter image description here

So now, when a user creates an account on your site, the value for the Signup Code (the custom field created) will be directly accessible through the API for that customer's account. Take a look at what that JSON data looks like: enter image description here


Okay, so this is nice and all, but how do we automate it?
To do so, we will have to let our external application know that a customer just registered. Furthermore, our external application will need some sort of reference to this newly created customer, so that it knows which customer to update the customer group for. Normally a BigCommerce webhook would notify us of all this, but since we aren't using a BigCommerce webhook, here's the alternative method to triggering the external script.

  1. We will trigger our external application via the BigCommerce Registration Confirmation page - createaccount_thanks.html. This page is loaded immediately after a customer creates an account, so it is the perfect place to insert our trigger script.
  2. Additionally, now that the customer is logged in, we can access the customer's email address via a BigCommerce Global system variable -%%GLOBAL_CurrentCustomerEmail%%.
  3. We should make an HTTP request from this page to our external application along with the customer's email address. Specifically, we can make an XMLHttpRequest via JavaScript, or to be modern, we'll use Ajax via jQuery. This script should be inserted before the closing </body> tag on createaccount_thanks.html.

Example of POST request (although a GET would suffice as well):

<script>
  $(function() {
    $('.TitleHeading').text('One moment, we are finalizing your account. Please wait.').next().hide(); // Let the customer know they should wait a second before leaving this page.
    //** Configure and Execute the HTTP POST Request! **//
    $.ajax({
      url:         'the_url_to_your_script.com/script.php',
      type:        'POST',
      contentType: 'application/json',
      data:         JSON.stringify({email:"%%GLOBAL_CurrentCustomerEmail%%"}),
      success: function() {
        // If the customer group assignment goes well, display page and proceed normally. This callback is only called if your script returns a 200 status code.
        $('.TitleHeading').text('%%LNG_CreateAccountThanks%%').next().show();
      },
      error:   function() {
        // If the customer group assignment failed, you might want to tell your customer to contact you. This callback is called if your script returns any status except 200.
        $('.TitleHeading').text('There was a problem creating your account').after('Please contact us at +1-123-456-7890 so that we can look into the matter. Please feel free to continue shopping in the meantime.');            
      }                      
    });
  });
</script>

Now finally, you just need to create your serverside application responsible for handling the request above, and updating the customer's customer group. You can use any language that you desire, and BigCommerce even offers several SDK's you can use to save mega development time. Just remember that you need to host it somewhere online, and then insert its URL to the JS script above.

PHP Example (quick & dirty):

git clone https://github.com/bigcommerce/bigcommerce-api-php.git
curl -sS https://getcomposer.org/installer | php && php composer.phar install

<?php
/**
 * StackOverflow/BigCommerce :: Set Customer Group Example
 * http://stackoverflow.com/questions/37201106/
 * 
 * Automatically assigning a customer group.
 */

//--------------MAIN------------------------//

// Load Dependencies:
require ('bigcommerce-api-php/vendor/autoload.php');
use Bigcommerce\Api\Client as bc;

// Define BigCommerce API Credentials:
define('BC_PATH', 'https://store-abc123.mybigcommerce.com');
define('BC_USER', 'user');
define('BC_PASS', 'token');

// Load & Parse the Email From the Request Body;
$email = json_decode(file_get_contents('php://input'))->email;

// Execute Script if API Connection Good & Email Set:
if ($email && setConnection()) {
    $customer = bc::getCollection('/customers?email=' .$email)[0];        //Load customer by email
    $cgid     = determineCustomerGroup($customer->form_fields[0]->value); //Determine the relevant customer group ID, via your own set string comparisons. 
    bc::updateCustomer($customer->id, array('customer_group_id' => $cgid)) ? http_send_status(200) : http_send_status(500); //Update the customer group. 
} else {
    http_send_status(500);
    exit;
}

//-------------------------------------------------//

/**
 * Sets & tests the API connection.
 * @return bool true if the connection successful.
 */
function setConnection() {
    try {
        bc::configure(array(
        'store_url' => BC_PATH,
        'username'  => BC_USER,
        'api_key'   => BC_PASS
        ));
    } catch (Exception $e) {
        return false;
    }
    return bc::getResource('/time') ? true : false; //Test Connection
}

/**
 * Hard define the customer group & signup code associations here.
 * @param string The code user used at signup.
 * @return int   The associated customergroup ID. 
 */
function determineCustomerGroup($signupCode) {
    switch ($signupCode) {
        case 'test123':
            return 1;
        case 'codeIGaveToTheUser':
            return 8;
        default:
            return 0;
    }
}

So then you would do your customer group string comparisons directly in the serverside program. I'd recommend you rewrite your own BC API script as the one above in quality is really something along the lines of functional pseudo-code, but more so present to show the general idea. HTH

Betsy Dupuis
  • 513
  • 1
  • 6
  • 21
2

You would need to set up a server to listen for webhooks unless you wanted to do a cron job. We have some basic information on the developer portal, but I included more resources below. From there, you'd need to choose your server language of choice to listen for the webhooks once they been created, respond correctly (200 response if received), execute code based on this information, and then take action against the BC API.

So if you were looking for a code, you'd need to listen for the store/customer/created webhook, and have your code look for a custom field that contained the code. If it was present, then take action. Else, do nothing.

https://developer.github.com/webhooks/configuring/

http://coconut.co/how-to-create-webhooks

How do I receive Github Webhooks in Python

Community
  • 1
  • 1
Alyss
  • 1,866
  • 1
  • 13
  • 27
  • Sorry Alyss! And thanks so much for this. I'm having a pretty hard time understanding, and I am trying to figure out what listening for a webhook means exactly, but I will look at and read these links, and see if I can't learn a few things. I appreciate the time – Tron May 13 '16 at 05:36