Because if they purchase it legally, Mexico will generally accept it and not try to reclaim land. They still have to border Mexico no matter what, so giving them money for the land makes sense. It established a defined border and the US gained alot of territory.
Also while the US paid $15 million, it was credited against money Mexico owed to the US so Mexico never actually saw the money.
What they paid didn't, by any stretch of the imagination equate to what the land was worth. It was done for two reasons: to maintain a benevolent reputation, and to give the impression of legality, which could become a useful precedent in the future.