native.js 32 KB

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