Payfast Api integration to Flutter App Http request Errors - flutter

I am building an app with Payfast payment gateway. The gateways documentaion only covers php side but I want to make it by requesting https. Trying to resolve the situation but don't understand where I am wrong.
Trying to make simple form integration on this site payfast_developers_docs
I got 404 and 500 error. Can not reach checkout form. Thanks for now.
Below my source code;
DateTime ax= DateTime.now();
print(ax);
String a = "amount=100.00&Content-Type=application/json&item_name=#000001&merchant_id=10000100&merchant_id=10000100&merchant_key=46f0cd694581a&timestamp=$ax&version=v1";
md5.convert(utf8.encode(a)).toString();
//String pkistring = v1hashing(requeststr);
HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.postUrl(Uri.https( "sandbox.payfast.co.za", "/eng/process​"));
request.headers.set('Content-Type' , 'application/json');
request.headers.set('merchant-id' , '10000100');
request.headers.set('version' , 'v1');
request.headers.set('timestamp' , ax);
request.headers.set('signature' , md5.convert(utf8.encode(a)).toString());
//headers
//request.headers.set('Accept' , 'application/json');
Map body = { 'merchant_id' : '10000100',
'merchant_key' : '46f0cd694581a',
'amount' : '100.00',
'item_name' : '#000001',
'signature': '${md5.convert(utf8.encode(a)).toString()}'} ;
//body
request.add(utf8.encode(json.encode(body)));
//response cevap
HttpClientResponse response = await request.close();
print(response.statusCode); // baglanti yapildi mi yapilmadi mi 200 ise yapildi
String reply = await response.transform(utf8.decoder).join();
//Map responseMap = json.decode(reply);
httpClient.close();
print("payfast ici odeme");
print(reply);
Navigator.push(context, MaterialPageRoute(builder: (context) => new a3dsecure(reply)));

Related

Flutter Integrate Apple pay response to stripe

Unhandled Exception: StripeException(error: LocalizedErrorMessage(code: FailureCode.Failed, localizedMessage: There was an unexpected error -- try again in a few seconds, message: No such payment_intent: 'pi_3M9vFfDn3WtZLRhzO5kP10SM', stripeErrorCode: resource_missing, declineCode: null, type: invalid_request_error))
I hit apple pay then after payment , reverted to stripe payment intent and then I get client secret from response . I revert that response to Stripe for payment verification and I got response as No such payment_intent or getting payment method reuired
#ᴅ ᴇ ʙ ᴊ ᴇᴇ ᴛ and #orakaro here is what I done
Future<void> onApplePayResult(paymentResult) async {
debugPrint("paymentResult.toString() is ${paymentResult.toString()}");
var data = jsonDecode(paymentResult['token']);
debugPrint("data is $data");
String transactionId = data['data'];
var response = await PaymentService().makePayment(
context: context,
amount: 100
,
);
String clientSecret = response['client_secret'].toString();
final params = PaymentMethodParams.cardFromToken(
paymentMethodData: PaymentMethodDataCardFromToken(
token: token,
));
await Stripe.instance.confirmPayment(
"clientSecret",
params,
);
}

How to handle cors for web flutter

I have been struggle to fix the cors problem in my PWA project of flutter and I am following this
how to solve flutter CERTIFICATE_VERIFY_FAILED error while performing a POST request?.
I am using universal_io package since dart.io can not be used for web...here is the part of the code
HttpClient client = new HttpClient();
client.badCertificateCallback =
((X509Certificate cert, String host, int port) => true);
String url = 'https:xxxx.php';
Map map = {
"a": "a",
"b": "b"
};
HttpClientRequest request = await client.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(json.encode(map)));
if (request is BrowserHttpClientRequest) {
request.credentialsMode = BrowserHttpClientCredentialsMode.include;
}
HttpClientResponse response = await request.close();
print(response.toString());
String reply = await response.transform(utf8.decoder).join();
print(reply);
but I get the error that say like this
--------------------------------------------------------------------------------
BrowserHttpClient received an error from XMLHttpRequest (which doesn't tell
reason for the error).
HTTP method: POST
URL: https://www.rscm.co.id/apirscm/v2.php
Origin: http://localhost:64121
Cross-origin request!
XmlHttpRequest 'credentials mode' is enabled.
Did the server send the following mandatory headers?
* Access-Control-Allow-Credentials: true
* Access-Control-Allow-Origin: http://localhost:64121
* In credentials mode, '*' would fail!
* Access-Control-Allow-Methods: POST
is there a way to solve this problem?
You can you local host server in the debug mode of chrome, here is how:
open this in terminal.
open -n -a /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --args --user-data-dir="/Users/i0868/Desktop/Chrome" --disable-web-security
you can do something like thisto enable credentials mode:
final httpClientRequest = MyHttpClientRequest;
if (httpClientRequest is BrowserHttpClientRequest) {
httpClientRequest.credentialsMode = BrowserHttpClientCredentialsMode.include;
}
But prefer using this librairy universal_io instead of dart.io

