app.js 12.6 KB
Newer Older
D
devil_gong 已提交
1 2
App({
  data: {
D
devil_gong 已提交
3 4 5
    // 用户登录缓存key
    cache_user_login_key: "cache_user_login_key",
    
D
devil_gong 已提交
6 7 8 9 10 11 12 13 14 15 16 17
    // 用户信息缓存key
    cache_user_info_key: "cache_shop_user_info_key",

    // 用户站点信息缓存key
    cache_user_merchant_key: "cache_shop_user_merchant_key",

    // 设备信息缓存key
    cache_system_info_key: "cache_shop_system_info_key",

    // 用户地址选择缓存key
    cache_buy_user_address_select_key: "cache_buy_user_address_select_key",

18
    // 启动参数缓存key
D
devil_gong 已提交
19 20 21 22 23 24 25 26 27 28 29
    cache_launch_info_key: "cache_shop_launch_info_key",

    // 默认用户头像
    default_user_head_src: "/images/default-user.png",

    // 成功圆形提示图片
    default_round_success_icon: "/images/default-round-success-icon.png",

    // 错误圆形提示图片
    default_round_error_icon: "/images/default-round-error-icon.png",

G
gongfuxiang 已提交
30 31 32 33 34 35 36
    // tabbar页面
    tabbar_pages: [
      "index",
      "goods-category",
      "cart",
      "user",
    ],
D
devil_gong 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

    // 页面标题
    common_pages_title: {
      "goods_search": "商品搜索",
      "goods_detail": "商品详情",
      "goods_attribute": "属性",
      "user_address": "我的地址",
      "user_address_save_add": "新增地址",
      "user_address_save_edit": "编辑地址",
      "buy": "订单确认",
      "user_order": "我的订单",
      "user_order_detail": "订单详情",
      "user_favor": "我的收藏",
      "answer_form": "留言",
      "answer_list": "问答",
      "user_answer_list": "我的留言",
      "user": "用户中心",
      "goods_category": "分类",
      "cart": "购物车",
      "message": "消息",
      "user_integral": "我的积分",
      "user_goods_browse": "我的足迹",
D
devil_gong 已提交
59
      "goods_comment": "商品评论",
D
Devil 已提交
60
      "user_orderaftersale": "退款/售后",
D
Devil 已提交
61
      "user_orderaftersale_detail": "订单售后",
D
devil_gong 已提交
62
      "user_order_comments": "订单评论",
D
devil_gong 已提交
63 64 65
    },

    // 请求地址
G
gongfuxiang 已提交
66
    request_url: "{{request_url}}",
D
Devil 已提交
67
     request_url: 'http://tp5-dev.com/',
D
devil_gong 已提交
68
     request_url: 'https://test.shopxo.net/',
D
devil_gong 已提交
69 70 71 72 73 74 75 76 77 78

    // 基础信息
    application_title: "{{application_title}}",
    application_describe: "{{application_describe}}",
  },

  /**
   * 小程序初始化
   */
  onLaunch(options) {
79 80 81
    // 启动参数处理
    options = this.launch_params_handle(options);

D
devil_gong 已提交
82 83 84
    // 设置设备信息
    this.set_system_info();

85 86 87 88 89
    // 缓存启动参数
    wx.setStorage({
      key: this.data.cache_launch_info_key,
      data: options
    });
D
devil_gong 已提交
90 91 92
  },

  /**
93
   * 启动参数处理
D
devil_gong 已提交
94
   */
95 96 97 98
  launch_params_handle(params) {
    // 启动参数处理
    if ((params.query || null) != null) {
      params = params.query;
D
devil_gong 已提交
99
    }
100 101
    if ((params.scene || null) != null) {
      params = this.url_params_to_json(decodeURIComponent(params.scene));
D
devil_gong 已提交
102
    }
103
    return params;
D
devil_gong 已提交
104 105 106 107 108 109
  },

  /**
   * 获取设备信息
   */
  get_system_info() {
D
devil_gong 已提交
110 111
    let system_info = wx.getStorageSync(this.data.cache_system_info_key) || null;
    if (system_info == null) {
D
devil_gong 已提交
112 113
      return this.set_system_info();
    }
D
devil_gong 已提交
114
    return system_info;
D
devil_gong 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
  },

  /**
   * 设置设备信息
   */
  set_system_info() {
    var system_info = wx.getSystemInfoSync();
    wx.setStorage({
      key: this.data.cache_system_info_key,
      data: system_info
    });
    return system_info;
  },

  /**
  /**
   * 请求地址生成
   */
  get_request_url(a, c, m, params) {
    a = a || "index";
    c = c || "index";
    m = m || "api";
    params = params || "";
    if (params != "" && params.substr(0, 1) != "&") {
      params = "&" + params;
    }
D
devil_gong 已提交
141
    var user = this.get_user_cache_info();
D
devil_gong 已提交
142
    var token = (user == false) ? '' : user.token || '';
D
devil_gong 已提交
143 144 145
    return (
      this.data.request_url +
      "index.php?s=/" + m + "/" + c + "/" + a +
D
devil_gong 已提交
146 147 148
      "&application=app&application_client_type=weixin" +
      "&token=" +
      token +
D
devil_gong 已提交
149 150 151 152 153 154 155 156
      "&ajax=ajax" +
      params
    );
  },

  /**
   * 从缓存获取用户信息
   */
D
devil_gong 已提交
157
  get_user_cache_info() {
D
devil_gong 已提交
158 159
    let user = wx.getStorageSync(this.data.cache_user_info_key) || null;
    if (user == null) {
D
devil_gong 已提交
160 161 162 163 164 165 166 167 168
      return false;
    }
    return user;
  },

  /**
   * 用户登录
   * object     回调操作对象
   * method     回调操作对象的函数
G
gongfuxiang 已提交
169
   * auth_data  授权数据
D
devil_gong 已提交
170
   */
G
gongfuxiang 已提交
171
  user_auth_login(object, method, auth_data) {
172
    wx.showLoading({ title: "授权中..." });
D
devil_gong 已提交
173
    var self = this;
D
devil_gong 已提交
174 175
    wx.checkSession({
      success: function () {
D
devil_gong 已提交
176
        var openid = wx.getStorageSync(self.data.cache_user_login_key) || null;
D
devil_gong 已提交
177
        if (openid == null)
D
devil_gong 已提交
178
        {
D
devil_gong 已提交
179
          self.user_login(object, method, auth_data);
D
devil_gong 已提交
180
        } else {
D
devil_gong 已提交
181
          self.get_user_login_info(object, method, openid, auth_data);
D
devil_gong 已提交
182 183 184
        }
      },
      fail: function () {
D
devil_gong 已提交
185
        self.user_login(object, method, auth_data);
D
devil_gong 已提交
186 187 188 189 190 191 192 193
      }
    });
  },

  /**
   * 用户登录
   * object     回调操作对象
   * method     回调操作对象的函数
G
gongfuxiang 已提交
194
   * auth_data  授权数据
D
devil_gong 已提交
195
   */
G
gongfuxiang 已提交
196
  user_login(object, method, auth_data) {
D
devil_gong 已提交
197
    var self = this;
D
devil_gong 已提交
198 199 200 201
    wx.login({
      success: (res) => {
        if (res.code) {
          wx.request({
D
devil_gong 已提交
202
            url: self.get_request_url('wechatuserauth', 'user'),
D
devil_gong 已提交
203 204 205 206 207
            method: 'POST',
            data: { authcode: res.code },
            dataType: 'json',
            header: { 'content-type': 'application/x-www-form-urlencoded' },
            success: (res) => {
G
微信  
gongfuxiang 已提交
208
              if (res.data.code == 0) {
D
devil_gong 已提交
209
                wx.setStorage({
D
devil_gong 已提交
210
                  key: self.data.cache_user_login_key,
D
devil_gong 已提交
211 212
                  data: res.data.data
                });
D
devil_gong 已提交
213
                self.get_user_login_info(object, method, res.data.data, auth_data);
D
devil_gong 已提交
214 215
              } else {
                wx.hideLoading();
D
devil_gong 已提交
216
                self.showToast(res.data.msg);
D
devil_gong 已提交
217 218 219 220
              }
            },
            fail: () => {
              wx.hideLoading();
D
devil_gong 已提交
221
              self.showToast('服务器请求出错');
D
devil_gong 已提交
222 223 224 225 226 227
            },
          });
        }
      },
      fail: (e) => {
        wx.hideLoading();
D
devil_gong 已提交
228
        self.showToast('授权失败');
D
devil_gong 已提交
229 230 231 232 233 234 235 236 237
      }
    });
  },

  /**
   * 获取用户授权信息
   * object     回调操作对象
   * method     回调操作对象的函数
   * openid     用户openid
G
gongfuxiang 已提交
238
   * auth_data  授权数据
D
devil_gong 已提交
239
   */
G
gongfuxiang 已提交
240
  get_user_login_info(object, method, openid, auth_data) {
G
gongfuxiang 已提交
241
    // 邀请人参数
D
devil_gong 已提交
242
    var params = wx.getStorageSync(this.data.cache_launch_info_key) || null;
243
    var referrer = (params == null) ? 0 : (params.referrer || 0);
G
gongfuxiang 已提交
244

G
gongfuxiang 已提交
245
    // 远程解密数据
D
devil_gong 已提交
246
    var self = this;
G
gongfuxiang 已提交
247
    wx.request({
D
devil_gong 已提交
248
      url: self.get_request_url('wechatuserinfo', 'user'),
G
gongfuxiang 已提交
249
      method: 'POST',
G
gongfuxiang 已提交
250 251 252 253 254 255
      data: {
        "encrypted_data": auth_data.encryptedData,
        "iv": auth_data.iv,
        "openid": openid,
        "referrer": referrer
      },
G
gongfuxiang 已提交
256 257 258 259 260 261
      dataType: 'json',
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      success: (res) => {
        wx.hideLoading();
        if (res.data.code == 0) {
          wx.setStorage({
D
devil_gong 已提交
262
            key: self.data.cache_user_info_key,
G
gongfuxiang 已提交
263 264 265 266 267 268 269
            data: res.data.data,
            success: (res) => {
              if (typeof object === 'object' && (method || null) != null) {
                object[method]();
              }
            },
            fail: () => {
D
devil_gong 已提交
270
              self.showToast('用户信息缓存失败');
D
devil_gong 已提交
271
            }
G
gongfuxiang 已提交
272 273
          });
        } else {
D
devil_gong 已提交
274
          self.showToast(res.data.msg);
G
gongfuxiang 已提交
275
        }
D
devil_gong 已提交
276
      },
G
gongfuxiang 已提交
277
      fail: () => {
D
devil_gong 已提交
278
        wx.hideLoading();
D
devil_gong 已提交
279
        self.showToast('服务器请求出错');
G
gongfuxiang 已提交
280
      },
D
devil_gong 已提交
281 282 283 284 285 286 287 288 289 290
    });
  },

  /**
   * 字段数据校验
   * data           待校验的数据, 一维json对象
   * validation     待校验的字段, 格式 [{fields: 'mobile', msg: '请填写手机号码'}, ...]
  */
  fields_check(data, validation) {
    for (var i in validation) {
D
Devil 已提交
291 292 293 294 295
      var temp_value = data[validation[i]["fields"]];
      var temp_is_can_zero = validation[i]["is_can_zero"] || null;

      if ((temp_value == undefined || temp_value.length == 0 || temp_value == -1) || (temp_is_can_zero == null && temp_value == 0)
      ) {
D
devil_gong 已提交
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
        this.showToast(validation[i]['msg']);
        return false;
      }
    }
    return true;
  },

  /**
   * 获取当前时间戳
   */
  get_timestamp() {
    return parseInt(new Date().getTime() / 1000);
  },

  /**
   * 获取日期
   * format       日期格式(默认 yyyy-MM-dd h:m:s)
   * timestamp    时间戳(默认当前时间戳)
   */
  get_date(format, timestamp) {
    var d = new Date((timestamp || this.get_timestamp()) * 1000);
    var date = {
      "M+": d.getMonth() + 1,
      "d+": d.getDate(),
      "h+": d.getHours(),
      "m+": d.getMinutes(),
      "s+": d.getSeconds(),
      "q+": Math.floor((d.getMonth() + 3) / 3),
      "S+": d.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
      format = format.replace(RegExp.$1, (d.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
      if (new RegExp("(" + k + ")").test(format)) {
        format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
      }
    }
    return format;
  },

  /**
   * 获取对象、数组的长度、元素个数
   * obj      要计算长度的元素(object、array、string)
   */
  get_length(obj) {
    var obj_type = typeof obj;
    if (obj_type == "string") {
      return obj.length;
    } else if (obj_type == "object") {
      var obj_len = 0;
      for (var i in obj) {
        obj_len++;
      }
      return obj_len;
    }
    return false;
  },

  /**
   * 价格保留两位小数
   * price      价格保留两位小数
   */
  price_two_decimal(x) {
    var f_x = parseFloat(x);
    if (isNaN(f_x)) {
      return 0;
    }
    var f_x = Math.round(x * 100) / 100;
    var s_x = f_x.toString();
    var pos_decimal = s_x.indexOf('.');
    if (pos_decimal < 0) {
      pos_decimal = s_x.length;
      s_x += '.';
    }
    while (s_x.length <= pos_decimal + 2) {
      s_x += '0';
    }
    return s_x;
  },

G
gongfuxiang 已提交
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
  /**
   * 当前地址是否存在tabbar中
   */
  is_tabbar_pages(url) {
    if (url.indexOf("?") == -1)
    {
      var all = url.split("/");
    } else {
      var temp_str = url.split("?");
      var all = temp_str[0].split("/");
    }
    if (all.length <= 0)
    {
      return false;
    }

    var temp_tabbar_pages = this.data.tabbar_pages;
    for (var i in temp_tabbar_pages)
    {
      if (temp_tabbar_pages[i] == all[all.length-1])
      {
        return true;
      }
    }
    return false;
  },

G
wechat  
gongfuxiang 已提交
404 405 406 407 408 409 410 411 412 413
  /**
   * 事件操作
   */
  operation_event(e) {
    var value = e.currentTarget.dataset.value || null;
    var type = parseInt(e.currentTarget.dataset.type);
    if (value != null) {
      switch (type) {
        // web
        case 0:
G
gongfuxiang 已提交
414
          wx.navigateTo({ url: '/pages/web-view/web-view?url=' + encodeURIComponent(value) });
G
wechat  
gongfuxiang 已提交
415 416 417 418
          break;

        // 内部页面
        case 1:
G
gongfuxiang 已提交
419 420 421 422 423 424
          if (this.is_tabbar_pages(value))
          {
            wx.switchTab({ url: value });
          } else {
            wx.navigateTo({ url: value });
          }
G
wechat  
gongfuxiang 已提交
425 426 427 428 429 430 431 432 433 434 435
          break;

        // 跳转到外部小程序
        case 2:
          wx.navigateToMiniProgram({ appId: value });
          break;

        // 跳转到地图查看位置
        case 3:
          var values = value.split('|');
          if (values.length != 4) {
D
devil_gong 已提交
436
            this.showToast('事件值格式有误');
G
wechat  
gongfuxiang 已提交
437 438 439 440 441 442 443 444 445 446 447 448 449
            return false;
          }

          wx.openLocation({
            name: values[0],
            address: values[1],
            longitude: values[2],
            latitude: values[3],
          });
          break;

        // 拨打电话
        case 4:
G
gongfuxiang 已提交
450
          wx.makePhoneCall({ phoneNumber: value });
G
wechat  
gongfuxiang 已提交
451 452 453 454 455
          break;
      }
    }
  },

D
devil_gong 已提交
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
  /**
   * 默认弱提示方法
   * msg    [string]  提示信息
   * status [string]  状态 默认error [正确success, 错误error]
   */
  showToast(msg, status)
  {
    if ((status || 'error') == 'success')
    {
      wx.showToast({
        title: msg,
        duration: 3000
      });
    } else {
      wx.showToast({
        image: '/images/default-toast-error.png',
        title: msg,
        duration: 3000
      });
    }
D
1.6  
devil_gong 已提交
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
  },

  /**
   * 是否需要登录
   * 是否需要绑定手机号码
   */
  user_is_need_login(user) {
    // 用户信息是否正确
    if (user == false)
    {
      return true;
    }

    // 是否需要绑定手机号码
    if ((user.is_mandatory_bind_mobile || 0) == 1)
    {
      if ((user.mobile || null) == null)
      {
        return true;
      }
    }
    
    return false;
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
  },

  /**
   * url参数转json对象
   */
  url_params_to_json(url_params) {
    var json = new Object();
    if ((url_params || null) != null)
    {
      var arr = url_params.split('&');
      for(var i = 0; i<arr.length; i++) {
      var temp = arr[i].split('=');
        json[temp[0]] = temp[1]
      }
    }
    return json;
D
devil_gong 已提交
515 516 517
  }

});