How can they afford to give 5 percent cash back on gas and groceries when their transaction fees are around 2 percent?

It's a type of "legal kickback". And in many cases the card issuer is part of the corporate conglomerate, that gives the so called "rebate". Another catch is gas and groceries are considered living expenses, as opposed to luxury items. If a debtor defaults charges that were living expenses, medical expenses, educational, etc. can be disputed by the company. And can be listed as non-dischargeable in a BK situation.