一起源码网

  • www.171739.xyz
  • 全球最大的互联网技术和资源下载平台
搜索
一起源码网 门户 高级进阶 查看主题

微信小程序支付(java后端)

发布者: 2000redfox | 发布时间: 2018-5-8 19:26| 查看数: 9480| 评论数: 1|帖子模式

作者:苏雄伟,来自原文地址

第一步

进入小程序,下单,请求下单支付,调用小程序登录API来获取Openid(https://mp.weixin.qq.com/debug/wxadoc/dev/api/api-login.html#wxloginobject),生成商户订单,这些都是在小程序端完成的业务。

小程序端代码

  1. // pages/pay/pay.js
  2. var app = getApp();
  3. Page({
  4. data: {},
  5. onLoad: function (options) {
  6. // 页面初始化 options为页面跳转所带来的参数
  7. },
  8. /* 微信支付 */
  9. wxpay: function () {
  10. var that = this
  11. //登陆获取code
  12. wx.login({
  13. success: function (res) {
  14. console.log(res.code)
  15. //获取openid
  16. that.getOpenId(res.code)
  17. }
  18. });
  19. },
  20. getOpenId: function (code) {
  21. var that = this;
  22. wx.request({
  23. url: "https://api.weixin.qq.com/sns/jscode2session?appid=wxa142513e524e496c&secret=5d6a7d86048884e7c60f84f7aa85253c&js_code=" + code + "&grant_type=authorization_code",
  24. data: {},
  25. method: 'GET',
  26. success: function (res) {
  27. console.log('返回openId')
  28. console.log(res.data)
  29. that.generateOrder(res.data.openid)
  30. },
  31. fail: function () {
  32. // fail
  33. },
  34. complete: function () {
  35. // complete
  36. }
  37. })
  38. },
  39. /**生成商户订单 */
  40. generateOrder: function (openid) {
  41. var that = this
  42. //统一支付
  43. wx.request({
  44. url: 'http://localhost:8070/RMS/pay_pay.action',
  45. method: 'GET',
  46. data: {
  47. total_fee: '5',
  48. body: '支付测试',
  49. attach:'真假酒水'
  50. },
  51. success: function (res) {
  52. console.log(res)
  53. var pay = res.data
  54. //发起支付
  55. var timeStamp = pay[0].timeStamp;
  56. console.log("timeStamp:"+timeStamp)
  57. var packages = pay[0].package;
  58. console.log("package:"+packages)
  59. var paySign = pay[0].paySign;
  60. console.log("paySign:"+paySign)
  61. var nonceStr = pay[0].nonceStr;
  62. console.log("nonceStr:"+nonceStr)
  63. var param = { "timeStamp": timeStamp, "package": packages, "paySign": paySign, "signType": "MD5", "nonceStr": nonceStr };
  64. that.pay(param)
  65. },
  66. })
  67. },
  68. /* 支付 */
  69. pay: function (param) {
  70. console.log("支付")
  71. console.log(param)
  72. wx.requestPayment({
  73. timeStamp: param.timeStamp,
  74. nonceStr: param.nonceStr,
  75. package: param.package,
  76. signType: param.signType,
  77. paySign: param.paySign,
  78. success: function (res) {
  79. // success
  80. console.log("支付")
  81. console.log(res)
  82. wx.navigateBack({
  83. delta: 1, // 回退前 delta(默认为1) 页面
  84. success: function (res) {
  85. wx.showToast({
  86. title: '支付成功',
  87. icon: 'success',
  88. duration: 2000
  89. })
  90. },
  91. fail: function () {
  92. // fail
  93. },
  94. complete: function () {
  95. // complete
  96. }
  97. })
  98. },
  99. fail: function (res) {
  100. // fail
  101. console.log("支付失败")
  102. console.log(res)
  103. },
  104. complete: function () {
  105. // complete
  106. console.log("pay complete")
  107. }
  108. })
  109. }
  110. })

第二步

调用支付统一下单API来获取prepay_id,并将小程序调起支付数据需要签名的字段appId,timeStamp,nonceStr,package再次签名(https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=3

后台代码

  1. package cn.it.shop.action;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.InputStream;
  4. import java.io.UnsupportedEncodingException;
  5. import java.text.SimpleDateFormat;
  6. import java.util.Date;
  7. import java.util.HashMap;
  8. import java.util.List;
  9. import java.util.Map;
  10. import org.dom4j.Document;
  11. import org.dom4j.DocumentException;
  12. import org.dom4j.Element;
  13. import org.dom4j.io.SAXReader;
  14. import cn.it.shop.util.MessageUtil;
  15. import cn.it.shop.util.PayUtil;
  16. import cn.it.shop.util.PaymentPo;
  17. import cn.it.shop.util.UUIDHexGenerator;
  18. import net.sf.json.JSONArray;
  19. import net.sf.json.JSONObject;
  20. /**
  21. * @author
  22. * @version 创建时间:2017年1月21日 下午4:59:03
  23. * 小程序端请求的后台action,返回签名后的数据传到前台
  24. */
  25. public class PayAction {
  26. private String total_fee;//总金额
  27. private String body;//商品描述
  28. private String detail;//商品详情
  29. private String attach;//附加数据
  30. private String time_start;//交易起始时间
  31. private String time_expire;//交易结束时间
  32. private String openid;//用户标识
  33. private JSONArray jsonArray=new JSONArray();
  34. public String pay() throws UnsupportedEncodingException, DocumentException{
  35. body = new String(body.getBytes("UTF-8"),"ISO-8859-1");
  36. String appid = "替换为自己的小程序ID";//小程序ID
  37. String mch_id = "替换为自己的商户号";//商户号
  38. String nonce_str = UUIDHexGenerator.generate();//随机字符串
  39. String today = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
  40. String code = PayUtil.createCode(8);
  41. String out_trade_no = mch_id+today+code;//商户订单号
  42. String spbill_create_ip = "替换为自己的终端IP";//终端IP
  43. String notify_url = "http://www.weixin.qq.com/wxpay/pay.php";//通知地址
  44. String trade_type = "JSAPI";//交易类型
  45. String openid="替换为用户的openid";//用户标识
  46. /**/
  47. PaymentPo paymentPo = new PaymentPo();
  48. paymentPo.setAppid(appid);
  49. paymentPo.setMch_id(mch_id);
  50. paymentPo.setNonce_str(nonce_str);
  51. String newbody=new String(body.getBytes("ISO-8859-1"),"UTF-8");//以utf-8编码放入paymentPo,微信支付要求字符编码统一采用UTF-8字符编码
  52. paymentPo.setBody(newbody);
  53. paymentPo.setOut_trade_no(out_trade_no);
  54. paymentPo.setTotal_fee(total_fee);
  55. paymentPo.setSpbill_create_ip(spbill_create_ip);
  56. paymentPo.setNotify_url(notify_url);
  57. paymentPo.setTrade_type(trade_type);
  58. paymentPo.setOpenid(openid);
  59. // 把请求参数打包成数组
  60. Map<String, String> sParaTemp = new HashMap<String, String>();
  61. sParaTemp.put("appid", paymentPo.getAppid());
  62. sParaTemp.put("mch_id", paymentPo.getMch_id());
  63. sParaTemp.put("nonce_str", paymentPo.getNonce_str());
  64. sParaTemp.put("body", paymentPo.getBody());
  65. sParaTemp.put("out_trade_no", paymentPo.getOut_trade_no());
  66. sParaTemp.put("total_fee",paymentPo.getTotal_fee());
  67. sParaTemp.put("spbill_create_ip", paymentPo.getSpbill_create_ip());
  68. sParaTemp.put("notify_url",paymentPo.getNotify_url());
  69. sParaTemp.put("trade_type", paymentPo.getTrade_type());
  70. sParaTemp.put("openid", paymentPo.getOpenid());
  71. // 除去数组中的空值和签名参数
  72. Map<String, String> sPara = PayUtil.paraFilter(sParaTemp);
  73. String prestr = PayUtil.createLinkString(sPara); // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
  74. String key = "&key=替换为商户支付密钥"; // 商户支付密钥
  75. //MD5运算生成签名
  76. String mysign = PayUtil.sign(prestr, key, "utf-8").toUpperCase();
  77. paymentPo.setSign(mysign);
  78. //打包要发送的xml
  79. String respXml = MessageUtil.messageToXML(paymentPo);
  80. // 打印respXml发现,得到的xml中有“__”不对,应该替换成“_”
  81. respXml = respXml.replace("__", "_");
  82. String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";//统一下单API接口链接
  83. String param = respXml;
  84. //String result = SendRequestForUrl.sendRequest(url, param);//发起请求
  85. String result =PayUtil.httpRequest(url, "POST", param);
  86. // 将解析结果存储在HashMap中
  87. Map<String, String> map = new HashMap<String, String>();
  88. InputStream in=new ByteArrayInputStream(result.getBytes());
  89. // 读取输入流
  90. SAXReader reader = new SAXReader();
  91. Document document = reader.read(in);
  92. // 得到xml根元素
  93. Element root = document.getRootElement();
  94. // 得到根元素的所有子节点
  95. @SuppressWarnings("unchecked")
  96. List<Element> elementList = root.elements();
  97. for (Element element : elementList) {
  98. map.put(element.getName(), element.getText());
  99. }
  100. // 返回信息
  101. String return_code = map.get("return_code");//返回状态码
  102. String return_msg = map.get("return_msg");//返回信息
  103. System.out.println("return_msg"+return_msg);
  104. JSONObject JsonObject=new JSONObject() ;
  105. if(return_code=="SUCCESS"||return_code.equals(return_code)){
  106. // 业务结果
  107. String prepay_id = map.get("prepay_id");//返回的预付单信息
  108. String nonceStr=UUIDHexGenerator.generate();
  109. JsonObject.put("nonceStr", nonceStr);
  110. JsonObject.put("package", "prepay_id="+prepay_id);
  111. Long timeStamp= System.currentTimeMillis()/1000;
  112. JsonObject.put("timeStamp", timeStamp+"");
  113. String stringSignTemp = "appId="+appid+"&nonceStr=" + nonceStr + "&package=prepay_id=" + prepay_id+ "&signType=MD5&timeStamp=" + timeStamp;
  114. //再次签名
  115. String paySign=PayUtil.sign(stringSignTemp, "&key=替换为自己的密钥", "utf-8").toUpperCase();
  116. JsonObject.put("paySign", paySign);
  117. jsonArray.add(JsonObject);
  118. }
  119. return "pay";
  120. }
  121. public String getTotal_fee() {
  122. return total_fee;
  123. }
  124. public void setTotal_fee(String total_fee) {
  125. this.total_fee = total_fee;
  126. }
  127. public String getBody() {
  128. return body;
  129. }
  130. public void setBody(String body) {
  131. this.body = body;
  132. }
  133. public JSONArray getJsonArray() {
  134. return jsonArray;
  135. }
  136. public void setJsonArray(JSONArray jsonArray) {
  137. this.jsonArray = jsonArray;
  138. }
  139. public String getDetail() {
  140. return detail;
  141. }
  142. public void setDetail(String detail) {
  143. this.detail = detail;
  144. }
  145. public String getAttach() {
  146. return attach;
  147. }
  148. public void setAttach(String attach) {
  149. this.attach = attach;
  150. }
  151. public String getTime_start() {
  152. return time_start;
  153. }
  154. public void setTime_start(String time_start) {
  155. this.time_start = time_start;
  156. }
  157. public String getTime_expire() {
  158. return time_expire;
  159. }
  160. public void setTime_expire(String time_expire) {
  161. this.time_expire = time_expire;
  162. }
  163. public String getOpenid() {
  164. return openid;
  165. }
  166. public void setOpenid(String openid) {
  167. this.openid = openid;
  168. }
  169. }

后台业务逻辑涉及到的工具类及参数封装类

  1. MessageUtil
  2. package cn.it.shop.util;
  3. import java.io.IOException;
  4. import java.io.Writer;
  5. import java.util.HashMap;
  6. import java.util.List;
  7. import javax.servlet.http.HttpServletRequest;
  8. import org.dom4j.Document;
  9. import org.dom4j.Element;
  10. import org.dom4j.io.SAXReader;
  11. import com.thoughtworks.xstream.XStream;
  12. import com.thoughtworks.xstream.core.util.QuickWriter;
  13. import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
  14. import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
  15. import com.thoughtworks.xstream.io.xml.XppDriver;
  16. public class MessageUtil {
  17. public static HashMap<String,String> parseXML(HttpServletRequest request) throws Exception, IOException{
  18. HashMap<String,String> map=new HashMap<String,String>();
  19. // 通过IO获得Document
  20. SAXReader reader = new SAXReader();
  21. Document doc = reader.read(request.getInputStream());
  22. //得到xml的根节点
  23. Element root=doc.getRootElement();
  24. recursiveParseXML(root,map);
  25. return map;
  26. }
  27. private static void recursiveParseXML(Element root,HashMap<String,String> map){
  28. //得到根节点的子节点列表
  29. List<Element> elementList=root.elements();
  30. //判断有没有子元素列表
  31. if(elementList.size()==0){
  32. map.put(root.getName(), root.getTextTrim());
  33. }
  34. else{
  35. //遍历
  36. for(Element e:elementList){
  37. recursiveParseXML(e,map);
  38. }
  39. }
  40. }
  41. private static XStream xstream = new XStream(new XppDriver() {
  42. public HierarchicalStreamWriter createWriter(Writer out) {
  43. return new PrettyPrintWriter(out) {
  44. // 对所有xml节点都增加CDATA标记
  45. boolean cdata = true;
  46. public void startNode(String name, Class clazz) {
  47. super.startNode(name, clazz);
  48. }
  49. protected void writeText(QuickWriter writer, String text) {
  50. if (cdata) {
  51. writer.write("<![CDATA[");
  52. writer.write(text);
  53. writer.write("]]>");
  54. } else {
  55. writer.write(text);
  56. }
  57. }
  58. };
  59. }
  60. });
  61. public static String messageToXML(PaymentPo paymentPo){
  62. xstream.alias("xml",PaymentPo.class);
  63. return xstream.toXML(paymentPo);
  64. }
  65. }
  66. PaymentPo//封装支付参数实体
  67. package cn.it.shop.util;
  68. /**
  69. * @author
  70. * @version 创建时间:2017年1月21日 下午4:20:52
  71. * 类说明
  72. */
  73. public class PaymentPo {
  74. private String appid;//小程序ID
  75. private String mch_id;//商户号
  76. private String device_info;//设备号
  77. private String nonce_str;//随机字符串
  78. private String sign;//签名
  79. private String body;//商品描述
  80. private String detail;//商品详情
  81. private String attach;//附加数据
  82. private String out_trade_no;//商户订单号
  83. private String fee_type;//货币类型
  84. private String spbill_create_ip;//终端IP
  85. private String time_start;//交易起始时间
  86. private String time_expire;//交易结束时间
  87. private String goods_tag;//商品标记
  88. private String total_fee;//总金额
  89. private String notify_url;//通知地址
  90. private String trade_type;//交易类型
  91. private String limit_pay;//指定支付方式
  92. private String openid;//用户标识
  93. public String getAppid() {
  94. return appid;
  95. }
  96. public void setAppid(String appid) {
  97. this.appid = appid;
  98. }
  99. public String getMch_id() {
  100. return mch_id;
  101. }
  102. public void setMch_id(String mch_id) {
  103. this.mch_id = mch_id;
  104. }
  105. public String getNonce_str() {
  106. return nonce_str;
  107. }
  108. public void setNonce_str(String nonce_str) {
  109. this.nonce_str = nonce_str;
  110. }
  111. public String getSign() {
  112. return sign;
  113. }
  114. public void setSign(String sign) {
  115. this.sign = sign;
  116. }
  117. public String getBody() {
  118. return body;
  119. }
  120. public void setBody(String body) {
  121. this.body = body;
  122. }
  123. public String getOut_trade_no() {
  124. return out_trade_no;
  125. }
  126. public void setOut_trade_no(String out_trade_no) {
  127. this.out_trade_no = out_trade_no;
  128. }
  129. public String getTotal_fee() {
  130. return total_fee;
  131. }
  132. public void setTotal_fee(String total_fee) {
  133. this.total_fee = total_fee;
  134. }
  135. public String getNotify_url() {
  136. return notify_url;
  137. }
  138. public void setNotify_url(String notify_url) {
  139. this.notify_url = notify_url;
  140. }
  141. public String getTrade_type() {
  142. return trade_type;
  143. }
  144. public void setTrade_type(String trade_type) {
  145. this.trade_type = trade_type;
  146. }
  147. public String getOpenid() {
  148. return openid;
  149. }
  150. public void setOpenid(String openid) {
  151. this.openid = openid;
  152. }
  153. public String getSpbill_create_ip() {
  154. return spbill_create_ip;
  155. }
  156. public void setSpbill_create_ip(String spbill_create_ip) {
  157. this.spbill_create_ip = spbill_create_ip;
  158. }
  159. public String getDevice_info() {
  160. return device_info;
  161. }
  162. public void setDevice_info(String device_info) {
  163. this.device_info = device_info;
  164. }
  165. public String getDetail() {
  166. return detail;
  167. }
  168. public void setDetail(String detail) {
  169. this.detail = detail;
  170. }
  171. public String getAttach() {
  172. return attach;
  173. }
  174. public void setAttach(String attach) {
  175. this.attach = attach;
  176. }
  177. public String getFee_type() {
  178. return fee_type;
  179. }
  180. public void setFee_type(String fee_type) {
  181. this.fee_type = fee_type;
  182. }
  183. public String getTime_start() {
  184. return time_start;
  185. }
  186. public void setTime_start(String time_start) {
  187. this.time_start = time_start;
  188. }
  189. public String getTime_expire() {
  190. return time_expire;
  191. }
  192. public void setTime_expire(String time_expire) {
  193. this.time_expire = time_expire;
  194. }
  195. public String getGoods_tag() {
  196. return goods_tag;
  197. }
  198. public void setGoods_tag(String goods_tag) {
  199. this.goods_tag = goods_tag;
  200. }
  201. public String getLimit_pay() {
  202. return limit_pay;
  203. }
  204. public void setLimit_pay(String limit_pay) {
  205. this.limit_pay = limit_pay;
  206. }
  207. }
  208. PayUtil
  209. package cn.it.shop.util;
  210. import java.io.BufferedReader;
  211. import java.io.InputStream;
  212. import java.io.InputStreamReader;
  213. import java.io.OutputStream;
  214. import java.io.UnsupportedEncodingException;
  215. import java.net.HttpURLConnection;
  216. import java.net.URL;
  217. import java.util.ArrayList;
  218. import java.util.Collections;
  219. import java.util.HashMap;
  220. import java.util.List;
  221. import java.util.Map;
  222. import org.apache.commons.codec.digest.DigestUtils;
  223. /**
  224. * @author
  225. * @version 创建时间:2017年1月17日 下午7:46:29 类说明
  226. */
  227. public class PayUtil {
  228. /**
  229. * 签名字符串
  230. * @param text需要签名的字符串
  231. * @param key 密钥
  232. * @param input_charset编码格式
  233. * @return 签名结果
  234. */
  235. public static String sign(String text, String key, String input_charset) {
  236. text = text + key;
  237. return DigestUtils.md5Hex(getContentBytes(text, input_charset));
  238. }
  239. /**
  240. * 签名字符串
  241. * @param text需要签名的字符串
  242. * @param sign 签名结果
  243. * @param key密钥
  244. * @param input_charset 编码格式
  245. * @return 签名结果
  246. */
  247. public static boolean verify(String text, String sign, String key, String input_charset) {
  248. text = text + key;
  249. String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
  250. if (mysign.equals(sign)) {
  251. return true;
  252. } else {
  253. return false;
  254. }
  255. }
  256. /**
  257. * @param content
  258. * @param charset
  259. * @return
  260. * @throws SignatureException
  261. * @throws UnsupportedEncodingException
  262. */
  263. public static byte[] getContentBytes(String content, String charset) {
  264. if (charset == null || "".equals(charset)) {
  265. return content.getBytes();
  266. }
  267. try {
  268. return content.getBytes(charset);
  269. } catch (UnsupportedEncodingException e) {
  270. throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
  271. }
  272. }
  273. /**
  274. * 生成6位或10位随机数 param codeLength(多少位)
  275. * @return
  276. */
  277. public static String createCode(int codeLength) {
  278. String code = "";
  279. for (int i = 0; i < codeLength; i++) {
  280. code += (int) (Math.random() * 9);
  281. }
  282. return code;
  283. }
  284. private static boolean isValidChar(char ch) {
  285. if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
  286. return true;
  287. if ((ch >= 0x4e00 && ch <= 0x7fff) || (ch >= 0x8000 && ch <= 0x952f))
  288. return true;// 简体中文汉字编码
  289. return false;
  290. }
  291. /**
  292. * 除去数组中的空值和签名参数
  293. * @param sArray 签名参数组
  294. * @return 去掉空值与签名参数后的新签名参数组
  295. */
  296. public static Map<String, String> paraFilter(Map<String, String> sArray) {
  297. Map<String, String> result = new HashMap<String, String>();
  298. if (sArray == null || sArray.size() <= 0) {
  299. return result;
  300. }
  301. for (String key : sArray.keySet()) {
  302. String value = sArray.get(key);
  303. if (value == null || value.equals("") || key.equalsIgnoreCase("sign")
  304. || key.equalsIgnoreCase("sign_type")) {
  305. continue;
  306. }
  307. result.put(key, value);
  308. }
  309. return result;
  310. }
  311. /**
  312. * 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串
  313. * @param params 需要排序并参与字符拼接的参数组
  314. * @return 拼接后字符串
  315. */
  316. public static String createLinkString(Map<String, String> params) {
  317. List<String> keys = new ArrayList<String>(params.keySet());
  318. Collections.sort(keys);
  319. String prestr = "";
  320. for (int i = 0; i < keys.size(); i++) {
  321. String key = keys.get(i);
  322. String value = params.get(key);
  323. if (i == keys.size() - 1) {// 拼接时,不包括最后一个&字符
  324. prestr = prestr + key + "=" + value;
  325. } else {
  326. prestr = prestr + key + "=" + value + "&";
  327. }
  328. }
  329. return prestr;
  330. }
  331. /**
  332. *
  333. * @param requestUrl请求地址
  334. * @param requestMethod请求方法
  335. * @param outputStr参数
  336. */
  337. public static String httpRequest(String requestUrl,String requestMethod,String outputStr){
  338. // 创建SSLContext
  339. StringBuffer buffer=null;
  340. try{
  341. URL url = new URL(requestUrl);
  342. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  343. conn.setRequestMethod(requestMethod);
  344. conn.setDoOutput(true);
  345. conn.setDoInput(true);
  346. conn.connect();
  347. //往服务器端写内容
  348. if(null !=outputStr){
  349. OutputStream os=conn.getOutputStream();
  350. os.write(outputStr.getBytes("utf-8"));
  351. os.close();
  352. }
  353. // 读取服务器端返回的内容
  354. InputStream is = conn.getInputStream();
  355. InputStreamReader isr = new InputStreamReader(is, "utf-8");
  356. BufferedReader br = new BufferedReader(isr);
  357. buffer = new StringBuffer();
  358. String line = null;
  359. while ((line = br.readLine()) != null) {
  360. buffer.append(line);
  361. }
  362. }catch(Exception e){
  363. e.printStackTrace();
  364. }
  365. return buffer.toString();
  366. }
  367. public static String urlEncodeUTF8(String source){
  368. String result=source;
  369. try {
  370. result=java.net.URLEncoder.encode(source, "UTF-8");
  371. } catch (UnsupportedEncodingException e) {
  372. // TODO Auto-generated catch block
  373. e.printStackTrace();
  374. }
  375. return result;
  376. }
  377. }
  378. UUIDHexGenerator
  379. package cn.it.shop.util;
  380. import java.net.InetAddress;
  381. /**
  382. * @author
  383. * @version 创建时间:2017年1月17日 下午7:45:06 类说明
  384. */
  385. public class UUIDHexGenerator {
  386. private static String sep = "";
  387. private static final int IP;
  388. private static short counter = (short) 0;
  389. private static final int JVM = (int) (System.currentTimeMillis() >>> 8);
  390. private static UUIDHexGenerator uuidgen = new UUIDHexGenerator();
  391. static {
  392. int ipadd;
  393. try {
  394. ipadd = toInt(InetAddress.getLocalHost().getAddress());
  395. } catch (Exception e) {
  396. ipadd = 0;
  397. }
  398. IP = ipadd;
  399. }
  400. public static UUIDHexGenerator getInstance() {
  401. return uuidgen;
  402. }
  403. public static int toInt(byte[] bytes) {
  404. int result = 0;
  405. for (int i = 0; i < 4; i++) {
  406. result = (result << 8) - Byte.MIN_VALUE + (int) bytes[i];
  407. }
  408. return result;
  409. }
  410. protected static String format(int intval) {
  411. String formatted = Integer.toHexString(intval);
  412. StringBuffer buf = new StringBuffer("00000000");
  413. buf.replace(8 - formatted.length(), 8, formatted);
  414. return buf.toString();
  415. }
  416. protected static String format(short shortval) {
  417. String formatted = Integer.toHexString(shortval);
  418. StringBuffer buf = new StringBuffer("0000");
  419. buf.replace(4 - formatted.length(), 4, formatted);
  420. return buf.toString();
  421. }
  422. protected static int getJVM() {
  423. return JVM;
  424. }
  425. protected synchronized static short getCount() {
  426. if (counter < 0) {
  427. counter = 0;
  428. }
  429. return counter++;
  430. }
  431. protected static int getIP() {
  432. return IP;
  433. }
  434. protected static short getHiTime() {
  435. return (short) (System.currentTimeMillis() >>> 32);
  436. }
  437. protected static int getLoTime() {
  438. return (int) System.currentTimeMillis();
  439. }
  440. public static String generate() {
  441. return new StringBuffer(36).append(format(getIP())).append(sep).append(format(getJVM())).append(sep)
  442. .append(format(getHiTime())).append(sep).append(format(getLoTime())).append(sep)
  443. .append(format(getCount())).toString();
  444. }
  445. /**
  446. * @param args
  447. */
  448. public static void main(String[] args) {
  449. String id="";
  450. UUIDHexGenerator uuid = UUIDHexGenerator.getInstance();
  451. /*
  452. for (int i = 0; i < 100; i++) {
  453. id = uuid.generate();
  454. }*/
  455. id = uuid.generate();
  456. System.out.println(id);
  457. }
  458. }

第一次写,写的不是太完整,希望同大家多多交流,一起进步。

最新评论

a309394507 发表于 2022-6-14 05:19
安卓系统源代码是什么语言

一起源码让程序更轻更快

www.171739.xyz

工作时间 周一至周六 8:00-17:30

侵权处理

客服QQ点击咨询

关注抖音号

定期抽VIP

Copyright © 2016-2021 https://www.171739.xyz/ 滇ICP备13200218号

快速回复 返回顶部 返回列表