wcRegister method
Sends a request to register a user in WooCommerce with the following
parameters username
, email
and password
.
You can optionally set an expiry
for the token expiry like "+1 day".
Returns a WPUserRegisterResponse future. Throws an UsernameTakenException if username is taken InvalidNonceException if nonce token is not valid ExistingUserLoginException if user login exists ExistingUserEmailException if that email is in use UserAlreadyExistException if a user was found with the same email EmptyUsernameException if the username field has empty Exception if fails.
Implementation
Future<WPUserRegisterResponse> wcRegister(
{required String email,
required String password,
String? username,
String? expiry,
Map<String, dynamic>? args,
bool saveTokenToLocalStorage = true}) async {
// Get nonce from WordPress
WPNonceResponse wpNonceResponse = await wpNonce();
if (username == null) {
username = (email.replaceAll(RegExp(r'([@.])'), "")) + _randomString(4);
}
// Creates payload for register
Map<String, dynamic> payload = {
"email": email,
"password": password,
"username": username,
"wc_register": true, // This is the key to register a user in WooCommerce
"nonce": wpNonceResponse.data?.nonce,
"args": args
};
if (expiry != null) payload["expiry"] = expiry;
// send http request
final json = await _http(
method: "POST",
url: _urlForRouteType(WPRouteType.UserRegister),
body: payload,
);
// return response
if (_jsonHasBadStatus(json)) {
return _throwExceptionForStatusCode(json);
}
WPUserRegisterResponse wPUserRegisterResponse =
WPUserRegisterResponse.fromJson(json);
String? userToken = wPUserRegisterResponse.data?.userToken;
if (userToken != null && saveTokenToLocalStorage) {
WpUser wpUser = WpUser.fromWPUserRegisterResponse(wPUserRegisterResponse);
await WPJsonAPI.wpLogin(wpUser);
}
return wPUserRegisterResponse;
}