import java.io.IOException; import java.net.URI; import java.net.URLEncoder; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.time.Duration; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.StringJoiner; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; /** * 优时开放平台 · API 客户端示例(Java 11+,只用 JDK 自带的 java.net.http,单文件、无第三方依赖) * *
 * 签名串:METHOD + "\n" + path + "\n" + X-Timestamp + "\n" + X-Nonce + "\n" + sha256_hex(body)
 * 签名:  X-Sign = lower_hex(HMAC-SHA256(sign_key, 签名串))
 *   - path:实际发出的 URL 路径(保持 URL 编码原样),不含域名和查询参数,例如 /v1/tickets
 *   - body:实际发出的请求体原始字节;没有请求体时为空
 *   - X-Timestamp:秒级时间戳,与服务器相差不能超过 300 秒
 *   - X-Nonce:16~64 位的字母、数字、下划线或短横线,10 分钟内不能重复
 *
 * 用法(JDK 11+ 可以直接运行源文件):
 *   OPEN_BASE_URL=https://open-api.yours.xyz OPEN_APPID=op_xxx OPEN_SECRET=xxx OPEN_SIGN_KEY=xxx java YoursOpenClient.java
 *   java YoursOpenClient.java sign <sign_key> <method> <path> <timestamp> <nonce> <body_file>   # 只计算签名(自检)
 * 
* * 为了不引入依赖,文件末尾带了一个极简 JSON 编解码({@link Json});正式项目里请换成 Jackson / Gson 等, * 但要注意:签名用的 body 必须是最终发送的那份字节。 */ public class YoursOpenClient { /** token 到期前多少秒就重新获取 */ private static final long TOKEN_REFRESH_MARGIN = 300; /** token 无效或过期 */ private static final long CODE_TOKEN_INVALID = 40102; private static final SecureRandom RANDOM = new SecureRandom(); private final String baseUrl; private final String appid; private final String secret; private final String signKey; private final Duration timeout; private final HttpClient http; private String token = ""; private long tokenExpiresAt = 0; /** * @param baseUrl 只写协议和域名(可带端口),不要带 /v1,例如 https://open-api.yours.xyz */ public YoursOpenClient(String baseUrl, String appid, String secret, String signKey) { this.baseUrl = baseUrl.replaceAll("/+$", ""); this.appid = appid; this.secret = secret; this.signKey = signKey; this.timeout = Duration.ofSeconds(10); // 固定 HTTP/1.1:明文 http 下 HTTP/2 会先发 h2c 升级请求 this.http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).connectTimeout(timeout).build(); } /** 计算请求签名(纯函数,不读取时钟和随机数,方便和服务端对照) */ public static String sign(String signKey, String method, String path, String timestamp, String nonce, byte[] body) { try { String bodyHash = hex(MessageDigest.getInstance("SHA-256").digest(body)); String stringToSign = String.join("\n", method.toUpperCase(Locale.ROOT), path, timestamp, nonce, bodyHash); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(signKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); return hex(mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8))); } catch (NoSuchAlgorithmException | java.security.InvalidKeyException e) { throw new IllegalStateException(e); } } /** 获取 access_token。有效期内复用;每天获取次数有限,生产环境请在多个进程之间共享缓存。 */ public synchronized String token(boolean forceRefresh) throws IOException, InterruptedException { long now = System.currentTimeMillis() / 1000; if (!forceRefresh && !token.isEmpty() && now < tokenExpiresAt) { return token; } Map payload = new LinkedHashMap<>(); payload.put("appid", appid); payload.put("secret", secret); payload.put("grant_type", "client_credential"); Map res = send("POST", baseUrl + "/oauth/token", Json.encode(payload).getBytes(StandardCharsets.UTF_8), Map.of("Content-Type", "application/json")); if (code(res) != 0) { throw new IOException(describeError("获取 token 失败", res)); } Map data = asMap(res.get("data")); token = (String) data.get("access_token"); tokenExpiresAt = now + Math.max(0, ((Number) data.get("expires_in")).longValue() - TOKEN_REFRESH_MARGIN); return token; } /** * 调用开放接口,返回解析后的响应 {code, msg, data, request_id}(业务错误不抛异常,由调用方判断 code)。 * * @param path 以 / 开头、已经 URL 编码的路径,例如 /v1/tickets;查询参数放在 query 里(不参与签名) * @param query 查询参数,可为 null * @param body 请求体(Map / List / String / Number / Boolean),会编码成 JSON;null 表示不带请求体 */ public Map request(String method, String path, Map query, Object body) throws IOException, InterruptedException { return request(method, path, query, body, true); } /** @param signed 是否签名。写接口(*.write)必须签名;读接口签了也没有影响 */ public Map request(String method, String path, Map query, Object body, boolean signed) throws IOException, InterruptedException { if (!path.startsWith("/") || path.contains("?") || path.contains("#")) { throw new IllegalArgumentException("path 必须以 / 开头,且不能包含查询参数"); } String httpMethod = method.toUpperCase(Locale.ROOT); if (body != null && (httpMethod.equals("GET") || httpMethod.equals("HEAD"))) { throw new IllegalArgumentException("GET / HEAD 请求不能带请求体(签名包含请求体,但不会被发送)"); } byte[] raw = body == null ? new byte[0] : Json.encode(body).getBytes(StandardCharsets.UTF_8); String url = baseUrl + path + queryString(query); Map res = sendApi(httpMethod, path, url, raw, signed, false); if (code(res) == CODE_TOKEN_INVALID) { // token 被吊销或过期:重新获取一次再试(每次请求都会生成新的 nonce) res = sendApi(httpMethod, path, url, raw, signed, true); } return res; } private Map sendApi(String method, String path, String url, byte[] raw, boolean signed, boolean refreshToken) throws IOException, InterruptedException { Map headers = new LinkedHashMap<>(); headers.put("Authorization", "Bearer " + token(refreshToken)); if (raw.length > 0) { headers.put("Content-Type", "application/json"); } if (signed) { String timestamp = String.valueOf(System.currentTimeMillis() / 1000); byte[] nonceBytes = new byte[16]; RANDOM.nextBytes(nonceBytes); String nonce = hex(nonceBytes); headers.put("X-Timestamp", timestamp); headers.put("X-Nonce", nonce); // 签的必须是下面实际发送的 raw,不能重新编码一次 headers.put("X-Sign", sign(signKey, method, path, timestamp, nonce, raw)); } return send(method, url, raw, headers); } private Map send(String method, String url, byte[] body, Map headers) throws IOException, InterruptedException { boolean noBody = method.equals("GET") || method.equals("HEAD"); HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(url)).timeout(timeout) .method(method, noBody ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofByteArray(body)); headers.forEach(builder::header); HttpResponse resp = http.send(builder.build(), HttpResponse.BodyHandlers.ofByteArray()); Object parsed; try { parsed = Json.decode(new String(resp.body(), StandardCharsets.UTF_8)); } catch (RuntimeException e) { // 非 JSON(例如网关返回的 HTML 错误页) parsed = null; } if (!(parsed instanceof Map) || !((Map) parsed).containsKey("code")) { throw new IOException("响应不是开放平台格式(HTTP " + resp.statusCode() + ")"); } return asMap(parsed); } private static String queryString(Map query) { if (query == null || query.isEmpty()) { return ""; } StringJoiner joiner = new StringJoiner("&", "?", ""); query.forEach((k, v) -> joiner.add(urlEncode(k) + "=" + urlEncode(v))); return joiner.toString(); } private static String urlEncode(String value) { return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20"); } static long code(Map res) { Object code = res.get("code"); return code instanceof Number ? ((Number) code).longValue() : -1; } static String describeError(String title, Map res) { return title + ":code=" + res.getOrDefault("code", "-") + " msg=" + res.getOrDefault("msg", "-") + " request_id=" + res.getOrDefault("request_id", "-"); } @SuppressWarnings("unchecked") static Map asMap(Object value) { return (Map) value; } private static String hex(byte[] bytes) { StringBuilder sb = new StringBuilder(bytes.length * 2); for (byte b : bytes) { sb.append(String.format("%02x", b)); } return sb.toString(); } /** 演示:获取 token → 查询门店 → 现场取号。需要应用拥有 store.read 和 ticket.write 权限 */ static int demo() { Map config = new LinkedHashMap<>(); for (String name : List.of("OPEN_BASE_URL", "OPEN_APPID", "OPEN_SECRET", "OPEN_SIGN_KEY")) { String value = System.getenv(name); if (value == null || value.isEmpty()) { System.err.println("请设置环境变量 " + name); return 2; } config.put(name, value); } YoursOpenClient client = new YoursOpenClient(config.get("OPEN_BASE_URL"), config.get("OPEN_APPID"), config.get("OPEN_SECRET"), config.get("OPEN_SIGN_KEY")); try { client.token(false); System.out.println("获取 token 成功"); Map stores = client.request("GET", "/v1/stores", null, null); List items = code(stores) == 0 ? (List) asMap(stores.get("data")).get("items") : List.of(); if (items.isEmpty()) { System.err.println(describeError("查询门店失败", stores)); return 1; } Map store = asMap(items.get(0)); System.out.println("门店:store_id=" + store.get("store_id") + " name=" + store.get("name")); // out_ticket_no 是你自己的单号(幂等键):超时重试时必须使用同一个单号 byte[] suffix = new byte[3]; RANDOM.nextBytes(suffix); String outTicketNo = "DEMO" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + hex(suffix); Map user = new LinkedHashMap<>(); user.put("open_user_id", "demo_user_1"); user.put("mobile", "13800000000"); user.put("name", "张三"); Map body = new LinkedHashMap<>(); body.put("out_ticket_no", outTicketNo); body.put("store_id", store.get("store_id")); body.put("user", user); Map ticket = client.request("POST", "/v1/tickets", null, body); if (code(ticket) != 0) { System.err.println(describeError("取号失败", ticket)); return 1; } Map d = asMap(ticket.get("data")); System.out.println("取号成功:ticket_id=" + d.get("ticket_id") + " number=" + d.get("number") + " status=" + d.get("status") + " ahead_count=" + d.get("ahead_count")); return 0; } catch (IOException | RuntimeException e) { System.err.println("请求失败:" + e.getMessage()); return 1; } catch (InterruptedException e) { Thread.currentThread().interrupt(); return 1; } } public static void main(String[] args) throws IOException { if (args.length > 0 && args[0].equals("sign")) { if (args.length != 7) { System.err.println("用法:java YoursOpenClient.java sign "); System.exit(2); } byte[] body = Files.readAllBytes(Paths.get(args[6])); // 传 - 时从环境变量读取,避免 sign_key 出现在 shell 历史和进程列表里 String key = args[1].equals("-") ? System.getenv("OPEN_SIGN_KEY") : args[1]; System.out.println(sign(key, args[2], args[3], args[4], args[5], body)); System.exit(0); } System.exit(demo()); } /** 极简 JSON 编解码:只为让示例不依赖第三方库。数字解析为 Long 或 Double,对象保持字段顺序。 */ static final class Json { private final String s; private int pos; private Json(String s) { this.s = s; } static String encode(Object value) { StringBuilder sb = new StringBuilder(); write(sb, value); return sb.toString(); } static Object decode(String text) { Json parser = new Json(text); Object value = parser.readValue(); parser.skipSpace(); if (parser.pos != text.length()) { throw new IllegalArgumentException("JSON 末尾有多余内容"); } return value; } private static void write(StringBuilder sb, Object value) { if (value == null) { sb.append("null"); } else if (value instanceof String) { writeString(sb, (String) value); } else if (value instanceof Number || value instanceof Boolean) { sb.append(value); } else if (value instanceof Map) { sb.append('{'); boolean first = true; for (Map.Entry e : ((Map) value).entrySet()) { if (!first) { sb.append(','); } first = false; writeString(sb, String.valueOf(e.getKey())); sb.append(':'); write(sb, e.getValue()); } sb.append('}'); } else if (value instanceof List) { sb.append('['); boolean first = true; for (Object item : (List) value) { if (!first) { sb.append(','); } first = false; write(sb, item); } sb.append(']'); } else { throw new IllegalArgumentException("不支持的 JSON 类型:" + value.getClass()); } } private static void writeString(StringBuilder sb, String str) { sb.append('"'); for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); switch (c) { case '"': sb.append("\\\""); break; case '\\': sb.append("\\\\"); break; case '\n': sb.append("\\n"); break; case '\r': sb.append("\\r"); break; case '\t': sb.append("\\t"); break; default: if (c < 0x20) { sb.append(String.format("\\u%04x", (int) c)); } else { sb.append(c); // 中文等字符原样输出,按 UTF-8 发送 } } } sb.append('"'); } private Object readValue() { skipSpace(); if (pos >= s.length()) { throw new IllegalArgumentException("JSON 意外结束"); } char c = s.charAt(pos); if (c == '{') { return readObject(); } else if (c == '[') { return readArray(); } else if (c == '"') { return readString(); } else if (s.startsWith("true", pos)) { pos += 4; return Boolean.TRUE; } else if (s.startsWith("false", pos)) { pos += 5; return Boolean.FALSE; } else if (s.startsWith("null", pos)) { pos += 4; return null; } return readNumber(); } private Map readObject() { Map map = new LinkedHashMap<>(); pos++; // { skipSpace(); if (peek() == '}') { pos++; return map; } while (true) { skipSpace(); String key = readString(); skipSpace(); expect(':'); map.put(key, readValue()); skipSpace(); if (peek() == ',') { pos++; } else { expect('}'); return map; } } } private List readArray() { List list = new ArrayList<>(); pos++; // [ skipSpace(); if (peek() == ']') { pos++; return list; } while (true) { list.add(readValue()); skipSpace(); if (peek() == ',') { pos++; } else { expect(']'); return list; } } } private String readString() { expect('"'); StringBuilder sb = new StringBuilder(); while (pos < s.length()) { char c = s.charAt(pos++); if (c == '"') { return sb.toString(); } if (c != '\\') { sb.append(c); continue; } char e = s.charAt(pos++); switch (e) { 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((char) Integer.parseInt(s.substring(pos, pos + 4), 16)); pos += 4; break; default: sb.append(e); // " \ / } } throw new IllegalArgumentException("JSON 字符串未结束"); } private Object readNumber() { int start = pos; while (pos < s.length() && "+-0123456789.eE".indexOf(s.charAt(pos)) >= 0) { pos++; } String num = s.substring(start, pos); if (num.isEmpty()) { throw new IllegalArgumentException("无效的 JSON(位置 " + start + ")"); } try { return num.matches("-?\\d+") ? (Object) Long.parseLong(num) : (Object) Double.parseDouble(num); } catch (NumberFormatException e) { throw new IllegalArgumentException("无效的数字:" + num); } } private void skipSpace() { while (pos < s.length() && Character.isWhitespace(s.charAt(pos))) { pos++; } } private char peek() { if (pos >= s.length()) { throw new IllegalArgumentException("JSON 意外结束"); } return s.charAt(pos); } private void expect(char c) { if (peek() != c) { throw new IllegalArgumentException("JSON 位置 " + pos + " 应为 " + c); } pos++; } } }