Hey Roy,
I'm sorry you're running into issues with Twilio Functions. I've dug into the issue and I think I found the problem.
The first thing I tried was creating a Function with the lines of code you provided and the problematic JSON payload. In that scenario I am able to replicate your error. However, then I try the same code against your second JSON payload I do not get a successful request. In fact, in the second scenario I see the same error as with the original problematic JSON payload. This lead me to believe the error isn't with Twilio Functions.
I dug into your code and I think I found the issue. As is your code is attempt to JSON parse the first key returns by Object.keys(). I've annotated the snippet you provided to illustrate what is happening.
var keys = Object.keys(event); // [ "apikey", "status", "member", "plan"]
var body = keys[0].replace(/\n/g, " ").replace(/_/g, " "); // "apikey".replace(/\n/g, " ").replace(/_/g, " ") => "apikey"
var req = JSON.parse(body); // JSON.parse("apikey")
It seems like you are trying to parse the HTTP request body into JSON object. Luckily you don't need to do that with Twilio Functions. When you provide the appropriate Content-Type then Functions will populate the event object with your JSON payload. So, to access the API Key field from your request all you need to do is "event.apikey".
Hopefully, this helped unblock you. Please let me know if you have any other questions or feedback.
Thanks,
Chris Corcoran
Product Manager, Twilio Functions