I'm trying to receive response order_token
from test API https://sandbox.cashfree.com/pg/orders
which is used to create session of a payment gateway. Here is the code.
CFEnvironment environment = CFEnvironment.SANDBOX;
Future<dynamic> createOrder() async {
var response = await http.post(
Uri.https('https://sandbox.cashfree.com/pg/orders'),
headers: {
'Content-Type': 'application/json',
'x-client-id': 'your x-client-id',
'x-client-secret': 'your x-client-secret',
'x-api-version': '2022-01-01',
'x-request-id': 'developer_name',
},
body: jsonEncode(
{
"order_id": widget.cartId,
"order_amount": widget.grandTotal,
"order_currency": "INR",
"order_note": "Additional order info",
"customer_details": {
"customer_id": widget.address.id,
"customer_name": "name",
"customer_email": widget.email,
"customer_phone": widget.address.phone,
}
},
),
);
if (response.statusCode == 200) {
if (jsonDecode(response.body)['status'] == 'OK') {
debugPrint(jsonDecode(response.body)['order_id']);
debugPrint('log');
Logger.i(response.body);
return jsonDecode(response.body)['order_id'];
}
}
return '';
}
createSession() {
createOrder().then((value) {
try {
var session = CFSessionBuilder()
.setEnvironment(environment)
.setOrderId(widget.cartId!)
.setOrderToken(value)
.build();
return session;
} on CFException catch (e) {
debugPrint(e.message);
}
});
return null;
}
But the response seems to null and payment gateway doesn't open. What might be going wrong with my code? I tried printing response but there in null value there,What might be going wrong? How do I get a response? I've done this in postman I get a response.
CodePudding user response:
replace header placeholders with actual values like your x-client-secret
and others
CodePudding user response:
Try this
var decodedResponse = jsonDecode(utf8.decode(response.bodyBytes)) as Map;
orderId = decodedResponse["order_id"] as String;
orderToken = decodedResponse["order_token"] as String;
Once the order is created and session is created, there are further steps, then only the checkout page will open. Refer this example - https://pub.dev/packages/flutter_cashfree_pg_sdk/example
Note :- Ideally, you shouldn't be creating order from app level. It should be done from your backend (Move the order creation to your backend).