Add Salesforce Community Member Programmatically

Salesforce stores community members in NetworkMemberGroup object. Using apex we cannot insert the community member. So we can make a REST API call to add community member.

Sample Code:

//Get Endpoint URL
String endpointURL = URL.getSalesforceBaseUrl().toExternalForm()+'/services/data/v48.0/sobjects/NetworkMemberGroup';
HttpRequest req = new HttpRequest();  
req.setEndpoint(endpointURL);  
req.setMethod('POST');
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId()); 
req.setHeader('Content-Type', 'application/json;charset=UTF-8');
//Add Community Id as NetworkId and Profile Id as ParentId
req.setBody('{"NetworkId":"0DB1I000000TP59WAG","ParentId":"00e1I000001uXJUQA2"}');
Http http = new Http();
HttpResponse response = http.send(req);
System.debug('response-' + response);

Note: Add your salesforce base URL as remote site settings and then execute above code in developer console anonymous window.