problem with flutter and post http request for authentication with nginx server with flask

I'm testen with writing an rest-api in Flask in combination with a mobile flutter client.
I have a problem with authentication wiht Flask-JWT.
I use ngnix and uwsgi to run the flask application on ubuntu 20.04.
With debug mode of the flask app, it runs without without problems.
With Postman it works always.
Flutter dart code:
Future<String> authRequest() async {
try {
final HttpClient client = HttpClient();
client.badCertificateCallback =
((X509Certificate cert, String host, int port) =>
true); // accept all certificat
final Map login = {
"username": "user",
"password": "goodsecret",
};
final request = await client.postUrl(Uri.parse(ProviderBase.url + '/auth'));
request.headers.add(HttpHeaders.contentTypeHeader, "application/json");
request.add(utf8.encode(json.encode(login)));
final response = await request.close();
final reply = await response.transform(utf8.decoder).join();
final jresponse = json.decode(reply);
ProviderBase.authtoken = jresponse['access_token'];
print('token: ${ProviderBase.authtoken}');
} catch (error) {
print('Error: ${error.toString()}');
}
}
I get this error message (response) in flutter:
"<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>"
Maybe someone has an idea?
I uses at the moment self signed certificate.
I found the solution:
it's the missing header content length. With the webserver it's necessary.
this works for me:
...
final body = utf8.encode(json.encode(login));
request.headers.add(HttpHeaders.contentTypeHeader, "application/json");
request.headers.add(HttpHeaders.contentLengthHeader, body.length.toString());
request.add(body);
...

How i can get Token from headers?

I did authorization via http. post, send a JSON Body with username and password, in the response I get a Header, the Header has a token, it is stored in 'set_cookie: Authorization=token', how do I get it and write it to the storage?
You can get the cookie from the response of login request using the following code
HttpClient _httpClient = new HttpClient();
HttpClientRequest request = await _httpClient.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(json.encode(jsonMap)));
HttpClientResponse response = await request.close();
print(response.cookies); // this is a List<Cookie>, you can iterate and find the required cookie
Now you can store the cookie using shared_preference plugin, and use it in your all the future requests.
HttpClient client = new HttpClient();
HttpClientRequest clientRequest =
await client.getUrl(Uri.parse("http: //www.example.com/"));
clientRequest.cookies.add(Cookie("sessionid", "asdasdasqqwd"));
You can also explore dio library and use AuthInterceptor to add the token for all the requests for you.

Flutter Dart HTTP POST request body is empty on server side

I am working on a Flutter tablet app. Once one input field is inputted, I am trying to send a post request to the server. Following is the method I am invoking for this:
Future < http.Response > _postRequest() async {
print(globals.novaCoord.toString() + ' XYZXYZXYZXYZXYZ');
var url = globals.URL + 'api/nova_position';
Map data = {
'id_nova': '1',
'position.x': '1',
'position.y': '1',
'position.z': '1',
'position.pitch': '1',
'position.yaw': '1',
'position.roll': '1',
};
//encode Map to JSON
var body = json.encode(data);
http.Response response = await http.post(url,
headers: {
"Content-Type": "application/json"
},
body: body
);
print("${response.statusCode}");
print("${response.body}");
return response;
}
And on the NodeJs server side I have this:
app.post('/api/nova_position/', async (req,res) => {
console.log("NOVA POSITION");
console.log(req.body.id_nova);
const id_nova = req.body.id_nova;
const x = req.body.position.x;
const y = req.body.position.y;
const z = req.body.position.z;
const pitch = req.body.position.pitch;
const yaw = req.body.position.yaw;
const roll = req.body.position.roll;
const position = await db.db.create_position(id_nova,x,y,z,pitch,yaw,roll);
});
However, on the server-side, I am receiving an empty "body" for the request I sent and I receive the following error:
(node:23939) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'x' of undefined
I need help at this point. I appreciate any help and guidance.
Sending Map<String,dynamic> with http.post won't send your data properly.
To solve this, change the content-type of the header to:
Map<String, String> customHeaders = {
...
"content-type": "application/json"
...
};
Then, you can use http.post as follows:
http.post(url, headers: customHeaders, body);
You have to jsonEncode before pushing into Post request
Like
String bodyF = jsonEncode(body);
And i hope you will get your solution.
The solution I have found was simply to add Content-Length : x to your header, with x being the size of your json body.