POST not working in Flutter, but works in Postman

I’m making a POST request using the Http package in my Flutter application. I tested the same request on the Api sandbox website and Postman and got a 202 Accepted response. However, in Flutter, I always get a 400 Bad Request.

I also tried with HttpClient, but still got 400 Bad Request.

import 'package:http/http.dart';
import 'package:uuid/uuid.dart';
import 'package:wave_app/env/secrets.dart';
import 'package:wave_app/models/momo_token.dart';
import 'package:http_client/http_client.dart';

    String url = "https://sandbox.momodeveloper.mtn.com/collection/v1_0/requesttopay";
    var uuid = Uuid();
    String requestId = uuid.v4();
    MomoToken token = await _createMomoNewTokenCollection();

    String auth = "Bearer " + token.accessToken;

    Map<String, String> headers = {
      "Authorization": auth,
      "X-Target-Environment": "sandbox",
      "X-Reference-Id": requestId,
      "Content-Type": "application/json",
      "Ocp-Apim-Subscription-Key": momoCollectionSubscriptionKey
    };

    String jsonBody = '{"amount": "5","currency": "EUR", "externalId": "123", "payer": {"partyIdType": "MSISDN","partyId": "46733123454"}, "payerMessage": "tripId-123456","payeeNote": "driverId-654321"}';

    HttpClient httpClient = new HttpClient();
    HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));

    request.headers.set("Authorization", "Bearer " + token.accessToken);
    request.headers.set('content-type', 'application/json');
    request.headers.set("X-Target-Environment", "sandbox");
    request.headers.set("X-Reference-Id", requestId);
    request.headers.set("Ocp-Apim-Subscription-Key", momoCollectionSubscriptionKey);

    request.add(utf8.encode(jsonBody));
    HttpClientResponse response = await request.close();

    print("STATUS CODE " + response.statusCode.toString() + "   " + response.reasonPhrase);
    String reply = await response.transform(utf8.decoder).join();
    print("REPLY " + reply);
    httpClient.close();

I’m using the same variables for the request in both Api sandbox website, Postman and Flutter, and the API doc is here. I’m not sure what I’m doing wrong here. Any help would be greatly appreciated!

The issue is that the request body is not being passed correctly. Instead of passing jsonBody as the request body, you need to pass it as a JSON-encoded string using the json.encode method from the dart:convert package.

Replace the line:

request.add(utf8.encode(jsonBody));

with:

request.write(json.encode(json.decode(jsonBody)));

This should fix the issue and allow you to make successful POST requests with the Http package in your Flutter application.