JK Rowling was unmasked as the secret author of crime fiction novel The Cuckoo's Calling not by dogged detective work, but by an indiscreet Twitter exchange between a journalist and a family friend of a solicitor at her law firm.

The circumstances of Rowling's public outing as the pseudonymous debut author behind The Cuckoo's Calling, which she penned under the name Robert Galbraith, were confirmed at the high court in London on Wednesday.

The law firm Russells has agreed to make a substantial donation to The Soldiers' Charity, at Rowling's request, and apologised publicly for the indiscretion.

Rowling had only told a "handful" of her most trusted advisers that she wrote the crime novel, the court heard, but the pseudonym unravelled after a conversation between Christoper Gossage, a partner at Rowling's law firm Russells, and his family friend Judith Callegari.

Gossage divulged the secret to Callegari, who then disclosed it publicly during a Twitter conversation with a Sunday Times journalist, the court heard.

Rowling was left "betrayed and distressed by such a fundamental betrayal of trust" after the Sunday Times splashed on the revelation on 14 July, the author's lawyer Jenny Afia told the court.

Rowling, who was not in court for the hearing, said in a statement: "This donation is being made to The Soldiers' Charity partly as a thank you to the army people who helped me with research, but also because writing a hero who is a veteran has given me even greater appreciation and understanding of exactly how much this charity does for ex-servicemen and their families, and how much that support is needed.

"I always intended to give The Soldiers' Charity a donation out of Robert's royalties, but I had not anticipated him making the bestseller list a mere three months after publication (indeed, I had not counted on him ever being there!)."

Afia told the court that Rowling was "angry and distressed that her confidences had been betrayed and this was very much aggravated by repeated speculation that the leak had, in fact, been a carefully co-ordinated publicity stunt by her, her agent and her publishers, designed to increase sales."

Solicitors for Gossage and Callegari said they had offered their sincere apologies to Rowling and legally undertaken "not to make any further public statements about this incident or the claimant."

Rowling will donate the equivalent of three years' worth of royalties from The Cuckoo's Calling to The Soldiers' Charity. "It's a not insignificant amount. We're over the moon," said a spokesman for the charity.

• To contact the MediaGuardian news desk email media@theguardian.com or phone 020 3353 3857. For all other inquiries please call the main Guardian switchboard on 020 3353 2000. If you are writing a comment for publication, please mark clearly "for publication".

• To get the latest media news to your desktop or mobile, follow MediaGuardian on Twitter and Facebook.