native.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  1. /**
  2. * desc: js和客户端的交互模块,尽量封装到对业务逻辑透明,为移植到其他平台做准备
  3. * author: wangyang
  4. * date: 2015-04-11
  5. */
  6. //本地回调对象
  7. var NativeCallback;
  8. var NativeDataAdapter;
  9. define(function (require) {
  10. var helper = require('helper');
  11. var config = require('config');
  12. var pingpp = require('pingpp');
  13. //客户端接口类
  14. function NativeApi() {
  15. if (typeof NativeApi.instance === 'object') {
  16. return NativeApi.instance;
  17. }
  18. NativeApi.instance = this;
  19. this.getUserInfoCallback = null;
  20. this.shareCallback = null;
  21. this.getSignCallback = null;
  22. this.loginCallback = null;
  23. this.isWxAppInstalledCallback = null;
  24. this.payCallback = null;
  25. this.selectAddressCallback = null;
  26. this.chooseImageCallback = null;
  27. this.uploadImageCallbacks = {};
  28. this.selectPetTypeCallback = null;
  29. this.charge = null;
  30. this.keyboardEventTimer = 0;
  31. this.originalHeight = document.body.scrollHeight;
  32. this.keyboardIsOpen = false;
  33. this.keyboardIsClose = false;
  34. }
  35. NativeApi.prototype = {
  36. //获取用户信息
  37. getUserInfo: function (callback) {
  38. var that = this;
  39. var _callback = 'NativeCallback.getUserInfo';
  40. helper.osProxy({
  41. android: function () {
  42. var param = {
  43. callback: _callback
  44. };
  45. var param_str = JSON.stringify(param);
  46. window.jsapi.getUserInfo(param_str);
  47. },
  48. ios: function () {
  49. window.location.href = 'http://callclient?method=getUserInfo&callback=' + _callback;
  50. },
  51. wx: function () {
  52. //此处有一个循环引用
  53. require('api').getO2oUserInfo({
  54. request_from: 'weixin',
  55. user_id: localStorage.getItem('xyhwxUserID')
  56. }, function (res) {
  57. if (typeof(that.getUserInfoCallback) == 'function') {
  58. that.getUserInfoCallback(res);
  59. }
  60. });
  61. },
  62. cb: function () {
  63. require(['../../common/js/ctk-1.0.0'], function (ctk) {
  64. ctk.logged({
  65. yes: function (res) {
  66. console.log('已登录', res);
  67. //判断用户已登录的回调函数,用户的accessToken存放在res.accessToken内
  68. require('api').getO2oUserInfo({
  69. from: 'chubao',
  70. accessToken: res.accessToken
  71. }, function (res) {
  72. if (typeof(that.getUserInfoCallback) == 'function') {
  73. that.getUserInfoCallback(res);
  74. }
  75. });
  76. },
  77. no: function (res) {
  78. ctk.login({
  79. phone: '',
  80. success: function (res) {
  81. require('api').getO2oUserInfo({
  82. from: 'chubao',
  83. accessToken: res.accessToken
  84. }, function (res) {
  85. if (typeof(that.getUserInfoCallback) == 'function') {
  86. that.getUserInfoCallback(res);
  87. }
  88. });
  89. },
  90. fail: function (res) {
  91. // alert('login failed!');
  92. }
  93. });
  94. }
  95. });
  96. })
  97. }
  98. });
  99. var callback = typeof (arguments[0]) == 'function' ? arguments[0] : null;
  100. this.getUserInfoCallback = callback;
  101. },
  102. //从web返回APP
  103. back: function () {
  104. helper.osProxy({
  105. android: function () {
  106. window.jsapi.exitWebView();
  107. },
  108. ios: function () {
  109. window.location.href = 'http://callclient?method=exitWebView';
  110. },
  111. wx: function () {
  112. require(['../../common/js/jweixin-1.0.0'], function (wx) {
  113. wx.closeWindow();
  114. });
  115. }
  116. });
  117. },
  118. //登录
  119. login: function (callback) {
  120. var that = this;
  121. var _callback = 'NativeCallback.login';
  122. helper.osProxy({
  123. android: function () {
  124. var param = {
  125. callback: _callback
  126. };
  127. var param_str = JSON.stringify(param);
  128. window.jsapi.goLogin(param_str);
  129. },
  130. ios: function () {
  131. window.location.href = 'http://callclient?method=goLogin&callback=' + _callback;
  132. }
  133. });
  134. var callback = typeof (arguments[0]) == 'function' ? arguments[0] : null;
  135. this.loginCallback = callback;
  136. },
  137. //分享
  138. share: function (title, content, img_url, url, app_id, callback) {
  139. var param = {
  140. "share_title": title,
  141. "share_string": content,
  142. "share_img_url": img_url ? encodeURI(img_url) : 'http://common.yiguanjia.club/images/logo.png',
  143. "share_url": url ? encodeURI(url) : 'http://common.yiguanjia.club',
  144. "share_app_id": app_id
  145. };
  146. var _callback = 'NativeCallback.share';
  147. helper.osProxy({
  148. android: function () {
  149. param['callback'] = _callback;
  150. var param_str = JSON.stringify(param);
  151. window.jsapi.doShare(param_str);
  152. },
  153. ios: function () {
  154. var param_str = JSON.stringify(param);
  155. window.location.href = 'http://callclient?method=doShare&param=' + param_str + '&callback=' + _callback;
  156. }
  157. });
  158. var callback = typeof (arguments[5]) == 'function' ? arguments[5] : null;
  159. this.shareCallback = callback;
  160. },
  161. //参数加密验证
  162. getSign: function (param, callback) {
  163. var that = this;
  164. for (var x in param) {
  165. param[x] = param[x].toString();
  166. }
  167. var param = {
  168. sign_json_string: param
  169. };
  170. var _callback = 'NativeCallback.getSign';
  171. helper.osProxy({
  172. android: function () {
  173. param['callback'] = _callback;
  174. var param_str = JSON.stringify(param);
  175. window.jsapi.sign(param_str);
  176. },
  177. //支付
  178. pay: function (params, callback) {
  179. var that = this;
  180. var param = {};
  181. var _callback = 'NativeCallback.pay';
  182. helper.osProxy({
  183. android: function () {
  184. param['charge'] = params.charge;
  185. param['callback'] = _callback;
  186. var param_str = JSON.stringify(param);
  187. window.jsapi.pay(param_str);
  188. },
  189. // ios 的可以无视了,本项目暂时用不到
  190. ios: function () {
  191. NativeDataAdapter.charge = JSON.stringify(params.charge);
  192. param['charge'] = 'NativeDataAdapter.charge';
  193. var param_str = JSON.stringify(param);
  194. window.location.href = 'http://callclient?method=pay&param=' + encodeURIComponent(param_str) + '&callback=' + _callback;
  195. },
  196. wx: function () {
  197. // 这个我就不知道说什么好了,判断当前环境为test的话,走ping++模拟支付
  198. if (config.test) {
  199. pingpp.createPayment(params.charge, function (result, err) {
  200. if (result == "success") {
  201. // 只有微信公众账号 wx_pub 支付成功的结果会在这里返回,其他的支付结果都会跳转到 extra 中对应的 URL。
  202. var res = {
  203. success: true
  204. };
  205. callback(res);
  206. } else if (result == "fail") {
  207. // charge 不正确或者微信公众账号支付失败时会在此处返回
  208. console.log(err);
  209. } else if (result == "cancel") {
  210. // 微信公众账号支付取消支付
  211. console.log(err);
  212. }
  213. });
  214. }else {
  215. // 当前为正式环境,通过url传值到微信支付授权的url,然后在该url下面进行微信支付
  216. /*
  217. * 参数说明:带 * 号的为微信支付用到的
  218. * appId:* 公众号名称,由商户传入
  219. * nonceStr:* 随机串
  220. * prepay:预付款ID
  221. * signType:* 微信签名方式:
  222. * timeStamp:* 时间戳,自1970年以来的秒数
  223. * paySign:* 微信签名
  224. * amount:实付金额
  225. * created:建立
  226. * body:订单名字
  227. * bookingTime:预约时间
  228. * */
  229. var option = params['charge'].credential.wx_pub; // 支付凭据
  230. var prepay = option["package"].replace('prepay_id=', '');
  231. var bookingTime = params.orderInfo.booking_time_str;
  232. location.href = '/webapp/o2o/module/pay/index.html?appId='
  233. + option.appId + '&nonceStr=' + option.nonceStr
  234. + '&package=' + prepay + '&signType='
  235. + option.signType + '&timeStamp='
  236. + option.timeStamp + '&paySign='
  237. + option.paySign + '&amount=' + params['charge'].amount
  238. + '&created=' + params['charge'].created + '&body='
  239. + params['charge'].body + '&bookingTime=' + bookingTime;
  240. }
  241. }
  242. });
  243. var callback = typeof (arguments[1]) == 'function' ? arguments[1] : null;
  244. this.payCallback = callback;
  245. },
  246. wx: function () {
  247. //目前加上参数,绕过验证,后面再加上相关的验证
  248. param['user_id'] = localStorage.getItem('xyhwxUserID');
  249. param['request_from'] = 'weixin';
  250. if (that.getSignCallback) {
  251. that.getSignCallback(param);
  252. }
  253. }
  254. });
  255. var callback = typeof (arguments[1]) == 'function' ? arguments[1] : null;
  256. this.getSignCallback = callback;
  257. },
  258. //支付
  259. pay: function (params, callback) {
  260. var that = this;
  261. var param = {};
  262. var _callback = 'NativeCallback.pay';
  263. helper.osProxy({
  264. android: function () {
  265. param['charge'] = params.charge;
  266. param['callback'] = _callback;
  267. var param_str = JSON.stringify(param);
  268. window.jsapi.pay(param_str);
  269. },
  270. ios: function () {
  271. NativeDataAdapter.charge = JSON.stringify(params.charge);
  272. param['charge'] = 'NativeDataAdapter.charge';
  273. var param_str = JSON.stringify(param);
  274. window.location.href = 'http://callclient?method=pay&param=' + encodeURIComponent(param_str) + '&callback=' + _callback;
  275. },
  276. wx: function () {
  277. if (config.test)
  278. {
  279. pingpp.createPayment(params.charge, function (result, err) {
  280. if (result == "success") {
  281. // 只有微信公众账号 wx_pub 支付成功的结果会在这里返回,其他的支付结果都会跳转到 extra 中对应的 URL。
  282. var res = {
  283. success: true
  284. };
  285. callback(res);
  286. } else if (result == "fail") {
  287. // charge 不正确或者微信公众账号支付失败时会在此处返回
  288. console.log(err);
  289. } else if (result == "cancel") {
  290. // 微信公众账号支付取消支付
  291. console.log(err);
  292. }
  293. });
  294. } else {
  295. var option = params['charge'].credential.wx_pub;
  296. var prepay = option["package"].replace('prepay_id=', '');
  297. var bookingTime = params.orderInfo.booking_time_str;
  298. var isSpecial = params['isSpecial']
  299. location.href = '/webapp/o2o/module/pay/index.html?appId='
  300. + option.appId + '&nonceStr=' + option.nonceStr
  301. + '&package=' + prepay + '&signType='
  302. + option.signType + '&timeStamp='
  303. + option.timeStamp + '&paySign='
  304. + option.paySign + '&amount=' + params['charge'].amount
  305. + '&created=' + params['charge'].created + '&body='
  306. + params['charge'].body + '&bookingTime=' + bookingTime
  307. + '&isSpecial=' + isSpecial;
  308. }
  309. }
  310. });
  311. var callback = typeof (arguments[1]) == 'function' ? arguments[1] : null;
  312. this.payCallback = callback;
  313. },
  314. //检测是否安装了微信
  315. isWxAppInstalled: function (callback) {
  316. var _callback = 'NativeCallback.isWxInstalled';
  317. var param = {};
  318. helper.osProxy({
  319. android: function () {
  320. param['callback'] = _callback;
  321. var param_str = JSON.stringify(param);
  322. window.jsapi.isWxAppInstalled(param_str);
  323. },
  324. ios: function () {
  325. var param_str = JSON.stringify(param);
  326. window.location.href = 'http://callclient?method=isWxAppInstalled&param=' + param_str + '&callback=' + _callback;
  327. }
  328. });
  329. var callback = typeof (arguments[0]) == 'function' ? arguments[0] : null;
  330. this.isWxAppInstalledCallback = callback;
  331. },
  332. //选择地址
  333. selectAddress: function (callback) {
  334. var _callback = 'NativeCallback.selectAddress';
  335. var param = {};
  336. helper.osProxy({
  337. android: function () {
  338. param['callback'] = _callback;
  339. var param_str = JSON.stringify(param);
  340. window.jsapi.selectAddress(param_str);
  341. },
  342. ios: function () {
  343. var param_str = JSON.stringify(param);
  344. window.location.href = 'http://callclient?method=selectAddress&param=' + param_str + '&callback=' + _callback;
  345. }/*,
  346. WX: function() {
  347. require('address').getList(function(res){
  348. if (typeof(that.selectAddressCallback) == 'function') {
  349. that.selectAddressCallback(res);
  350. }
  351. })
  352. }*/
  353. });
  354. var callback = typeof (arguments[0]) == 'function' ? arguments[0] : null;
  355. this.selectAddressCallback = callback;
  356. },
  357. //打开一个链接
  358. openURL: function (new_param) {
  359. if (config.appVersion < 2.6) {
  360. return false;
  361. }
  362. var param = {
  363. url: 'http://common.yiguanjia.club'
  364. };
  365. if (typeof new_param === 'undefined') {
  366. new_param = {};
  367. }
  368. for (var x in new_param) {
  369. if (param.hasOwnProperty(x)) {
  370. param[x] = new_param[x];
  371. }
  372. }
  373. helper.osProxy({
  374. android: function () {
  375. var param_str = JSON.stringify(param);
  376. window.jsapi.openURL(param_str);
  377. },
  378. ios: function () {
  379. var param_str = JSON.stringify(param);
  380. window.location.href = 'http://callclient?method=openURL&param=' + param_str;
  381. }
  382. });
  383. },
  384. //打开多个页面时页面之间通信
  385. postMessage: function (data) {
  386. if (config.appVersion < 2.6) {
  387. return false;
  388. }
  389. var _callback = 'NativeCallback.postMessage';
  390. helper.osProxy({
  391. android: function () {
  392. var param = {
  393. data: JSON.stringify(data),
  394. callback: _callback
  395. };
  396. var param_str = JSON.stringify(param);
  397. window.jsapi.postMessage(param_str);
  398. },
  399. ios: function () {
  400. var param = {
  401. data: data,
  402. callback: _callback
  403. };
  404. var param_str = JSON.stringify(param);
  405. window.location.href = 'http://callclient?method=postMessage&param=' + param_str;
  406. }
  407. });
  408. },
  409. //选择图片
  410. chooseImage: function (new_param, callback) {
  411. if (config.appVersion < 2.6) {
  412. return false;
  413. }
  414. var param = {
  415. sourceType: ['album', 'camera'],
  416. count: 9,
  417. clip: false,
  418. clipSize: 320
  419. };
  420. if (typeof new_param === 'undefined') {
  421. new_param = {};
  422. }
  423. for (var x in new_param) {
  424. if (param.hasOwnProperty(x)) {
  425. param[x] = new_param[x];
  426. }
  427. }
  428. var _callback = 'NativeCallback.chooseImage';
  429. helper.osProxy({
  430. android: function () {
  431. param['callback'] = _callback;
  432. var param_str = JSON.stringify(param);
  433. window.jsapi.chooseImage(param_str);
  434. },
  435. ios: function () {
  436. var param_str = JSON.stringify(param);
  437. window.location.href = 'http://callclient?method=chooseImage&param=' + param_str + '&callback=' + _callback;
  438. }
  439. });
  440. var callback = typeof (arguments[1]) == 'function' ? arguments[1] : null;
  441. this.chooseImageCallback = callback;
  442. },
  443. //预览图片
  444. previewImage: function (urls, current) {
  445. if (!config.isWX && config.appVersion < 2.6) {
  446. return false;
  447. }
  448. var param = {
  449. urls: urls,
  450. current: current,
  451. };
  452. var param_str = JSON.stringify(param);
  453. helper.osProxy({
  454. android: function () {
  455. window.jsapi.previewImage(param_str);
  456. },
  457. ios: function () {
  458. window.location.href = 'http://callclient?method=previewImage&param=' + param_str;
  459. },
  460. wx: function () {
  461. require(['../../common/js/jweixin-1.0.0'], function (wx) {
  462. wx.previewImage({
  463. current: current, // 当前显示图片的http链接
  464. urls: urls // 需要预览的图片http链接列表
  465. });
  466. });
  467. }
  468. });
  469. },
  470. //上传图片
  471. uploadImage: function (new_param, callback) {
  472. if (config.appVersion < 2.6) {
  473. return false;
  474. }
  475. var param = {
  476. localId: '',
  477. isShowProgressTips: true,
  478. };
  479. if (typeof new_param === 'undefined') {
  480. new_param = {};
  481. }
  482. for (var x in new_param) {
  483. if (param.hasOwnProperty(x)) {
  484. param[x] = new_param[x];
  485. }
  486. }
  487. var _callback = 'NativeCallback.uploadImage';
  488. helper.osProxy({
  489. android: function () {
  490. param['callback'] = _callback;
  491. var param_str = JSON.stringify(param);
  492. window.jsapi.uploadImage(param_str);
  493. },
  494. ios: function () {
  495. var param_str = JSON.stringify(param);
  496. window.location.href = 'http://callclient?method=uploadImage&param=' + param_str + '&callback=' + _callback;
  497. }
  498. });
  499. var callback = typeof (arguments[1]) == 'function' ? arguments[1] : null;
  500. this.uploadImageCallbacks[param.localId] = callback;
  501. },
  502. // 选择宠物
  503. selectPetType: function (callback) {
  504. var _callback = 'NativeCallback.selectPetType';
  505. var param = {};
  506. helper.osProxy({
  507. android: function () {
  508. param['callback'] = _callback;
  509. var param_str = JSON.stringify(param);
  510. window.jsapi.selectPetType(param_str);
  511. },
  512. ios: function () {
  513. var param_str = JSON.stringify(param);
  514. window.location.href = 'http://callclient?method=selectPetType&param=' + param_str + '&callback=' + _callback;
  515. }
  516. });
  517. var callback = typeof (arguments[0]) == 'function' ? arguments[0] : null;
  518. this.selectPetTypeCallback = callback;
  519. },
  520. // 拨打电话
  521. call: function (telephone) {
  522. var that = this;
  523. helper.osProxy({
  524. android: function () {
  525. if (config.appVersion < '2.2') {
  526. //无法调用拨号,弹出
  527. $(document).trigger('spa:openpanel', ['simpleAlert', {
  528. message: '客服热线:' + telephone
  529. }]);
  530. } else {
  531. var param = {
  532. telephone: telephone
  533. };
  534. var param_str = JSON.stringify(param);
  535. window.jsapi.call(param_str);
  536. }
  537. },
  538. ios: function () {
  539. window.location.href = 'tel:' + telephone;
  540. }
  541. });
  542. },
  543. //ios
  544. //开关滑动返回
  545. switchPopGesture: function (flag) {
  546. var param = {
  547. enable: flag
  548. };
  549. helper.osProxy({
  550. ios: function () {
  551. var param_str = JSON.stringify(param);
  552. window.location.href = 'http://callclient?method=switchPopGesture&param=' + param_str;
  553. }
  554. });
  555. },
  556. //安卓
  557. //代理物理返回按钮
  558. delegateBackButton: function (flag, callback) {
  559. var param = {
  560. enable: flag,
  561. callback: 'NativeCallback.back'
  562. };
  563. helper.osProxy({
  564. android: function () {
  565. var param_str = JSON.stringify(param);
  566. window.jsapi.delegateBackButton(param_str);
  567. }
  568. });
  569. },
  570. //注册键盘事件,由于安卓回调有问题,所以改为js setInterval自定义检测
  571. registerEvent: function (enable) {
  572. if (!enable) {
  573. if (this.keyboardEventTimer != 0) {
  574. clearInterval(this.keyboardEventTimer);
  575. }
  576. return;
  577. }
  578. var that = this;
  579. this.keyboardIsOpen = false;
  580. this.keyboardIsClose = false;
  581. helper.osProxy({
  582. android: function () {
  583. that.keyboardEventTimer = setInterval(function () {
  584. if (that.originalHeight > document.body.scrollHeight) {
  585. if (!that.keyboardIsOpen) {
  586. that.keyboardIsOpen = true;
  587. that.keyboardIsClose = false;
  588. $('input, textarea').trigger('openKeyboard');
  589. }
  590. } else {
  591. if (!that.keyboardIsClose) {
  592. that.keyboardIsClose = true;
  593. that.keyboardIsOpen = false;
  594. $('input, textarea').trigger('closeKeyboard');
  595. }
  596. }
  597. }, 50);
  598. }
  599. });
  600. }
  601. };
  602. /*
  603. * 回调类
  604. */
  605. function CallbackApi() {
  606. if (typeof CallbackApi.instance === 'object') {
  607. return CallbackApi.instance;
  608. }
  609. CallbackApi.instance = this;
  610. }
  611. CallbackApi.prototype = {
  612. formatNativeParam: function (res) {
  613. var f_res = helper.osProxy({
  614. android: function () {
  615. var reg = new RegExp('(\r\n|\r|\n)', 'g');
  616. res = JSON.stringify(res).replace(reg, '');
  617. return JSON.parse(res);
  618. },
  619. ios: function () {
  620. if (res && res.hasOwnProperty('success')) {
  621. if (res.success == '1') {
  622. res.success = true;
  623. } else {
  624. res.success = false;
  625. }
  626. }
  627. return res;
  628. }
  629. });
  630. return f_res;
  631. },
  632. getUserInfo: function (res) {
  633. var f_res = this.formatNativeParam(res);
  634. var native_api = new NativeApi();
  635. if (typeof (native_api.getUserInfoCallback) == 'function') {
  636. native_api.getUserInfoCallback(f_res);
  637. }
  638. },
  639. login: function (res) {
  640. //fix by wangyang
  641. //ios客户端登陆回调的通知在2.0有点早,改为延时0.1s再重新获取一次用户信息
  642. var f_res = this.formatNativeParam(res);
  643. var nativeApi = new NativeApi();
  644. if (nativeApi.loginCallback != null) {
  645. setTimeout(function () {
  646. nativeApi.getUserInfo(nativeApi.loginCallback);
  647. nativeApi.loginCallback(f_res);
  648. }, 100);
  649. }
  650. },
  651. share: function (res) {
  652. var f_res = this.formatNativeParam(res);
  653. var native_api = new NativeApi();
  654. if (typeof (native_api.shareCallback) == 'function') {
  655. native_api.shareCallback(f_res);
  656. }
  657. },
  658. getSign: function (res) {
  659. var f_res = this.formatNativeParam(res);
  660. var native_api = new NativeApi();
  661. if (typeof (native_api.getSignCallback) == 'function') {
  662. native_api.getSignCallback(f_res);
  663. }
  664. },
  665. pay: function (res) {
  666. var f_res = this.formatNativeParam(res);
  667. if (f_res.success) {
  668. f_res.message = '支付成功';
  669. } else {
  670. helper.osProxy({
  671. android: function () {
  672. if (config.appVersion < '2.2') {
  673. if (f_res.message == 'user_cancelled') {
  674. f_res.message = '取消支付';
  675. } else {
  676. f_res.message = '支付异常,请稍后再试';
  677. }
  678. } else {
  679. switch (f_res.error_code) {
  680. case 'fail':
  681. f_res.message = '支付失败';
  682. break;
  683. case 'cancel':
  684. f_res.message = '取消支付';
  685. break;
  686. default:
  687. f_res.message = '支付异常,请稍后再试';
  688. break;
  689. }
  690. }
  691. },
  692. ios: function () {
  693. if (f_res.error_code == 5) {
  694. f_res.message = '取消支付';
  695. } else {
  696. f_res.message = '支付异常,请稍后再试';
  697. }
  698. }
  699. });
  700. }
  701. var native_api = new NativeApi();
  702. if (typeof (native_api.payCallback) == 'function') {
  703. native_api.payCallback(f_res);
  704. }
  705. },
  706. selectAddress: function (res) {
  707. var f_res = this.formatNativeParam(res);
  708. var native_api = new NativeApi();
  709. helper.osProxy({
  710. android: function () {
  711. //2.1返回的data是json字符串,特殊处理一下
  712. if (f_res.success && typeof (f_res.data) == 'string') {
  713. f_res.data = JSON.parse(f_res.data);
  714. }
  715. }
  716. });
  717. if (typeof (native_api.selectAddressCallback) == 'function') {
  718. native_api.selectAddressCallback(f_res);
  719. }
  720. },
  721. selectPetType: function (res) {
  722. var f_res = this.formatNativeParam(res);
  723. var native_api = new NativeApi();
  724. if (typeof (native_api.selectPetTypeCallback) == 'function') {
  725. native_api.selectPetTypeCallback(f_res);
  726. }
  727. },
  728. chooseImage: function (res) {
  729. var f_res = this.formatNativeParam(res);
  730. var native_api = new NativeApi();
  731. if (typeof (native_api.chooseImageCallback) == 'function') {
  732. native_api.chooseImageCallback(f_res);
  733. }
  734. },
  735. uploadImage: function (res) {
  736. var f_res = this.formatNativeParam(res);
  737. var native_api = new NativeApi();
  738. if (res.data.localId && typeof (native_api.uploadImageCallbacks[res.data.localId]) == 'function') {
  739. native_api.uploadImageCallbacks[res.data.localId](f_res);
  740. }
  741. },
  742. isWxInstalled: function (res) {
  743. var f_res = this.formatNativeParam(res);
  744. var native_api = new NativeApi();
  745. if (typeof (native_api.isWxAppInstalledCallback) == 'function') {
  746. native_api.isWxAppInstalledCallback(f_res);
  747. }
  748. },
  749. //以下回调为js自定义事件,注意,依赖jquery的trigger
  750. postMessage: function (res) {
  751. var f_res = this.formatNativeParam(res);
  752. f_res = helper.osProxy({
  753. android: function () {
  754. f_res.data = JSON.parse(f_res.data);
  755. return f_res;
  756. },
  757. ios: function () {
  758. return f_res;
  759. }
  760. });
  761. require(['$'], function ($) {
  762. $(document).trigger('postMessage', f_res);
  763. });
  764. },
  765. back: function () {
  766. require(['$'], function ($) {
  767. $(document).trigger('tapBackButton');
  768. });
  769. }
  770. };
  771. /*
  772. * 传递数据类,用于ios,某些复杂的json数据不适合通过url传递
  773. * 换一种思路,通过提供一个JS类给OC,然后OC调用js方法反查数据
  774. */
  775. function NativeDataCache() {
  776. if (typeof NativeDataCache.instance === 'object') {
  777. return NativeDataCache.instance;
  778. }
  779. NativeDataCache.instance = this;
  780. NativeDataCache.charge = '';
  781. }
  782. /**
  783. * android websocket支持
  784. */
  785. helper.osProxy({
  786. android: function () {
  787. if (typeof(WebSocketFactory) == 'undefined') {
  788. return false;
  789. }
  790. // window object
  791. var global = window;
  792. // WebSocket Object. All listener methods are cleaned up!
  793. var WebSocket = global.WebSocket = function (url) {
  794. // get a new websocket object from factory (check com.strumsoft.websocket.WebSocketFactory.java)
  795. this.socket = WebSocketFactory.getInstance(url);
  796. // store in registry
  797. if (this.socket) {
  798. WebSocket.store[this.socket.getId()] = this;
  799. } else {
  800. throw new Error('Websocket instantiation failed! Address might be wrong.');
  801. }
  802. };
  803. // private property
  804. WebSocket._keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  805. // private method for decoding base64
  806. WebSocket._decode = function (input) {
  807. var output = "";
  808. var chr1, chr2, chr3;
  809. var enc1, enc2, enc3, enc4;
  810. var i = 0;
  811. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  812. while (i < input.length) {
  813. enc1 = this._keyStr.indexOf(input.charAt(i++));
  814. enc2 = this._keyStr.indexOf(input.charAt(i++));
  815. enc3 = this._keyStr.indexOf(input.charAt(i++));
  816. enc4 = this._keyStr.indexOf(input.charAt(i++));
  817. chr1 = (enc1 << 2) | (enc2 >> 4);
  818. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  819. chr3 = ((enc3 & 3) << 6) | enc4;
  820. output = output + String.fromCharCode(chr1);
  821. if (enc3 != 64) {
  822. output = output + String.fromCharCode(chr2);
  823. }
  824. if (enc4 != 64) {
  825. output = output + String.fromCharCode(chr3);
  826. }
  827. }
  828. output = this._utf8_decode(output);
  829. return output;
  830. }
  831. // private method for UTF-8 decoding
  832. WebSocket._utf8_decode = function (utftext) {
  833. var string = "";
  834. var i = 0;
  835. var c = c1 = c2 = 0;
  836. while (i < utftext.length) {
  837. c = utftext.charCodeAt(i);
  838. if (c < 128) {
  839. string += String.fromCharCode(c);
  840. i++;
  841. } else if ((c > 191) && (c < 224)) {
  842. c2 = utftext.charCodeAt(i + 1);
  843. string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
  844. i += 2;
  845. } else {
  846. c2 = utftext.charCodeAt(i + 1);
  847. c3 = utftext.charCodeAt(i + 2);
  848. string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
  849. i += 3;
  850. }
  851. }
  852. return string;
  853. }
  854. // storage to hold websocket object for later invokation of event methods
  855. WebSocket.store = {};
  856. // static event methods to call event methods on target websocket objects
  857. WebSocket.onmessage = function (evt) {
  858. WebSocket.store[evt._target]['onmessage'].call(global, this._decode(evt._data));
  859. }
  860. WebSocket.onopen = function (evt) {
  861. WebSocket.store[evt._target]['onopen'].call(global, evt);
  862. }
  863. WebSocket.onclose = function (evt) {
  864. WebSocket.store[evt._target]['onclose'].call(global, evt);
  865. }
  866. WebSocket.onerror = function (evt) {
  867. WebSocket.store[evt._target]['onerror'].call(global, evt);
  868. }
  869. // instance event methods
  870. WebSocket.prototype.send = function (data) {
  871. this.socket.send(data);
  872. }
  873. WebSocket.prototype.close = function () {
  874. this.socket.close();
  875. }
  876. WebSocket.prototype.getReadyState = function () {
  877. this.socket.getReadyState();
  878. }
  879. ///////////// Must be overloaded
  880. WebSocket.prototype.onopen = function () {
  881. throw new Error('onopen not implemented.');
  882. };
  883. // alerts message pushed from server
  884. WebSocket.prototype.onmessage = function (msg) {
  885. throw new Error('onmessage not implemented.');
  886. };
  887. // alerts message pushed from server
  888. WebSocket.prototype.onerror = function (msg) {
  889. throw new Error('onerror not implemented.');
  890. };
  891. // alert close event
  892. WebSocket.prototype.onclose = function () {
  893. throw new Error('onclose not implemented.');
  894. };
  895. }
  896. })
  897. NativeDataAdapter = new NativeDataCache();
  898. NativeCallback = new CallbackApi();
  899. return new NativeApi();
  900. })