Pfizer Inc. has agreed to pay nearly $24 million to resolve allegations that it violated federal law by using a charity to pay Medicare patients’ out-of-pocket costs for the company’s prescription drugs, federal prosecutors said.

The settlement, with the U.S. Attorney’s Office in Boston, resolves allegations stemming from an investigation into charities that help patients pay for prescription drugs using donations from pharmaceutical companies.

Pfizer...