util.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. const app = getApp();
  2. const appConfig = require("../config")
  3. const Encrypt = require("../js/jsencrypt")
  4. const sha1 = require("../js/sha1");
  5. function http_build_query(formdata, numeric_prefix, arg_separator) {
  6. var value, key, tmp = [],
  7. that = this;
  8. var _http_build_query_helper = function (key, val, arg_separator) {
  9. var k, tmp = [];
  10. if (val === true) {
  11. val = '1';
  12. } else if (val === false) {
  13. val = '0';
  14. }
  15. if (val != null) {
  16. if (typeof val === 'object') {
  17. for (k in val) {
  18. if (val[k] != null) {
  19. tmp.push(_http_build_query_helper(key + '[' + k + ']', val[k], arg_separator));
  20. }
  21. }
  22. return tmp.join(arg_separator);
  23. } else if (typeof val !== 'function') {
  24. key = urldecode(key),
  25. val = urldecode(val); //有可能参数之前是encode过 add by fengwei
  26. return urlencode(key) + '=' + urlencode(val);
  27. } else {
  28. throw new Error('There was an error processing for http_build_query().');
  29. }
  30. } else {
  31. return '';
  32. }
  33. };
  34. if (!arg_separator) {
  35. arg_separator = '&';
  36. }
  37. for (key in formdata) {
  38. value = formdata[key];
  39. if (numeric_prefix && !isNaN(key)) {
  40. key = String(numeric_prefix) + key;
  41. }
  42. var query = _http_build_query_helper(key, value, arg_separator);
  43. if (query !== '') {
  44. tmp.push(query);
  45. }
  46. }
  47. return tmp.join(arg_separator);
  48. }
  49. //如php urlencode.
  50. function urlencode(str) {
  51. str += '';
  52. return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
  53. }
  54. //php urldecode.
  55. function urldecode(str) {
  56. try {
  57. return decodeURIComponent((str + '').replace(/%(?![\da-f]{2})/gi,
  58. function () {
  59. return '%25';
  60. }).replace(/\+/g, '%20'));
  61. } catch (e) {
  62. return '';
  63. }
  64. }
  65. var ksort = function(arr) {
  66. const ordered = {};
  67. Object.keys(arr).sort().forEach(function (key) {
  68. ordered[key] = arr[key];
  69. });
  70. return ordered;
  71. }
  72. const formatTime = date => {
  73. const year = date.getFullYear()
  74. const month = date.getMonth() + 1
  75. const day = date.getDate()
  76. const hour = date.getHours()
  77. const minute = date.getMinutes()
  78. const second = date.getSeconds()
  79. return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  80. }
  81. const formatNumber = n => {
  82. n = n.toString()
  83. return n[1] ? n : '0' + n
  84. }
  85. var showCreateTime = function(){
  86. var date = new Date();
  87. const month = date.getMonth() + 1
  88. const day = date.getDate()
  89. const hour = date.getHours()
  90. const minute = date.getMinutes()
  91. return [month, day].map(formatNumber).join('-') + ' ' + [hour, minute].map(formatNumber).join(':');
  92. }
  93. var wordwrap = function (str, width) {
  94. width = width || 64;
  95. if (!str) {
  96. return str;
  97. }
  98. var regex = "(.{1," + width + "})( +|$\n?)|(.{1," + width + "})";
  99. return str.match(RegExp(regex, "g")).join("\n");
  100. };
  101. var sslEncrypt = function(str, publicKey) {
  102. return this.encrypt(str, publicKey);
  103. }
  104. var sslDecrypt = function (str, privateKey) {
  105. //格式化js使用的private key格式,服务端返回的跟本地使用的不一致
  106. privateKey = privateKey.replace("-----BEGIN RSA PRIVATE KEY-----", "-----BEGIN PRIVATE KEY-----");
  107. privateKey = privateKey.replace("-----END RSA PRIVATE KEY-----", "-----END PRIVATE KEY-----");
  108. return this.decrypt(str, privateKey);
  109. }
  110. var hexSha1 = function(str){
  111. return sha1.sha1(str);
  112. }
  113. var sslSign = function (text, privateKey) {
  114. var crypt = new Encrypt.JSEncrypt({ default_key_size: 1024 });
  115. crypt.setPrivateKey(privateKey);
  116. return crypt.sign(text, hexSha1, '');
  117. }
  118. //验证公私钥
  119. var verifySslKey = function(publicKey, privateKey){
  120. var verifyStr = "It's ok";
  121. var encrypt = this.encrypt(verifyStr, publicKey);
  122. var decrypt = this.decrypt(encrypt, privateKey);
  123. if (decrypt != verifyStr) {
  124. return false;
  125. }
  126. return true;
  127. }
  128. var genSslKey = function(){
  129. var crypt = new Encrypt.JSEncrypt({ default_key_size: 1024 });
  130. crypt.getKey();
  131. var publicKey = crypt.getPublicKey();
  132. var privateKey = crypt.getPrivateKey();
  133. return {
  134. publicKey : publicKey,
  135. privateKey : privateKey
  136. };
  137. }
  138. var encrypt = function (str, publicKey) {
  139. var crypt = new Encrypt.JSEncrypt();
  140. crypt.setPublicKey(publicKey);
  141. return crypt.encrypt(str);
  142. }
  143. var decrypt = function(str, privateKey){
  144. var crypt = new Encrypt.JSEncrypt();
  145. crypt.setPrivateKey(privateKey);
  146. var decStr = crypt.decrypt(str);
  147. if(decStr == null) return false;
  148. return decStr;
  149. }
  150. var getUrl = function(api, params) {
  151. if(typeof params == 'undefined')
  152. {
  153. params = {};
  154. }
  155. params.fromApp = "weixin";
  156. params.appId = wx.getAccountInfoSync().miniProgram.appId;
  157. if (!appConfig.api[api]) {
  158. return "";
  159. }
  160. params.isLocal = appConfig.api[api].indexOf("localhost") != -1 ? 1 : 0;
  161. if (appConfig.api[api].indexOf("?") !== -1) {
  162. return appConfig.api[api] + "&" + http_build_query(params);
  163. }
  164. return appConfig.api[api] + "?" + http_build_query(params);
  165. }
  166. var getSwitchToLocalStatus = function() {
  167. var localStatus = wx.getStorageSync(appConfig.storeKeys.switchToLocal) || 0;
  168. if(localStatus == 1) {
  169. return true;
  170. }
  171. return false;
  172. }
  173. var syncServerInfo = function() { //同步更新serverInfo和sslKey
  174. var sslKeys = wx.getStorageSync(appConfig.storeKeys.sslKeys)
  175. var serverInfo = wx.getStorageSync(appConfig.storeKeys.serverInfo);
  176. if (!serverInfo) return false;
  177. if (sslKeys && sslKeys['publicKey'] && sslKeys['privateKey'] &&
  178. serverInfo && serverInfo['sslKeys'] && (sslKeys['publicKey'] == serverInfo['sslKeys']['publicKey'])
  179. ) {
  180. serverInfo['sslKeys']['privateKey'] = sslKeys['privateKey'];
  181. wx.setStorageSync(appConfig.storeKeys.serverInfo, serverInfo);
  182. }
  183. return serverInfo;
  184. }
  185. var hasPublicKey = function() {
  186. var serverInfo = this.syncServerInfo();
  187. if (!serverInfo) {
  188. return false;
  189. }
  190. if (!serverInfo['sslKeys']) {
  191. return false;
  192. }
  193. if (!serverInfo['sslKeys']['publicKey'] || serverInfo['sslKeys']['publicKey'] == "") {
  194. return false;
  195. }
  196. return true;
  197. }
  198. var hasPrivateKey = function() {
  199. var serverInfo = this.syncServerInfo();
  200. if (!serverInfo) {
  201. return false;
  202. }
  203. if (!serverInfo['sslKeys']) {
  204. return false;
  205. }
  206. if (!serverInfo['sslKeys']['privateKey'] || serverInfo['sslKeys']['privateKey'] == "") {
  207. return false;
  208. }
  209. return true;
  210. }
  211. ///
  212. var getPublicKey = function() {
  213. var serverInfo = this.syncServerInfo();
  214. if (!serverInfo) {
  215. return "";
  216. }
  217. if (!serverInfo['sslKeys']) {
  218. return "";
  219. }
  220. if (!serverInfo['sslKeys']['publicKey'] || serverInfo['sslKeys']['publicKey'] == "") {
  221. return "";
  222. }
  223. return serverInfo['sslKeys']['publicKey'];
  224. }
  225. var getPrivateKey = function() {
  226. var serverInfo = this.syncServerInfo();
  227. if (!serverInfo) {
  228. return "";
  229. }
  230. if (!serverInfo['sslKeys']) {
  231. return "";
  232. }
  233. if (!serverInfo['sslKeys']['privateKey'] || serverInfo['sslKeys']['privateKey'] == "") {
  234. return "";
  235. }
  236. return serverInfo['sslKeys']['privateKey'];
  237. }
  238. var hasLogined = function() {
  239. var serverInfo = this.syncServerInfo();
  240. if (!serverInfo) {
  241. return false;
  242. }
  243. if (serverInfo.sessionId && serverInfo.openId &&
  244. serverInfo.sessionId != "" && serverInfo.openId != ""
  245. ) {
  246. return true;
  247. }
  248. return false;
  249. }
  250. var getSessionId = function() {
  251. var serverInfo = this.syncServerInfo();
  252. if (!serverInfo) {
  253. return "";
  254. }
  255. if (!serverInfo['sessionId']) {
  256. return "";
  257. }
  258. return serverInfo['sessionId'];
  259. }
  260. var getOpenId = function() {
  261. var serverInfo = this.syncServerInfo();
  262. if (!serverInfo) {
  263. return "";
  264. }
  265. if (!serverInfo['openId']) {
  266. return "";
  267. }
  268. return serverInfo['openId'];
  269. }
  270. var setBackground = function(url) {
  271. wx.setStorageSync(appConfig.storeKeys.background, url);
  272. }
  273. var getBackground = function() {
  274. var background = wx.getStorageSync(appConfig.storeKeys.background);
  275. if (!background) return app.globalData.background;
  276. return background;
  277. }
  278. var promisify = api => {
  279. return (options, ...params) => {
  280. return new Promise((resolve, reject) => {
  281. const extras = {
  282. success: resolve,
  283. fail: reject
  284. }
  285. api({ ...options, ...extras }, ...params)
  286. })
  287. }
  288. }
  289. module.exports = {
  290. formatTime: formatTime,
  291. hexSha1: hexSha1,
  292. sslEncrypt: encrypt,
  293. sslDecrypt: decrypt,
  294. sslSign: sslSign,
  295. encrypt: encrypt,
  296. decrypt: decrypt,
  297. genSslKey: genSslKey,
  298. verifySslKey: verifySslKey,
  299. getUrl: getUrl,
  300. httpBuild: http_build_query,
  301. getSwitchToLocalStatus: getSwitchToLocalStatus,
  302. showCreateTime: showCreateTime,
  303. syncServerInfo: syncServerInfo,
  304. hasPublicKey: hasPublicKey,
  305. hasPrivateKey: hasPrivateKey,
  306. getPublicKey: getPublicKey,
  307. getPrivateKey: getPrivateKey,
  308. hasLogined: hasLogined,
  309. getSessionId: getSessionId,
  310. getOpenId: getOpenId,
  311. setBackground: setBackground,
  312. getBackground: getBackground,
  313. promisify: promisify,
  314. ksort: ksort,
  315. }