WASHINGTON — Congressional Republicans, already facing a difficult election landscape, confronted a prospect on Sunday they had worked feverishly to avoid: a threat by President Trump to shut down the government over funding for a border wall.

“I would be willing to ‘shut down’ government if the Democrats do not give us the votes for Border Security, which includes the Wall!” Mr. Trump wrote on Twitter. “Must get rid of Lottery, Catch & Release etc. and finally go to system of Immigration based on MERIT! We need great people coming into our Country!”

Last week, Republican leaders thought they had reached a deal with Mr. Trump to delay a confrontation on funding for the wall until after the November midterm elections, according to a person familiar with their discussion.

But Mr. Trump’s shutdown threat, in which he also demanded several pieces of a comprehensive immigration overhaul that is stalled in Congress, has opened the door to a politically bruising spending fight as the fiscal year ends in September.