The same idea exists in the US, and often bathrooms have a PIN code to enter or a special key only the shop owner has.
I’ve never been turned down when asking politely. Most people are rather sympathetic when someone needs to use the bathroom for legitimate purposes.
Business owners perceive the presence of homeless people as bad for business so they don't want to encourage homeless people to stick around. And they think homeless people will trash their bathrooms or use drugs inside which is dangerous for other customers and brings police presence.
So business owners lock up their bathrooms. Result: Even fewer places for homeless people to use the toilet.
These things aren’t just perceptions or thoughts. It’s a real problem that anyone who runs a business in a location with a homeless problem can attest to.
Businesses care about the first type because of the associated problems and are completely fine with the later.
In Turkey they really like putting formal structure to that kind of stuff and venues at the high street sometimes have a lock with a password which is printed on the receipt with your purchase. One particular McDonald's was a pioneer in this, as their location was at the most crowded and central place where people used to meet before the proliferation of cellphones.
If it’s a chain then you probably don’t have to buy anything.
If it’s a large establishment such as a supermarket then you don’t have to buy anything, nobody is keeping track.
And obviously toilets in public places like train stations are free for all nowadays.
A 8-table local run cafe? I wouldn't dare ask