You should create new Contact and add a new subscription to ListSubscriptions facet
.
Create contact:
public async Task<bool> CreateContact(
string source,
string identifier,
string firstName,
string lastName,
string email)
{
using (XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
{
try
{
IdentifiedContactReference reference = new IdentifiedContactReference(source, identifier);
var contactTask = client.GetAsync(
reference,
new ContactExpandOptions()
);
Contact existingContact = await contactTask;
if (existingContact != null)
{
return false;
}
var contactIdentifiers = new[]
{
new ContactIdentifier(source, identifier, ContactIdentifierType.Known),
};
Contact contact = new Contact(contactIdentifiers);
var personal = new PersonalInformation
{
FirstName = firstName,
LastName = lastName
};
var preferredEmail = new EmailAddress(email, true);
var emails = new EmailAddressList(preferredEmail, "Work");
client.AddContact(contact);
client.SetPersonal(contact, personal);
client.SetEmails(contact, emails);
await client.SubmitAsync();
return true;
}
catch (XdbExecutionException ex)
{
_logService.Error(ex.Message, ex);
return false;
}
}
}
Subscribe contact to list:
public async Task<bool> SubscribeContact(string source, string identifier, Guid listId)
{
using (XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
{
try
{
IdentifiedContactReference reference = new IdentifiedContactReference(source, identifier);
var contactTask = client.GetAsync(
reference,
new ContactExpandOptions(
ListSubscriptions.DefaultFacetKey
)
);
Contact contact = await contactTask;
if (contact == null)
{
return false;
}
if (contact.Identifiers.All(x => x.Source != "ListManager"))
client.AddContactIdentifier(contact, new ContactIdentifier("ListManager", Guid.NewGuid().ToString(), ContactIdentifierType.Known));
var subscriptions = contact.ListSubscriptions() ?? new ListSubscriptions();
var subscription = new ContactListSubscription(DateTime.UtcNow, true, listId);
subscriptions.Subscriptions.Add(subscription);
client.SetListSubscriptions(contact, subscriptions);
await client.SubmitAsync();
return true;
}
catch (XdbExecutionException ex)
{
_logService.Error(ex.Message, ex);
return false;
}
}
}