import 'dart:convert'; import 'dart:io'; import 'package:cathaypay_mobile/Login/LoginValidate.dart'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:http_parser/http_parser.dart'; import 'package:mime/mime.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../Home/HomePage.dart'; import '../model/token_model.dart'; import '../utils/utils.dart'; class Api { static String userAdmin = "admin"; static String passAdmin = "P@ssword1"; static String mobileAdmin = "0987654321"; static String API_KEY = "1807520152955802"; static String API_SECRET = "212ff75df009bacb70a00e819b35c5c6"; static String BaseUrlBuildingReadCard = "https://ocr.71dev.com/"; static String BaseUrlBuilding = "https://neo.cathay-pay.com/"; static String BaseUrlCathay = "https://neotravel.cathay-pay.com/neo-api/api/"; static String refresh_token = "${BaseUrlBuilding}api/v1/User/refresh"; static String login = BaseUrlBuilding + "api/v3/User/Login"; static String register = BaseUrlBuilding + "api/v1/User/registerPersonal"; static String forgot_password = BaseUrlBuilding + "api/v2/Authentication/ForgotPassword"; static String image_id_card = BaseUrlBuildingReadCard + "process_image"; static String image_id_card_back = BaseUrlBuildingReadCard + "process_back_card_image"; static String image_face_detect = BaseUrlBuildingReadCard + "face_detect"; static String balance = BaseUrlBuilding + "api/v2/Authentication/getBalance"; static String profile = BaseUrlBuilding + "api/v2/Authentication/getProfile"; static String point = BaseUrlBuilding + "api/v2/Authentication/getPoint"; static String transferedPromptPayInitial = BaseUrlBuilding + "api/v2/Payment/transaction/TransferedPromptPayInitial"; static String transferedPromptPayConfirm = BaseUrlBuilding + "api/v2/Payment/transaction/TransferedPromptPayConfirm"; // static String qrcodeCreate = BaseUrlBuilding + "api/v2/QR/create/TransferedQR"; // static String qrcodeConfirm = BaseUrlBuilding + "api/v2/Payment/transaction/ConfirmTransferedQR"; static String myQrCode = BaseUrlBuilding + "api/v2/QR/create/myQR"; static String myQrCodeConfirm = BaseUrlBuilding + "api/v2/Payment/transaction/ConfirmmyQR"; static String qrCodeTransfer = BaseUrlBuilding + "api/v2/QR/create/TransferedQR"; static String qrCodeTransferConfirm = BaseUrlBuilding + "api/v2/Payment/transaction/ConfirmTransferedQR"; static String initC2B = BaseUrlBuilding + "api/v2/Payment/transaction/initialB2C"; static String getTransactionTopUp = BaseUrlBuilding + "api/v2/EPaymentSCB/GetEPaymentRequestCriteria"; static String getTransactionTopUpV4 = BaseUrlBuilding + "api/v4/EPaymentReport/GetModelLogCriteria"; static String ekyc = BaseUrlCathay + "common/kyc"; static String uploadImage = BaseUrlCathay + "common/upload"; static String walletTopup = BaseUrlBuilding + "api/V2/EPaymentSCB/WalletTopup"; static String lockTest = BaseUrlBuilding + "api/V2/Authentication/LockUnlock"; static String otp = "https://otp.thaibulksms.com/v2/otp/request"; static String verify = "https://otp.thaibulksms.com/v2/otp/verify"; static String otpEmail = BaseUrlCathay+"common/user_login/otp/"; static String menuIcons = BaseUrlCathay+"common/icon?is_use=true"; static String banner = BaseUrlCathay + "common/banner?is_use=true"; static String promotion = BaseUrlCathay + "common/promotion?is_use=true"; static String getTokenAdmin = BaseUrlBuilding + "api/v3/User/Login"; static String c2bCreate = BaseUrlBuilding + "api/v2/QR/create/C2B"; static String c2bInitial = BaseUrlBuilding + "api/v2/Payment/transaction/initialC2B"; static String c2bConfirm = BaseUrlBuilding + "api/v2/Payment/transaction/confirmC2B"; //static String getTransaction = BaseUrlBuilding + "api/v2/Payment/getTransaction"; static String getTransaction = BaseUrlBuilding + "api/v2/EPaymentReport/GetModelLogCriteria"; static String getTransactionV4 = BaseUrlBuilding + "api/v4/EPaymentReport/GetModelLogCriteria"; // static String BaseUrlBuildingCathay = "https://sathorn.cathay-pay.com/"; static String payPromptPayInitial = BaseUrlBuilding + "api/v2/EPaymentBBL/TransferedPromptPayIDInitial"; static String payPromptPayConfirm = BaseUrlBuilding + "api/v2/EPaymentBBL/TransferedPromptPayIDConfirm"; static String payThaiInitial = BaseUrlBuilding + "api/v2/EPaymentBBL/TransferedPromptPayQRInitial"; static String payThaiConfirm = BaseUrlBuilding + "api/v2/EPaymentBBL/TransferedPromptPayQRConfirm"; static String user = BaseUrlBuilding + "api/v1/User"; static String callBackURL = "http://www.responseClient.com"; static String merchantId = "TCPPROD1600"; // static Profile? profile; // // // static setProfile(Profile p) { // profile = p; // } static Future imageUploadPath(String api, File image) async { var uri = Uri.parse(api); final mimeTypeData = lookupMimeType(image.path, headerBytes: [0xFF, 0xD8])?.split('/'); // Intilize the multipart request final imageUploadRequest = http.MultipartRequest('POST', uri); // Attach the file in the request final file = await http.MultipartFile.fromPath('file', image.path, contentType: MediaType(mimeTypeData![0], mimeTypeData[1])); imageUploadRequest.files.add(file); // add headers if needed //imageUploadRequest.headers.addAll(); try { final streamedResponse = await imageUploadRequest.send(); final response = await http.Response.fromStream(streamedResponse); printApiStatus(response); if (response.statusCode == 200 || response.statusCode == 201) { final jsonResponse = json.decode(response.body); printLongString("response api $jsonResponse"); return jsonResponse; } } catch (e) { print(e); return null; } } static Future imageUpload(String api, File image) async { var uri = Uri.parse(api); final mimeTypeData = lookupMimeType(image.path, headerBytes: [0xFF, 0xD8])?.split('/'); // Intilize the multipart request final imageUploadRequest = http.MultipartRequest('POST', uri); // Attach the file in the request final file = await http.MultipartFile.fromPath('file', image.path, contentType: MediaType(mimeTypeData![0], mimeTypeData[1])); imageUploadRequest.files.add(file); // add headers if needed //imageUploadRequest.headers.addAll(); try { final streamedResponse = await imageUploadRequest.send(); final response = await http.Response.fromStream(streamedResponse); printApiStatus(response); try { // var res = response.body; // final jsonResponse = json.decode(res.substring(1,res.length-1)); final jsonRes = jsonDecode(utf8.decode(response.bodyBytes)); final jsonResponse = json.decode(jsonRes); print(jsonResponse); return jsonResponse; } catch (a) { print(a); } } catch (e) { print(e); return null; } } static Future refreshToken(BuildContext context) async { var param = jsonEncode({"accessToken": tokenModel?.token, "refreshToken": tokenModel?.refreshToken}); var value = await postLogin(context, Api.refresh_token, param); if (value != null) { tokenModel?.token = value["result"]["accessToken"]; tokenModel?.refreshToken = value["result"]["refreshToken"]; storeProfile(jsonEncode(tokenModel?.toJson())); return tokenModel; } } static Future get(BuildContext context, String url) async { try { http.Response response; if (tokenModel != null) { printLongString("start api " + url + "\ntoken = " + tokenModel!.token!); Map requestHeaders = {HttpHeaders.contentTypeHeader: "application/json", "Authorization": "Bearer ${tokenModel!.token!}"}; print(requestHeaders.toString()); response = await http.get(Uri.parse(url), headers: requestHeaders); } else { Map requestHeaders = {HttpHeaders.contentTypeHeader: "application/json"}; response = await http.get(Uri.parse(url), headers: requestHeaders); } printApiStatus(response); if (response.statusCode == 200 || response.statusCode == 201) { final jsonResponse = json.decode(response.body); printLongString("response api ${jsonResponse}"); return jsonResponse; } else if (response.statusCode == 401) { var value = await refreshToken(context); if (value != null) { var value = await get(context, url); return value; } } else { showAlertDialog(context, "กรุณาตรวจสอบ Internet ของท่าน"); // showAlertDialog(context, response.body); try { final jsonResponse = json.decode(response.body); print(response.body); return jsonResponse; } catch (a) { print(a); } } } catch (e) { print(e); // showAlertDialog(context, e.toString()); } } static Future getRaw(BuildContext context, String url) async { try { http.Response response; if (tokenModel != null) { printLongString("start api " + url + "\ntoken = " + tokenModel!.token!); Map requestHeaders = {HttpHeaders.contentTypeHeader: "application/json", "Authorization": "Bearer ${tokenModel!.token!}"}; print(requestHeaders.toString()); response = await http.get(Uri.parse(url), headers: requestHeaders); } else { Map requestHeaders = {HttpHeaders.contentTypeHeader: "application/json"}; response = await http.get(Uri.parse(url), headers: requestHeaders); } printApiStatus(response); if (response.statusCode == 200 || response.statusCode == 201) { // final jsonResponse = json.decode(response.body); printLongString("response api ${response.body}"); return response.body; } else if (response.statusCode == 401) { var value = await refreshToken(context); if (value != null) { var value = await get(context, url); return value; } } else { showAlertDialog(context, "กรุณาตรวจสอบ Internet ของท่าน"); // showAlertDialog(context, response.body); try { // final jsonResponse = json.decode(response.body); print(response.body); return response.body; } catch (a) { print(a); } } } catch (e) { print(e); // showAlertDialog(context, e.toString()); } } static Future postLogin(BuildContext context, String url, String jsonParam) async { printLongString(jsonParam); try { var response; Map requestHeaders = {HttpHeaders.contentTypeHeader: "application/json"}; response = await http.post(Uri.parse(url), body: jsonParam, headers: requestHeaders); printApiStatus(response); if (response.statusCode == 200 || response.statusCode == 201 || response.statusCode == 204) { final jsonResponse = json.decode(response.body); return jsonResponse; } else if (response.statusCode == 404) { // showAlertDialog(context, "Not found"); showAlertDialog(context, "กรุณาตรวจสอบ Internet ของท่าน"); } else { showAlertDialog(context, "กรุณาตรวจสอบ Internet ของท่าน"); // final jsonResponse = json.decode(response.body); // var code = jsonResponse["Error"]["Code"]; // if (code == 112) { // showAlertDialog(context, jsonResponse["Error"]["Message"]); // } else if (code == 111) { // showAlertDialog(context, jsonResponse["Error"]["Message"]); // } else if (code == 113) { // showAlertDialog(context, jsonResponse["Error"]["Message"]); // } } } catch (e) { print(e); // showAlertDialog(context, e.toString()); } } static Future post(BuildContext context, String url, String jsonParam) async { printLongString(url); printLongString(jsonParam); try { var response; if (tokenModel != null) { Map requestHeaders = {HttpHeaders.contentTypeHeader: "application/json", "Authorization": "Bearer ${tokenModel!.token!}"}; response = await http.post(Uri.parse(url), body: jsonParam, headers: requestHeaders); } else { Map requestHeaders = {HttpHeaders.contentTypeHeader: "application/json"}; response = await http.post(Uri.parse(url), body: jsonParam, headers: requestHeaders); } printApiStatus(response); if (response.statusCode == 200 || response.statusCode == 201 || response.statusCode == 204) { final jsonResponse = json.decode(response.body); return jsonResponse; } else if (response.statusCode == 404) { // showAlertDialog(context, "Not found"); // final jsonResponse = json.decode(response.body); // var des = jsonResponse["status"]["description"]; // showAlertDialog(context, des); showAlertDialog(context, "กรุณาตรวจสอบ Internet ของท่าน"); } else if (response.statusCode == 401) { var value = await refreshToken(context); if (value != null) { var value = await post(context, url, jsonParam); return value; } } else { showAlertDialog(context, "กรุณาตรวจสอบ Internet ของท่าน"); // final jsonResponse = json.decode(response.body); // var code = jsonResponse["Error"]["Code"]; // if (code == 112) { // showAlertDialog(context, jsonResponse["Error"]["Message"]); // } else if (code == 111) { // showAlertDialog(context, jsonResponse["Error"]["Message"]); // } else if (code == 113) { // showAlertDialog(context, jsonResponse["Error"]["Message"]); // } } } catch (e) { print(e); // showAlertDialog(context, e.toString()); } } static storeProfile(var jsonString) async { SharedPreferences prefs = await SharedPreferences.getInstance(); await prefs.setString('access_token', jsonString); } static Future postGetMessage(BuildContext context, String url, String jsonParam) async { printLongString(url); printLongString(jsonParam); try { var response; if (tokenModel != null) { Map requestHeaders = {HttpHeaders.contentTypeHeader: "application/json", "Authorization": "Bearer ${tokenModel!.token!}"}; response = await http.post(Uri.parse(url), body: jsonParam, headers: requestHeaders); } else { Map requestHeaders = {HttpHeaders.contentTypeHeader: "application/json"}; response = await http.post(Uri.parse(url), body: jsonParam, headers: requestHeaders); } printApiStatus(response); if (response.statusCode == 200 || response.statusCode == 201 || response.statusCode == 204) { final jsonResponse = json.decode(response.body); return jsonResponse; } else { showAlertDialog(context, response.body); // final jsonResponse = json.decode(response.body); // var code = jsonResponse["Error"]["Code"]; // if (code == 112) { // showAlertDialog(context, jsonResponse["Error"]["Message"]); // } else if (code == 111) { // showAlertDialog(context, jsonResponse["Error"]["Message"]); // } else if (code == 113) { // showAlertDialog(context, jsonResponse["Error"]["Message"]); // } } } catch (e) { print(e); // showAlertDialog(context, e.toString()); } } static Future postStatus(BuildContext context, String url, String jsonParam) async { printLongString(url); printLongString(jsonParam); try { var response; if (tokenModel != null) { Map requestHeaders = {HttpHeaders.contentTypeHeader: "application/json", "Authorization": "Bearer ${tokenModel!.token!}"}; response = await http.post(Uri.parse(url), body: jsonParam, headers: requestHeaders); } else { Map requestHeaders = {HttpHeaders.contentTypeHeader: "application/json"}; response = await http.post(Uri.parse(url), body: jsonParam, headers: requestHeaders); } printApiStatus(response); if (response.statusCode == 200 || response.statusCode == 201 || response.statusCode == 204) { final jsonResponse = json.decode(response.body); return jsonResponse; } else { // showAlertDialog(context, response.body); // final jsonResponse = json.decode(response.body); // var code = jsonResponse["Error"]["Code"]; // if (code == 112) { // showAlertDialog(context, jsonResponse["Error"]["Message"]); // } else if (code == 111) { // showAlertDialog(context, jsonResponse["Error"]["Message"]); // } else if (code == 113) { // showAlertDialog(context, jsonResponse["Error"]["Message"]); // } } } catch (e) { print(e); // showAlertDialog(context, e.toString()); } } static Future refreshTokenAdmin(BuildContext context) async { // Api.get(context, Api.getTokenAdmin).then((value) => {tokenAdmin = value["token"]}); var param = jsonEncode({ "UserName": Api.userAdmin, "Password": Api.passAdmin, "MobileDeviceId": Api.mobileAdmin, }); var value = await postLogin(context, Api.login, param); if (value != null) { var tokenModel = TokenModel.fromJson(value); tokenAdmin = tokenModel.token ?? ""; return tokenAdmin; } } static Future postAdmin(BuildContext context, String url, String jsonParam) async { printLongString(url); printLongString(jsonParam); try { var response; if (tokenAdmin != null) { Map requestHeaders = {HttpHeaders.contentTypeHeader: "application/json", "Authorization": "Bearer $tokenAdmin"}; response = await http.post(Uri.parse(url), body: jsonParam, headers: requestHeaders); } else { Map requestHeaders = {HttpHeaders.contentTypeHeader: "application/json"}; response = await http.post(Uri.parse(url), body: jsonParam, headers: requestHeaders); } printApiStatus(response); if (response.statusCode == 200 || response.statusCode == 201 || response.statusCode == 204) { final jsonResponse = json.decode(response.body); return jsonResponse; } else if (response.statusCode == 401) { var value = await refreshTokenAdmin(context); if (value != null) { var value = await postAdmin(context, url, jsonParam); return value; } } else if (response.statusCode == 404) { showAlertDialog(context, "กรุณาตรวจสอบ Internet ของท่าน"); } else { showAlertDialog(context, "กรุณาตรวจสอบ Internet ของท่าน"); } } catch (e) { print(e); // showAlertDialog(context, e.toString()); } } static Future put(BuildContext context, String url, String jsonParam) async { print(url); try { print(jsonParam); // http.Response response = await http.post( // Uri.parse(url), // body: jsonParam, // headers: { // HttpHeaders.contentTypeHeader: "application/json" // }, // ); var response; // if (authenToken != null) { // Map requestHeaders = { // 'Accept': 'application/json', // HttpHeaders.contentTypeHeader: "application/json" // // 'user_id': "38" // }; // response = await http.put(Uri.parse(url), // body: jsonParam, headers: requestHeaders); // } else { Map requestHeaders = { HttpHeaders.contentTypeHeader: "application/json" // 'user_id': "38" }; response = await http.post(Uri.parse(url), body: jsonParam, headers: requestHeaders); // } print('print respon status code = ' + response.statusCode.toString()); if (response.statusCode == 200 || response.statusCode == 201 || response.statusCode == 204) { if (response.body != null) { print(response.body); final jsonResponse = json.decode(response.body); return jsonResponse; } else {} } else if (response.statusCode == 404) { // showAlertDialog(context, "Not found"); } else { final jsonResponse = json.decode(response.body); var code = jsonResponse["Error"]["Code"]; if (code == 112) { showAlertDialog(context, jsonResponse["Error"]["Message"]); } else if (code == 111) { showAlertDialog(context, jsonResponse["Error"]["Message"]); } else if (code == 113) { showAlertDialog(context, jsonResponse["Error"]["Message"]); } } } catch (e) { print(e); // showAlertDialog(context, e.toString()); } } static showAlertDialog(BuildContext context, String message) { // set up the button Widget okButton = ElevatedButton( child: Text("OK"), onPressed: () { Navigator.pop(context); }, ); // set up the AlertDialog AlertDialog alert = AlertDialog( content: Text(message), actions: [ okButton, ], ); // show the dialog showDialog( context: context, builder: (BuildContext context) { return alert; }, ); } static showLoaderDialog(BuildContext context) { AlertDialog alert = AlertDialog( content: new Row( children: [ CircularProgressIndicator(), Container(margin: EdgeInsets.only(left: 7), child: Text("Loading...")), ], ), ); showDialog( barrierDismissible: false, context: context, builder: (BuildContext context) { return alert; }, ); } }