You can apply direct to St Andrews Links Trust. Details here. You need to apply two days ahead of play, before 14:00. For example to play on a Thursday you should apply in the window from when the ballot opens around 14:15 on Monday and before it closes at 14:00 on Tuesday. You do not have to apply immediately the ballot opens as it is not first come, first served.