app.js 16.8 KB
Newer Older
D
v1.2.0  
devil_gong 已提交
1 2
App({
  data: {
D
1.6  
devil_gong 已提交
3 4 5
    // 用户登录缓存key
    cache_user_login_key: "cache_user_login_key",

D
v1.2.0  
devil_gong 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
    // 用户信息缓存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",

    // 用户传入信息缓存key
    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
v1.2.0  
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": "我的足迹",
G
gongfuxiang 已提交
59
      "goods_comment": "商品评论",
D
Devil 已提交
60 61
      "user_orderaftersale": "退款/售后",
      "user_orderaftersale_detail": "订单售后",
D
devil_gong 已提交
62
      "user_order_comments": "订单评论",
D
devil_gong 已提交
63 64
      "coupon": "领劵中心",
      "user_coupon": "优惠劵",
D
devil_gong 已提交
65
      "extraction_address": "自提地址",
D
v1.2.0  
devil_gong 已提交
66 67 68
    },

    // 请求地址
D
devil_gong 已提交
69
    request_url: "{{request_url}}",
D
devil_gong 已提交
70 71
     request_url: 'http://tp5-dev.com/',
     request_url: 'http://dev.shopxo.net/',
D
v1.2.0  
devil_gong 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 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 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180

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

  /**
   * 小程序初始化
   */
  onLaunch(options) {
    // 设置设备信息
    this.set_system_info();

    // 参数缓存
    my.setStorage({
      key: this.data.cache_launch_info_key,
      data: options.query || null
    });
    // 启动query参数处理
    this.startup_query(options.query);
  },

  /**
   * 启动query参数处理
   */
  startup_query(params) {
    // 没有启动参数则返回
    if ((params || null) == null) {
      return false;
    }

    // 启动处理类型
    var type = params.type || null;
    switch (type) {
      // type=page
      case "page":
        // 页面
        var page = params.page || null;

        // 参数名
        var params_field = params.params_field || null;

        // 参数值
        var params_value = params.params_value || null;

        // 页面跳转
        if(page != null)
        {
          my.navigateTo({
            url: "/pages/" + page + "/" + page + "?" + params_field + "=" + params_value
          });
        }
        break;

      // type=view
      case "view" :
        var url = params.url || null;

        // 页面跳转
        if(url != null)
        {
          my.navigateTo({
            url: '/pages/web-view/web-view?url='+url
          });
        }
        break;

      // 默认
      default:
        break;
    }
  },

  /**
   * 获取设备信息
   */
  get_system_info() {
    let system_info = my.getStorageSync({
      key: this.data.cache_system_info_key
    });
    if ((system_info.data || null) == null) {
      return this.set_system_info();
    }
    return system_info.data;
  },

  /**
   * 设置设备信息
   */
  set_system_info() {
    var system_info = my.getSystemInfoSync();
    my.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
1.6  
devil_gong 已提交
181
    var user = this.get_user_cache_info();
G
gongfuxiang 已提交
182
    var token = (user == false) ? '' : user.token || '';
D
v1.2.0  
devil_gong 已提交
183 184 185
    return (
      this.data.request_url +
      "index.php?s=/" + m + "/" + c + "/" + a +
D
devil_gong 已提交
186 187 188
      "&application=app&application_client_type=alipay" +
      "&token=" +
      token +
D
v1.2.0  
devil_gong 已提交
189 190 191 192 193 194 195 196 197 198 199
      "&ajax=ajax" +
      params
    );
  },

  /**
   * 获取用户信息,信息不存在则唤醒授权
   * object     回调操作对象
   * method     回调操作对象的函数
   * return     有用户数据直接返回, 则回调调用者
   */
D
1.6  
devil_gong 已提交
200 201
  get_user_info(object, method) {
    var user = this.get_user_cache_info();
D
v1.2.0  
devil_gong 已提交
202 203
    if (user == false) {
      // 唤醒用户授权
D
devil_gong 已提交
204
      this.user_login(object, method);
D
v1.2.0  
devil_gong 已提交
205 206 207 208 209 210 211 212 213 214

      return false;
    } else {
      return user;
    }
  },

  /**
   * 从缓存获取用户信息
   */
D
1.6  
devil_gong 已提交
215
  get_user_cache_info() {
D
v1.2.0  
devil_gong 已提交
216 217 218 219 220 221 222 223 224
    var user = my.getStorageSync({ key: this.data.cache_user_info_key });
    if ((user.data || null) == null) {
      return false;
    }
    return user.data;
  },

  /**
   * 用户授权
D
devil_gong 已提交
225 226
   * object     回调操作对象
   * method     回调操作对象的函数
D
v1.2.0  
devil_gong 已提交
227
   */
D
devil_gong 已提交
228
  user_login(object, method) {
G
gongfuxiang 已提交
229 230 231
    var openid = my.getStorageSync({key: this.data.cache_user_login_key});
    if ((openid.data || null) == null)
    {
D
devil_gong 已提交
232
      var self = this;
G
gongfuxiang 已提交
233 234 235 236 237 238 239 240 241
      // 加载loding
      my.showLoading({ content: "授权中..." });

      // 请求授权接口
      my.getAuthCode({
        scopes: "auth_base",
        success: res => {
          if (res.authCode) {
            my.request({
D
devil_gong 已提交
242
              url: self.get_request_url("alipayuserauth", "user"),
G
gongfuxiang 已提交
243 244 245 246 247 248 249
              method: "POST",
              data: {authcode: res.authCode},
              dataType: "json",
              headers: { 'content-type': 'application/x-www-form-urlencoded' },
              success: res => {
                my.hideLoading();
                if (res.data.code == 0) {
D
devil_gong 已提交
250 251 252 253
                  var data = res.data.data;
                  if((data.is_alipay_user_exist || 0) == 1)
                  {
                    my.setStorage({
D
devil_gong 已提交
254
                      key: self.data.cache_user_info_key,
D
devil_gong 已提交
255 256 257 258 259 260 261
                      data: data,
                      success: (res) => {
                        if (typeof object === 'object' && (method || null) != null) {
                          object[method]();
                        }
                      },
                      fail: () => {
D
devil_gong 已提交
262
                        self.showToast('用户信息缓存失败');
D
devil_gong 已提交
263 264 265 266
                      }
                    });
                  } else {
                    my.setStorageSync({
D
devil_gong 已提交
267
                      key: self.data.cache_user_login_key,
D
devil_gong 已提交
268 269
                      data: res.data.data.openid
                    });
D
devil_gong 已提交
270
                    self.login_to_auth();
D
devil_gong 已提交
271
                  }
G
gongfuxiang 已提交
272
                } else {
D
devil_gong 已提交
273
                  self.showToast(res.data.msg);
G
gongfuxiang 已提交
274 275 276 277
                }
              },
              fail: () => {
                my.hideLoading();
D
devil_gong 已提交
278
                self.showToast('服务器请求出错');
D
v1.2.0  
devil_gong 已提交
279
              }
G
gongfuxiang 已提交
280 281 282 283 284
            });
          }
        },
        fail: e => {
          my.hideLoading();
D
devil_gong 已提交
285
          self.showToast('授权失败');
D
v1.2.0  
devil_gong 已提交
286
        }
G
gongfuxiang 已提交
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
      });
    } else {
      this.login_to_auth();
    }
  },

  /**
   * 跳转到登录页面授权
   */
  login_to_auth() {
    my.confirm({
        title: '温馨提示',
        content: '授权用户信息',
        confirmButtonText: '确认',
        cancelButtonText: '暂不',
        success: (result) => {
          if (result.confirm) {
            my.navigateTo({
              url: "/pages/login/login"
            });
          }
        }
      });
D
v1.2.0  
devil_gong 已提交
310 311
  },

D
1.6  
devil_gong 已提交
312 313 314 315 316 317 318 319
  /**
   * 用户登录
   * object     回调操作对象
   * method     回调操作对象的函数
   * auth_data  授权数据
   */
  user_auth_login(object, method, auth_data) {
    var openid = my.getStorageSync({key: this.data.cache_user_login_key});
D
1.6  
devil_gong 已提交
320
    if ((openid.data || null) == null)
D
1.6  
devil_gong 已提交
321
    {
D
devil_gong 已提交
322
      this.user_login(object, method);
D
1.6  
devil_gong 已提交
323
    } else {
D
1.6  
devil_gong 已提交
324
      this.get_user_login_info(object, method, openid.data, auth_data);
D
1.6  
devil_gong 已提交
325 326 327 328 329 330 331 332 333 334 335
    }
  },

  /**
   * 获取用户授权信息
   * object     回调操作对象
   * method     回调操作对象的函数
   * openid     用户openid
   * auth_data  授权数据
   */
  get_user_login_info(object, method, openid, userinfo) {
G
gongfuxiang 已提交
336 337 338 339
    // 邀请人参数
    var params = my.getStorageSync({key: this.data.cache_launch_info_key});

    // 请求数据
D
1.6  
devil_gong 已提交
340
    my.showLoading({ content: "授权中..." });
D
devil_gong 已提交
341
    var self = this;
D
1.6  
devil_gong 已提交
342
    userinfo['openid'] = openid;
G
gongfuxiang 已提交
343
    userinfo['referrer'] = (params.data == null) ? 0 : (params.data.referrer || 0);
D
1.6  
devil_gong 已提交
344
    my.request({
D
devil_gong 已提交
345
      url: self.get_request_url('alipayuserinfo', 'user'),
D
1.6  
devil_gong 已提交
346
      method: 'POST',
D
1.6  
devil_gong 已提交
347
      data: userinfo,
D
1.6  
devil_gong 已提交
348
      dataType: 'json',
D
1.6  
devil_gong 已提交
349
      headers: { 'content-type': 'application/x-www-form-urlencoded' },
D
1.6  
devil_gong 已提交
350 351 352 353
      success: (res) => {
        my.hideLoading();
        if (res.data.code == 0) {
          my.setStorage({
D
devil_gong 已提交
354
            key: self.data.cache_user_info_key,
D
1.6  
devil_gong 已提交
355 356 357 358 359 360 361
            data: res.data.data,
            success: (res) => {
              if (typeof object === 'object' && (method || null) != null) {
                object[method]();
              }
            },
            fail: () => {
D
devil_gong 已提交
362
              self.showToast('用户信息缓存失败');
D
1.6  
devil_gong 已提交
363 364 365
            }
          });
        } else {
D
devil_gong 已提交
366
          self.showToast(res.data.msg);
D
1.6  
devil_gong 已提交
367 368 369
        }
      },
      fail: () => {
D
1.6  
devil_gong 已提交
370
        my.hideLoading();
D
devil_gong 已提交
371
        self.showToast('服务器请求出错');
D
1.6  
devil_gong 已提交
372 373 374 375
      },
    });
  },

D
v1.2.0  
devil_gong 已提交
376 377 378 379 380 381 382
  /**
   * 获取位置权限
   * object     回调操作对象
   * method     回调操作对象的函数
   */
  use_location(object, method) {
    my.showLoading({ content: "定位中..." });
D
devil_gong 已提交
383
    var self = this;
D
v1.2.0  
devil_gong 已提交
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
    my.getLocation({
      success(res) {
        my.hideLoading();

        // 回调
        if (typeof object === "object" && (method || null) != null) {
          object[method]({ lng: res.longitude, lat: res.latitude, status: 1000 });
        }
      },
      fail(e) {
        my.hideLoading();
        switch (e.error) {
          case 11:
          case 2001:
            my.alert({
              title: "温馨提示",
              content: "点击右上角->关于->右上角->设置->打开地理位置权限",
              buttonText: "我知道了",
              success: () => {
                if (typeof object === "object" && (method || null) != null) {
                  object[method]({ status: 400 });
                }
              }
            });
            break;

          case 12:
D
devil_gong 已提交
411
            self.showToast("网络异常,请重试[" + e.error + "]");
D
v1.2.0  
devil_gong 已提交
412 413 414
            break;

          case 13:
D
devil_gong 已提交
415
            self.showToast("定位失败,请重试[" + e.error + "]");
D
v1.2.0  
devil_gong 已提交
416 417 418
            break;

          default:
D
devil_gong 已提交
419
            self.showToast("定位超时,请重试[" + e.error + "]");
D
v1.2.0  
devil_gong 已提交
420 421 422 423 424 425 426 427
        }
      }
    });
  },

  /**
   * 字段数据校验
   * data           待校验的数据, 一维json对象
D
devil_gong 已提交
428
   * validation     待校验的字段, 格式 [{fields: 'mobile', msg: '请填写手机号码', is_can_zero: 1(是否可以为0)}, ...]
D
v1.2.0  
devil_gong 已提交
429 430 431 432 433 434 435 436
   */
  fields_check(data, validation) {
    for (var i in validation) {
      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 已提交
437
        this.showToast(validation[i]["msg"]);
D
v1.2.0  
devil_gong 已提交
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
        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 已提交
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
  /**
   * 当前地址是否存在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;
  },

D
v1.2.0  
devil_gong 已提交
553
  /**
G
wechat  
gongfuxiang 已提交
554
   * 事件操作
D
v1.2.0  
devil_gong 已提交
555 556 557 558 559 560 561 562 563
   */
  operation_event(e) {
      var value = e.target.dataset.value || null;
      var type = parseInt(e.target.dataset.type);

      if (value != null) {
        switch(type) {
          // web
          case 0 :
G
gongfuxiang 已提交
564
            my.navigateTo({url: '/pages/web-view/web-view?url='+encodeURIComponent(value)});
D
v1.2.0  
devil_gong 已提交
565 566 567 568
            break;

          // 内部页面
          case 1 :
G
gongfuxiang 已提交
569 570 571 572 573 574
            if (this.is_tabbar_pages(value))
            {
              my.switchTab({ url: value });
            } else {
              my.navigateTo({ url: value });
            }
D
v1.2.0  
devil_gong 已提交
575 576 577 578 579 580 581 582 583 584 585
            break;

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

          // 跳转到地图查看位置
          case 3 :
            var values = value.split('|');
            if (values.length != 4) {
D
devil_gong 已提交
586
              this.showToast('事件值格式有误');
D
v1.2.0  
devil_gong 已提交
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
              return false;
            }

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

          // 拨打电话
          case 4 :
            my.makePhoneCall({ number: value });
            break;
        }
      }
    },
D
1.6  
devil_gong 已提交
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620

  /**
   * 是否需要绑定手机号码
   */
  user_is_need_login(user) {
    // 是否需要绑定手机号码
    if ((user.is_mandatory_bind_mobile || 0) == 1)
    {
      if ((user.mobile || null) == null)
      {
        return true;
      }
    }
    return false;
  },

G
gongfuxiang 已提交
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
  /**
   * 默认弱提示方法
   * msg    [string]  提示信息
   * status [string]  状态 默认error [正确success, 错误error]
   */
  showToast(msg, status)
  {
    if ((status || 'error') == 'success')
    {
      my.showToast({
        type: "success",
        content: msg
      });
    } else {
      my.showToast({
        type: "fail",
        content: msg
      });
    }
  },

D
devil_gong 已提交
642 643 644 645 646 647 648
  // 拨打电话
  call_tel(value) {
    if ((value || null) != null) {
      my.makePhoneCall({ number: value });
    }
  },

D
devil_gong 已提交
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
  // 登录校验
  is_login_check(res) {
    if(res.code == -400)
    {
      my.clearStorage();
      my.confirm({
        title: '温馨提示',
        content: '授权用户信息',
        confirmButtonText: '确认',
        cancelButtonText: '暂不',
        success: (result) => {
          if (result.confirm) {
            my.navigateTo({
              url: "/pages/login/login?event_callback=init"
            });
          }
        },
      });
      return false;
    }
    return true;
  },

D
devil_gong 已提交
672 673 674 675 676 677
  // 获取用户openid
  get_user_openid() {
    var user = this.get_user_cache_info();
    return (user == false) ? null : user.alipay_openid || null;
  },

D
v1.2.0  
devil_gong 已提交
678
});