Mock361YXSDK.java 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. package com.ljsd.channel;
  2. import com.google.gson.Gson;
  3. import com.google.gson.JsonObject;
  4. import com.google.gson.JsonParser;
  5. import com.ljsd.util.BaseGlobal;
  6. import com.ljsd.util.TimeUtil;
  7. import com.ljsd.util.XmlParser;
  8. import com.mongodb.BasicDBObject;
  9. import com.mongodb.DBObject;
  10. import org.apache.http.HttpEntity;
  11. import org.apache.http.NameValuePair;
  12. import org.apache.http.client.entity.UrlEncodedFormEntity;
  13. import org.apache.http.client.methods.CloseableHttpResponse;
  14. import org.apache.http.client.methods.HttpGet;
  15. import org.apache.http.client.methods.HttpPost;
  16. import org.apache.http.client.utils.URIBuilder;
  17. import org.apache.http.impl.client.CloseableHttpClient;
  18. import org.apache.http.impl.client.HttpClients;
  19. import org.apache.http.message.BasicNameValuePair;
  20. import org.apache.http.util.EntityUtils;
  21. import org.slf4j.Logger;
  22. import org.slf4j.LoggerFactory;
  23. import javax.servlet.http.HttpServletRequest;
  24. import java.io.UnsupportedEncodingException;
  25. import java.net.URLEncoder;
  26. import java.nio.charset.StandardCharsets;
  27. import java.security.MessageDigest;
  28. import java.security.NoSuchAlgorithmException;
  29. import java.util.ArrayList;
  30. import java.util.HashMap;
  31. import java.util.List;
  32. import java.util.Map;
  33. import java.util.stream.Collectors;
  34. public class Mock361YXSDK {
  35. private static final Logger LOGGER = LoggerFactory.getLogger(Mock361YXSDK.class);
  36. private static final String APP_ID="39bee2c821834c32";
  37. private static final String LOGIN_KEY="3dc60d6756c04f4ca23c6addba1e400e";
  38. private static final String PAY_KEY="befa74b8ed734b01afb34b64f56c8cc2";
  39. private static final String VERIFY_API_URL="http://sdk.361yx.com/tools/gamefactor.ashx?action=factor_login";
  40. private static final CloseableHttpClient httpClient = HttpClients.createDefault();
  41. private final static String _COLLECTION_PAY = "pay";
  42. private static final Gson GSON = new Gson();
  43. public static boolean verifyUser(String uid) {
  44. try {
  45. Map<String, String> params = new HashMap<>();
  46. params.put("app_id",APP_ID);
  47. params.put("uid",uid);
  48. params.put("timestamp",String.valueOf(TimeUtil.getTimeNow()));
  49. params.put("pay_key", PAY_KEY);
  50. // 构建排序后的查询字符串
  51. String sortedQuery = buildSortedQuery(params);
  52. LOGGER.info("排序后的查询字符串:{}", sortedQuery);
  53. String sign = md5(sortedQuery);
  54. // 域名+/tools/gamefactor.ashx?action=factor_login
  55. List<NameValuePair> formParams = new ArrayList<>();
  56. formParams.add(new BasicNameValuePair("app_id", APP_ID)); // app_id 参数
  57. formParams.add(new BasicNameValuePair("uid", uid)); // uid 参数
  58. formParams.add(new BasicNameValuePair("timestamp", params.get("timestamp"))); // timestamp 参数
  59. formParams.add(new BasicNameValuePair("sign", sign));
  60. HttpPost httpPost = new HttpPost(VERIFY_API_URL);
  61. UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8);
  62. httpPost.setEntity(formEntity);
  63. CloseableHttpResponse response = httpClient.execute(httpPost);
  64. String responseStr = EntityUtils.toString(response.getEntity(), "UTF-8");
  65. JsonObject jsonObject = GSON.fromJson(responseStr, JsonObject.class);
  66. int status = jsonObject.get("status").getAsInt();
  67. String realname = jsonObject.has("realname") ? jsonObject.get("realname").getAsString() : null;
  68. String idcard = jsonObject.has("idcard") ? jsonObject.get("idcard").getAsString() : null;
  69. String msg = jsonObject.has("msg") ? jsonObject.get("msg").getAsString() : null;
  70. response.close();
  71. if (status == 1) {
  72. LOGGER.info("验证成功!真实姓名:{},身份证号:{}", realname, idcard);
  73. return true;
  74. } else {
  75. LOGGER.error("验证失败,原因:{}", msg);
  76. return false;
  77. }
  78. } catch (Exception e) {
  79. e.printStackTrace();
  80. LOGGER.error("361yx 验证异常:", e);
  81. return false;
  82. }
  83. }
  84. public static String md5(String input) throws NoSuchAlgorithmException {
  85. MessageDigest md = MessageDigest.getInstance("MD5");
  86. byte[] hashBytes = md.digest(input.getBytes(StandardCharsets.UTF_8));
  87. StringBuilder hexString = new StringBuilder();
  88. for (byte b : hashBytes) {
  89. String hex = Integer.toHexString(0xFF & b);
  90. if (hex.length() == 1) {
  91. hexString.append('0'); // 补前导零(如 0x0A → "0a")
  92. }
  93. hexString.append(hex);
  94. }
  95. return hexString.toString();
  96. }
  97. public static boolean verifyCallback(HttpServletRequest request) throws NoSuchAlgorithmException {
  98. String appId = request.getParameter("app_id");
  99. String cpOrderId = request.getParameter("cp_order_id");
  100. String orderAmount = request.getParameter("order_amount");
  101. String orderId = request.getParameter("order_id");
  102. String roleId = request.getParameter("role_id");
  103. String serverId = request.getParameter("server_id");
  104. String timestamp = request.getParameter("timestamp");
  105. String uid = request.getParameter("uid");
  106. String sign = request.getParameter("sign");
  107. Map<String, String> params = new HashMap<>();
  108. params.put("app_id",appId);
  109. params.put("cp_order_id",cpOrderId);
  110. params.put("order_amount",orderAmount);
  111. params.put("order_id", orderId);
  112. params.put("role_id", roleId);
  113. params.put("server_id", serverId);
  114. params.put("timestamp", timestamp);
  115. params.put("uid", uid);
  116. params.put("pay_key", PAY_KEY); // 包含特殊字符
  117. // 构建排序后的查询字符串
  118. String sortedQuery = buildSortedQuery(params);
  119. LOGGER.info("排序后的查询字符串:{}", sortedQuery);
  120. String signCheck = md5(sortedQuery);
  121. return signCheck.equals(sign);
  122. }
  123. public static String buildSortedQuery(Map<String, String> params) {
  124. // 1. 分离 pay_key 和其他参数(其他参数需非空)
  125. Map<String, String> otherParams = new HashMap<>();
  126. String payKeyValue = params.get("pay_key");
  127. // 过滤其他参数(非 pay_key 且值非空)
  128. for (Map.Entry<String, String> entry : params.entrySet()) {
  129. String key = entry.getKey();
  130. String value = entry.getValue();
  131. if (!"pay_key".equals(key) && value != null && !value.trim().isEmpty()) {
  132. otherParams.put(key, value);
  133. }
  134. }
  135. // 2. 对其他参数按键的 ASCII 字典序排序
  136. List<String> sortedOtherKeys = otherParams.keySet().stream()
  137. .sorted() // 按 String 自然顺序(ASCII 字典序)排序
  138. .collect(Collectors.toList());
  139. // 3. 拼接其他参数(已排序)
  140. StringBuilder otherParamsStr = new StringBuilder();
  141. for (String key : sortedOtherKeys) {
  142. String value = otherParams.get(key);
  143. try {
  144. String encodedValue = URLEncoder.encode(value, StandardCharsets.UTF_8.name());
  145. otherParamsStr.append(key).append("=").append(encodedValue).append("&");
  146. } catch (UnsupportedEncodingException e) {
  147. // 理论上不会触发,此处处理异常
  148. otherParamsStr.append(key).append("=").append(value).append("&");
  149. }
  150. }
  151. // 移除末尾多余的 &
  152. if (otherParamsStr.length() > 0) {
  153. otherParamsStr.deleteCharAt(otherParamsStr.length() - 1);
  154. }
  155. // 4. 拼接 pay_key(始终在最后)
  156. StringBuilder finalQuery = new StringBuilder(otherParamsStr); // 初始化为其他参数的拼接结果
  157. // 拼接 pay_key(如果有值)
  158. if (payKeyValue != null && !payKeyValue.trim().isEmpty()) {
  159. try {
  160. String encodedPayKey = URLEncoder.encode(payKeyValue, StandardCharsets.UTF_8.name());
  161. if (finalQuery.length() > 0) {
  162. finalQuery.append("&").append("pay_key=").append(encodedPayKey);
  163. } else {
  164. finalQuery.append("pay_key=").append(encodedPayKey);
  165. }
  166. } catch (UnsupportedEncodingException e) {
  167. if (finalQuery.length() > 0) {
  168. finalQuery.append("&").append("pay_key=").append(payKeyValue);
  169. } else {
  170. finalQuery.append("pay_key=").append(payKeyValue);
  171. }
  172. }
  173. }
  174. return finalQuery.toString();
  175. }
  176. public static DBObject saveDB(HttpServletRequest request) throws Exception {
  177. LOGGER.info("request = {}", request);
  178. String orderId = request.getParameter("cp_order_id");
  179. DBObject payInfo = new BasicDBObject();
  180. payInfo.put("cporderId", orderId);
  181. List<DBObject> payInfoList = BaseGlobal.getInstance().mongoDBPool.find(_COLLECTION_PAY, payInfo);
  182. if (payInfoList.size() != 1) {
  183. return null;
  184. }
  185. payInfo.put("billno", request.getParameter("order_id"));
  186. payInfo.put("uid", request.getParameter("role_id"));
  187. payInfo.put("openId", request.getParameter("open_id"));
  188. payInfo.put("region", request.getParameter("server_id"));
  189. payInfo.put("channel", "361yx");
  190. // payInfo.put("gameorderId", request.getParameter("game_order"));
  191. // dbObject.put("cporderId", platform);
  192. payInfo.put("creattime",request.getParameter("pay_time"));
  193. payInfo.put("callbaktime", TimeUtil.getTimeNow());
  194. BaseGlobal.getInstance().mongoDBPool.save(_COLLECTION_PAY, payInfo);
  195. return payInfo;
  196. }
  197. private static String generateSign(String appId, String appSecret, String userId) {
  198. String raw = appId + appSecret + userId;
  199. return raw.hashCode() + "";
  200. }
  201. }