· 7 years ago · Sep 09, 2018, 10:50 AM
1try {
2 int type = 1; // Loại thẻ Viettel
3 String serial = "08476107812"; // Seri thẻ cà o
4 String code = "0072919362926"; // Mã thẻ cà o
5 int amount = 100000; // Mệnh giá thẻ
6
7 // ID tà i khoản của bạn
8 String merchant_id = "04a23a03-ce2f-49ae-8a1e-379aea66f8ee";
9
10 // Mã bà máºt
11 String secret_key = "4b380bf3872c554aef96806a";
12
13 String data = merchant_id + type + serial + code + amount;
14
15 Mac sha256 = Mac.getInstance("HmacSHA256");
16 SecretKeySpec key = new SecretKeySpec(secret_key.getBytes("UTF-8"), "HmacSHA256");
17 sha256.init(key);
18
19 String signature = Base64.getEncoder().encodeToString(data.getBytes());
20
21 URL url = new URL("https://recard.vn/api/card");
22 HttpURLConnection con = (HttpURLConnection) url.openConnection();
23 con.setRequestMethod("POST");
24 con.setRequestProperty("User-Agent", "Mozilla/5.0");
25 con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
26 con.setRequestProperty("charset", "UTF-8");
27 con.setDoOutput(true);
28 String query = "?merchant_id=" + merchant_id
29 + "&type=" + type
30 + "&serial=" + serial
31 + "&code=" + code
32 + "&amount=" + amount
33 + "&signature=" + signature;
34 DataOutputStream wr = new DataOutputStream(con.getOutputStream());
35 wr.writeBytes(query);
36 wr.flush();
37 wr.close();
38
39 int responseCode = con.getResponseCode();
40 if(responseCode == 200) {
41 // Phản hồi thà nh công
42 }else {
43 // Phản hồi thà nh lỗi
44 System.out.print("Error: '" + con.getResponseMessage() + "' - Code: " + con.getResponseCode());
45 }
46} catch (UnsupportedEncodingException e) {
47 e.printStackTrace();
48} catch (NoSuchAlgorithmException e) {
49 e.printStackTrace();
50} catch (InvalidKeyException e) {
51 e.printStackTrace();
52} catch (MalformedURLException e) {
53 e.printStackTrace();
54} catch (ProtocolException e) {
55 e.printStackTrace();
56} catch (IOException e) {
57 e.printStackTrace();
58}