Assign new customer with specific user role upon checkout registration When a new customer is created, in the first checkout steps, its useful to be able to assign him with a specific user role, apart from the default 'authenticated'

A relevant use case would be when there are both customers and different backend user roles (editors e.t.c.) and it is need to create specific permissions to users according to whether they are customers or not.

This has been answered for commerce v1 (drupal 7) in the following
Drupal Commerce assign role on account create on checkout

This solution can be applied to Drupal 8 commerce v2. So by utilizing hook_user_insert one can get the new account and assign it other roles, upon registration.

However its not clear how/if we can determine in this hook whether this new user is a commerce created user and therefore a customer, or if its a user created by the admin and therefore possibly not a customer.

One not so safe condition would be to check if he already is assigned with any roles, as it would be the case if he was a backend user, but still this does not feel so safe.

So, there are 2 questions


Is there a 'by the book' way to assign a specific role to a commerce customer?
Is there a safe way to identify who is creating (commerce checkout or backend admin) a user in hook_user_insert?
Surely If someone creates the order the the order is associated to that user, so in this case you don't need to wory about user being created, what you can do is look in to:

hook_ENTITY_TYPE_update()

this way your going from the order status being upgraded to paid or whatever I dont know what the entity name for the order is but you could grab that loaded it, get the user id and check the roles , if no role add new role to them and save. as a bonus you have more control over what type of products to restrict it to ect.