In a 4-3 vote, the nation's top electoral court ruled that the 2014 campaign that earned him a second term as vice president — before he ascended to the presidency with the impeachment of Dilma Rouseff — did not break campaign finance rules.
The decision allows him to keep his job until his term ends next year.
The case, which was brought by the Brazilian Social Democracy Party after the 2014 election, alleged that Temer's ticket had received illegal contributions.
Without a deadline for the seven judges of the court to hear the case, it dragged on. A hearing was finally held in April, but then delayed until June to allowed new witnesses to testify. Legal experts accused Temer's team of stall tactics.
Temer became president in August after Rouseff was impeached for illegally moving funds between government budgets.
The hearing this week was for both Temer and Rouseff. Both denied any wrongdoing.
A ruling against them would have annulled the 2014 election, forcing Temer out of office.
Initially expected to last three days, the hearing was extended by a day to allow for more debate, including over whether testimony in the country's billion-dollar Lava Jato corruption investigation should be considered. It was.
The decision was 3 to 3 until the court's president, Gilmar Mendes, cast the final vote. His friendship with Temer, which both have acknowledged, has stirred debate over whether he should have recused himself.
The court released a statement saying that the judge frequently meets with politicians to discuss electoral reform and that all of his meetings with Temer have been transparent.
Temer, whose approval rate is 4%, is also being investigated on allegations of approving the payment of hush money to impeached lower house speaker Eduardo Cunha, who is currently serving a 15-year prison sentence for corruption, money laundering and tax evasion.
The president is also accused of receiving bribes by way of his former aide, Rodrigo Rocha Loures, who was arrested on June 3 after police released video that authorities said showed him carrying a suitcase containing $154,000.