Question: Do publishers give you an advance as some sort of earnest money for your manuscript? If your work doesn't sell very well do you have to give the advance back to them?

Do they ever just buy your work and you get some money plus royalties?

thanks.

Answer: 
**Maybe**. If, for some unforeseen reason, the book is cancelled between the time the contract is signed and the publication date, the publisher may request that any paid-out portion of the advance be repaid.

For instance, it might happen if the first half of the book is amazing, but the second half is a complete turkey. Or if the second half never gets submitted at all. Or a million other reasons.

But the contract should say what happens, or at least what the publisher is allowed to ask for and when.
As someone else stated, it depends on your contract. I had a situation where I received an advance for a book proposal, but personal issues and family matters caused me to miss my deadline, and the publisher requested the money back. I hadn't spent any of it and felt it was the right thing to do because I hadn't delivered as promised. (I was aware beforehand that if I wasn't able to finish the book within a certain time range I would have to refund the advance, which is why I still had it!)

In general, though, once the publisher has accepted the book and you have delivered, the advance is yours to keep. If the book doesn't sell well enough, then the publisher takes a loss. That's one of the reasons why new writers get smaller advances: they are a bigger risk. By the same token, you don't receive another penny from the publisher until the book makes enough money to pay the advance back to the publisher. Only then do you start collecting royalties.