-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRedInvoiceExample.java
More file actions
633 lines (574 loc) · 21.2 KB
/
RedInvoiceExample.java
File metadata and controls
633 lines (574 loc) · 21.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class RedInvoiceExample {
private static final String BASE_URL = "https://api.fa-piao.com";
/**
* 示例入口,演示POST multipart/form-data请求
*/
public static void main(String[] args) throws Exception {
try {
String appKey = "";
String appSecret = "";
String nsrsbh = "";//统一社会信用代码
String title = "";//名称(营业执照)
String username = "";//手机号码(电子税务局)
String password = "";//密码(电子税务局)
String type = "7";//6基础版 7标准
String token = "";
String fphm = "26502000000536415466";
String kprq = "";
System.setOut(new PrintStream(System.out, true, "UTF-8"));
System.out.println("java " + System.getProperty("java.version"));
if(token.isEmpty()) {// 获取token 建议redis缓存 30天
/*
* 获取授权Token文档
* @see https://fa-piao.com/doc.html#api1?source=github
*/
Map<String, Object> formData = new LinkedHashMap<>();
formData.put("nsrsbh", nsrsbh);
formData.put("type", type);
// formData.put("username", username);
// formData.put("password", password);
/*
* 获取授权Token文档
* @see https://fa-piao.com/doc.html#api1?source=github
*/
ApiResponse tokenResponse = postRequest("/v5/enterprise/authorization",formData,"" ,appKey, appSecret);
token = tokenResponse.getTokenString();
if (token == null || token.isEmpty()) {
System.out.println("获取授权失败:" + tokenResponse.getMsg());
return;
}
}
Map<String, Object> queryParams = new LinkedHashMap<>();
queryParams.put("nsrsbh", nsrsbh);
queryParams.put("fphm", fphm);
queryParams.put("username", username);
queryParams.put("sqyy", "2");
if (kprq != null && !kprq.isEmpty()) {
queryParams.put("kprq", kprq);
}
/*
* 1. 数电申请红字前查蓝票信息接口
* @link https://fa-piao.com/doc.html#api8?source=github
*/
ApiResponse queryResponse = postRequest("/v5/enterprise/retMsg", queryParams, token, appKey, appSecret);
if (queryResponse.getCode() != 200) {
System.out.println(queryResponse.getCode() + " 查询蓝票失败:" + queryResponse.getMsg());
System.out.println(queryResponse.getBody());
return;
}
System.out.println("1 可以申请红字");
Map<String, Object> applyParams = new LinkedHashMap<>();
applyParams.put("xhdwsbh", nsrsbh);
applyParams.put("yfphm", fphm);
applyParams.put("username", username);
applyParams.put("sqyy", "2");
applyParams.put("chyydm", "01");
/*
* 2. 申请红字信息表
* @link https://fa-piao.com/doc.html#api9?source=github
*/
ApiResponse applyResponse = postRequest("/v5/enterprise/hzxxbsq", applyParams, token, appKey, appSecret);
if (applyResponse.getCode() != 200) {
System.out.println(applyResponse.getCode() + " 申请红字信息表失败:" + applyResponse.getMsg());
System.out.println(applyResponse.getBody());
return;
}
String xxbbh = applyResponse.getDataString("xxbbh");
if (xxbbh == null || xxbbh.isEmpty()) {
System.out.println("红字信息表缺少字段: xxbbh");
System.out.println(applyResponse.getBody());
return;
}
System.out.println("2 申请红字信息表成功");
Map<String, Object> redParams = new LinkedHashMap<>();
redParams.put("fpqqlsh", "red" + fphm);
redParams.put("username", username);
redParams.put("xhdwsbh", nsrsbh);
redParams.put("tzdbh", xxbbh);
redParams.put("yfphm", fphm);
/*
* 3. 开具红字发票
* @link https://fa-piao.com/doc.html#api10?source=github
*/
ApiResponse redResponse = postRequest("/v5/enterprise/hzfpkj", redParams, token, appKey, appSecret);
if (redResponse.getCode() == 200) {
System.out.println("3 负数开具成功");
} else {
System.out.println(redResponse.getCode() + " 数电票负数开具失败:" + redResponse.getMsg());
System.out.println(redResponse.getBody());
}
} catch (Exception e) {
System.out.println("请求异常:" + e.getMessage());
e.printStackTrace();
}
}
/**
* post 请求
*/
public static ApiResponse postRequest(String path,Map<String, Object> formData, String token, String appKey, String appSecret) throws Exception {
String randomString = generateRandomString(20);
String timestamp = String.valueOf(Instant.now().getEpochSecond());
String signature = calculateSignature("POST", path, randomString, timestamp,appKey,appSecret);
Map<String, String> headers = new LinkedHashMap<>();
headers.put("AppKey", appKey);
headers.put("Sign", signature);
headers.put("TimeStamp", timestamp);
headers.put("RandomString", randomString);
if (token != null && !token.isEmpty()) {
headers.put("Authorization", "Bearer " + token);
}
return postMultipart(path, headers, formData);
}
/**
* 发送POST multipart/form-data请求
*/
public static ApiResponse postMultipart(String path, Map<String, String> headers, Map<String, Object> formData)
throws IOException {
String boundary = "----JavaFormBoundary" + generateRandomString(24);
byte[] body = buildMultipartBody(formData, boundary);
String urlString = BASE_URL + path;
HttpURLConnection connection = openConnection(urlString, "POST", headers);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
connection.setRequestProperty("Content-Length", String.valueOf(body.length));
connection.getOutputStream().write(body);
connection.getOutputStream().flush();
connection.getOutputStream().close();
return readResponse(connection);
}
/**
* 生成随机字符串
*/
private static String generateRandomString(int length) {
SecureRandom random = new SecureRandom();
String chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
StringBuilder sb = new StringBuilder();
for(int i=0; i<length; i++) {
int index = random.nextInt(chars.length());
sb.append(chars.charAt(index));
}
return sb.toString();
}
/**
* 计算签名
*/
private static String calculateSignature(String method, String path,
String randomString, String timestamp,
String appKey, String appSecret)
throws Exception {
String content = String.format(
"Method=%s&Path=%s&RandomString=%s&TimeStamp=%s&AppKey=%s",
method, path, randomString, timestamp, appKey
);
Mac sha256 = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec(appSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
sha256.init(secretKey);
byte[] hash = sha256.doFinal(content.getBytes(StandardCharsets.UTF_8));
return bytesToHex(hash).toUpperCase();
}
/**
* 字节转十六进制字符串
*/
private static String bytesToHex(byte[] hash) {
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
public static class ApiResponse {
private final int statusCode;
private final String body;
private final Map<String, List<String>> headers;
private final Object json;
public ApiResponse(int statusCode, String body, Map<String, List<String>> headers) {
this.statusCode = statusCode;
this.body = body;
this.headers = headers;
this.json = parseJson(body);
}
public int getStatusCode() {
return statusCode;
}
public String getBody() {
return body;
}
public Map<String, List<String>> getHeaders() {
return headers;
}
public boolean isJson() {
return json != null;
}
public int getCode() {
Object value = getJsonValue("code");
if (value instanceof Number) {
return ((Number) value).intValue();
}
return 0;
}
public String getMsg() {
Object value = getJsonValue("msg");
if (value == null) {
value = getJsonValue("message");
}
return value == null ? null : String.valueOf(value);
}
public Object getData() {
return getJsonValue("data");
}
public Object getDataValue(String key) {
Object data = getData();
if (!(data instanceof Map)) {
return null;
}
return ((Map<?, ?>) data).get(key);
}
public String getDataString(String key) {
Object value = getDataValue(key);
return value == null ? null : String.valueOf(value);
}
public String getDataAsString() {
Object data = getData();
if (data == null) {
return null;
}
if (data instanceof String || data instanceof Number || data instanceof Boolean) {
return String.valueOf(data);
}
return null;
}
public String getTokenString () {
Object data = getData();
if (data instanceof Map) {
Object token = ((Map<?, ?>) data).get("token");
return token == null ? "" : String.valueOf(token);
}
return "";
}
public Object getJson() {
return json;
}
private Object getJsonValue(String key) {
if (!(json instanceof Map)) {
return null;
}
return ((Map<?, ?>) json).get(key);
}
private static Object parseJson(String text) {
if (text == null) {
return null;
}
String trimmed = text.trim();
if (trimmed.isEmpty()) {
return null;
}
if (trimmed.charAt(0) != '{' && trimmed.charAt(0) != '[') {
return null;
}
try {
return new JsonParser(trimmed).parse();
} catch (Exception e) {
return null;
}
}
}
private static class JsonParser {
private final String text;
private int index;
JsonParser(String text) {
this.text = text;
this.index = 0;
}
Object parse() {
skipWhitespace();
Object value = parseValue();
skipWhitespace();
return value;
}
private Object parseValue() {
skipWhitespace();
if (index >= text.length()) {
return null;
}
char c = text.charAt(index);
if (c == '{') {
return parseObject();
}
if (c == '[') {
return parseArray();
}
if (c == '"') {
return parseString();
}
if (c == 't' || c == 'f' || c == 'n') {
return parseLiteral();
}
return parseNumber();
}
private Map<String, Object> parseObject() {
Map<String, Object> map = new LinkedHashMap<>();
index++;
skipWhitespace();
if (peek('}')) {
index++;
return map;
}
while (index < text.length()) {
skipWhitespace();
String key = parseString();
skipWhitespace();
expect(':');
Object value = parseValue();
map.put(key, value);
skipWhitespace();
if (peek(',')) {
index++;
continue;
}
if (peek('}')) {
index++;
break;
}
}
return map;
}
private List<Object> parseArray() {
List<Object> list = new java.util.ArrayList<>();
index++;
skipWhitespace();
if (peek(']')) {
index++;
return list;
}
while (index < text.length()) {
Object value = parseValue();
list.add(value);
skipWhitespace();
if (peek(',')) {
index++;
continue;
}
if (peek(']')) {
index++;
break;
}
}
return list;
}
private String parseString() {
expect('"');
StringBuilder sb = new StringBuilder();
while (index < text.length()) {
char c = text.charAt(index++);
if (c == '"') {
break;
}
if (c == '\\') {
if (index >= text.length()) {
break;
}
char esc = text.charAt(index++);
switch (esc) {
case '"':
sb.append('"');
break;
case '\\':
sb.append('\\');
break;
case '/':
sb.append('/');
break;
case 'b':
sb.append('\b');
break;
case 'f':
sb.append('\f');
break;
case 'n':
sb.append('\n');
break;
case 'r':
sb.append('\r');
break;
case 't':
sb.append('\t');
break;
case 'u':
sb.append(parseUnicode());
break;
default:
sb.append(esc);
break;
}
} else {
sb.append(c);
}
}
return sb.toString();
}
private char parseUnicode() {
if (index + 4 > text.length()) {
return '?';
}
String hex = text.substring(index, index + 4);
index += 4;
try {
return (char) Integer.parseInt(hex, 16);
} catch (Exception e) {
return '?';
}
}
private Object parseLiteral() {
if (text.startsWith("true", index)) {
index += 4;
return Boolean.TRUE;
}
if (text.startsWith("false", index)) {
index += 5;
return Boolean.FALSE;
}
if (text.startsWith("null", index)) {
index += 4;
return null;
}
return null;
}
private Number parseNumber() {
int start = index;
boolean dot = false;
boolean exp = false;
if (peek('-')) {
index++;
}
while (index < text.length()) {
char c = text.charAt(index);
if (c >= '0' && c <= '9') {
index++;
continue;
}
if (c == '.' && !dot) {
dot = true;
index++;
continue;
}
if ((c == 'e' || c == 'E') && !exp) {
exp = true;
index++;
if (peek('+') || peek('-')) {
index++;
}
continue;
}
break;
}
String num = text.substring(start, index);
try {
if (dot || exp) {
return Double.parseDouble(num);
}
return Long.parseLong(num);
} catch (Exception e) {
return 0;
}
}
private void skipWhitespace() {
while (index < text.length()) {
char c = text.charAt(index);
if (c == ' ' || c == '\n' || c == '\r' || c == '\t') {
index++;
continue;
}
break;
}
}
private void expect(char c) {
if (index < text.length() && text.charAt(index) == c) {
index++;
}
}
private boolean peek(char c) {
return index < text.length() && text.charAt(index) == c;
}
}
/**
* 构建multipart/form-data请求体
*/
private static byte[] buildMultipartBody(Map<String, Object> data, String boundary) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
for (Map.Entry<String, Object> entry : data.entrySet()) {
writeString(out, "--" + boundary + "\r\n");
writeString(out, "Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
Object value = entry.getValue();
writeString(out, value == null ? "" : String.valueOf(value));
writeString(out, "\r\n");
}
writeString(out, "--" + boundary + "--\r\n");
return out.toByteArray();
}
/**
* 创建并初始化HTTP连接
*/
private static HttpURLConnection openConnection(String urlString, String method, Map<String, String> headers)
throws IOException {
HttpURLConnection connection = (HttpURLConnection) new URL(urlString).openConnection();
connection.setRequestMethod(method);
connection.setUseCaches(false);
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
return connection;
}
/**
* 读取HTTP响应内容
*/
private static ApiResponse readResponse(HttpURLConnection connection) throws IOException {
int statusCode = connection.getResponseCode();
byte[] bytes;
if (statusCode >= 200 && statusCode < 400) {
bytes = readAllBytes(connection.getInputStream());
} else {
bytes = readAllBytes(connection.getErrorStream());
}
String body = bytes == null ? "" : new String(bytes, StandardCharsets.UTF_8);
return new ApiResponse(statusCode, body, connection.getHeaderFields());
}
/**
* 读取输入流为字节数组
*/
private static byte[] readAllBytes(java.io.InputStream in) throws IOException {
if (in == null) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
in.close();
return out.toByteArray();
}
/**
* 按UTF-8写入字符串
*/
private static void writeString(ByteArrayOutputStream out, String value) throws IOException {
out.write(value.getBytes(StandardCharsets.UTF_8));
}
}