util.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. // 去除-----*** RSA **** KEY----- 和空格换行
  134. //publicKey = (publicKey.split('-----'))[2];
  135. //publicKey = publicKey.replace(/\n/g, "").replace(/\r/g, "").replace(/\t/g, "").replace(/\s*/g, "");
  136. //privateKey = (privateKey.split('-----'))[2];
  137. //privateKey = privateKey.replace(/\n/g, "").replace(/\r/g, "").replace(/\t/g, "").replace(/\s*/g, "");
  138. return {
  139. publicKey : publicKey,
  140. privateKey : privateKey
  141. };
  142. }
  143. var encrypt = function (str, publicKey) {
  144. var crypt = new Encrypt.JSEncrypt();
  145. crypt.setPublicKey(publicKey);
  146. return crypt.encrypt(str);
  147. }
  148. var decrypt = function(str, privateKey){
  149. var crypt = new Encrypt.JSEncrypt();
  150. crypt.setPrivateKey(privateKey);
  151. var decStr = crypt.decrypt(str);
  152. if(decStr == null) return false;
  153. return decStr;
  154. }
  155. var getUrl = function(api, params) {
  156. if(typeof params == 'undefined')
  157. {
  158. params = {};
  159. }
  160. params.fromApp = "weixin";
  161. params.appId = wx.getAccountInfoSync().miniProgram.appId;
  162. if (!appConfig.api[api]) {
  163. return "";
  164. }
  165. params.isLocal = appConfig.api[api].indexOf("localhost") != -1 ? 1 : 0;
  166. if (appConfig.api[api].indexOf("?") !== -1) {
  167. return appConfig.api[api] + "&" + http_build_query(params);
  168. }
  169. return appConfig.api[api] + "?" + http_build_query(params);
  170. }
  171. var getSwitchToLocalStatus = function() {
  172. var localStatus = wx.getStorageSync(appConfig.storeKeys.switchToLocal) || 0;
  173. if(localStatus == 1) {
  174. return true;
  175. }
  176. return false;
  177. }
  178. var syncServerInfo = function() { //同步更新serverInfo和sslKey
  179. var sslKeys = wx.getStorageSync(appConfig.storeKeys.sslKeys)
  180. var serverInfo = wx.getStorageSync(appConfig.storeKeys.serverInfo);
  181. if (!serverInfo) return false;
  182. if (sslKeys && sslKeys['publicKey'] && sslKeys['privateKey'] &&
  183. serverInfo && serverInfo['sslKeys'] && (sslKeys['publicKey'] == serverInfo['sslKeys']['publicKey'])
  184. ) {
  185. serverInfo['sslKeys']['privateKey'] = sslKeys['privateKey'];
  186. wx.setStorageSync(appConfig.storeKeys.serverInfo, serverInfo);
  187. }
  188. return serverInfo;
  189. }
  190. var hasPublicKey = function() {
  191. var serverInfo = this.syncServerInfo();
  192. if (!serverInfo) {
  193. return false;
  194. }
  195. if (!serverInfo['sslKeys']) {
  196. return false;
  197. }
  198. if (!serverInfo['sslKeys']['publicKey'] || serverInfo['sslKeys']['publicKey'] == "") {
  199. return false;
  200. }
  201. return true;
  202. }
  203. var hasPrivateKey = function() {
  204. var serverInfo = this.syncServerInfo();
  205. if (!serverInfo) {
  206. return false;
  207. }
  208. if (!serverInfo['sslKeys']) {
  209. return false;
  210. }
  211. if (!serverInfo['sslKeys']['privateKey'] || serverInfo['sslKeys']['privateKey'] == "") {
  212. return false;
  213. }
  214. return true;
  215. }
  216. ///
  217. var getPublicKey = function() {
  218. var serverInfo = this.syncServerInfo();
  219. if (!serverInfo) {
  220. return "";
  221. }
  222. if (!serverInfo['sslKeys']) {
  223. return "";
  224. }
  225. if (!serverInfo['sslKeys']['publicKey'] || serverInfo['sslKeys']['publicKey'] == "") {
  226. return "";
  227. }
  228. return serverInfo['sslKeys']['publicKey'];
  229. }
  230. var getPrivateKey = function() {
  231. var serverInfo = this.syncServerInfo();
  232. if (!serverInfo) {
  233. return "";
  234. }
  235. if (!serverInfo['sslKeys']) {
  236. return "";
  237. }
  238. if (!serverInfo['sslKeys']['privateKey'] || serverInfo['sslKeys']['privateKey'] == "") {
  239. return "";
  240. }
  241. return serverInfo['sslKeys']['privateKey'];
  242. }
  243. var hasLogined = function() {
  244. var serverInfo = this.syncServerInfo();
  245. if (!serverInfo) {
  246. return false;
  247. }
  248. if (serverInfo.sessionId && serverInfo.openId &&
  249. serverInfo.sessionId != "" && serverInfo.openId != ""
  250. ) {
  251. return true;
  252. }
  253. return false;
  254. }
  255. var getSessionId = function() {
  256. var serverInfo = this.syncServerInfo();
  257. if (!serverInfo) {
  258. return "";
  259. }
  260. if (!serverInfo['sessionId']) {
  261. return "";
  262. }
  263. return serverInfo['sessionId'];
  264. }
  265. var getOpenId = function() {
  266. var serverInfo = this.syncServerInfo();
  267. if (!serverInfo) {
  268. return "";
  269. }
  270. if (!serverInfo['openId']) {
  271. return "";
  272. }
  273. return serverInfo['openId'];
  274. }
  275. var setBackground = function(url) {
  276. wx.setStorageSync(appConfig.storeKeys.background, url);
  277. }
  278. var getBackground = function() {
  279. var background = wx.getStorageSync(appConfig.storeKeys.background);
  280. if (!background) return app.globalData.background;
  281. return background;
  282. }
  283. var promisify = api => {
  284. return (options, ...params) => {
  285. return new Promise((resolve, reject) => {
  286. const extras = {
  287. success: resolve,
  288. fail: reject
  289. }
  290. api({ ...options, ...extras }, ...params)
  291. })
  292. }
  293. }
  294. module.exports = {
  295. formatTime: formatTime,
  296. hexSha1: hexSha1,
  297. sslEncrypt: encrypt,
  298. sslDecrypt: decrypt,
  299. sslSign: sslSign,
  300. encrypt: encrypt,
  301. decrypt: decrypt,
  302. genSslKey: genSslKey,
  303. verifySslKey: verifySslKey,
  304. getUrl: getUrl,
  305. httpBuild: http_build_query,
  306. getSwitchToLocalStatus: getSwitchToLocalStatus,
  307. showCreateTime: showCreateTime,
  308. syncServerInfo: syncServerInfo,
  309. hasPublicKey: hasPublicKey,
  310. hasPrivateKey: hasPrivateKey,
  311. getPublicKey: getPublicKey,
  312. getPrivateKey: getPrivateKey,
  313. hasLogined: hasLogined,
  314. getSessionId: getSessionId,
  315. getOpenId: getOpenId,
  316. setBackground: setBackground,
  317. getBackground: getBackground,
  318. promisify: promisify,
  319. ksort: ksort,
  320. }