Changing the primary domain name on a Google Apps account is a non-trivial process. I recently needed to do this for a customer, and created a console application that makes the job easier.
Clone the GitHub project:
git clone https://github.com/dougreese/ga-change-primary-domain.git
then follow the instructions in the README to build and run.
Some additional resources:
* [Before you change your primary domain](https://support.google.com/a/answer/6301932/)
* Short (https://www.youtube.com/watch?v=G8GdNAZE98E) that uses the [APIs Explorer to change the primary domain](https://developers.google.com/apis-explorer/#p/admin/directory_v1/)
* [Google APIs Developer console](https://console.developers.google.com/project) – to set up a project and download your client_secret.json data
* [Google Directory API Go Quickstart](https://developers.google.com/admin-sdk/directory/v1/quickstart/go)
* [Documentation for API Go package](https://godoc.org/google.golang.org/api/admin/directory/v1)