CiviCRM Membership form with login
To programatically user from code, you need to replicate what user_login_submit and user_login_finalize are doing:

function user_login_submit($form, &amp;$form_state) {
  global $user;
  $user = user_load($form_state['uid']);
  $form_state['redirect'] = 'user/' . $user-&gt;uid;

  user_login_finalize($form_state);
}

function user_login_finalize(&amp;$edit = array()) {
  global $user;
  watchdog('user', 'Session opened for %name.', array('%name' =&gt; $user-&gt;name));
  // Update the user table timestamp noting user has logged in.
  // This is also used to invalidate one-time login links.
  $user-&gt;login = REQUEST_TIME;
  db_update('users')-&gt;fields(array('login' =&gt; $user-&gt;login))-&gt;condition('uid', $user-&gt;uid)-&gt;execute();

  // Regenerate the session ID to prevent against session fixation attacks.
  // This is called before hook_user in case one of those functions fails
  // or incorrectly does a redirect which would leave the old session in place.
  drupal_session_regenerate();

  user_module_invoke('login', $edit, $user);
}


Just replace $form_state['uid'] with UID you generated in earlier step, and maybe use other way to redirect.