Commit 041cfa7f authored by caimeng's avatar caimeng

嵌入webview提交

parent 6549c41b
<script>
import { convertPromise ,initHeaderInfo} from './utils/header.js'
import Permission from '@/js_sdk/wa-permission/permission'
import { SelectLocation } from "./utils/authPerission";
import silentlyAppUpdate from '@/pages/app-update/js-sdk/silentlyAppUpdate'
export default {
onLaunch: function() {
const common = uni.getStorageSync("m-headers")
if (!common && plus.os.name=='iOS') {
this.loadDevice();
this.loadNetwork();
this.loadLocation();
this.loadUuid()
}
// let versionNumber
// plus.runtime.getProperty(plus.runtime.appid, function(wgtinfo){
// if(wgtinfo.version){
// versionNumber = wgtinfo.version;
// }else{
// versionNumber = plus.runtime.version;
// }
// uni.setStorageSync('version',versionNumber)
// })
import { switchShowTabbar,loadDevice,loadLocation,loadNetwork,loadUuid } from '@/utils/index.js'
export default {
onLaunch: function () {
// 手机型号
uni.getSystemInfo({
success:function(res) {
// console.log(res,'model')
uni.setStorageSync('modelApp',res.deviceBrand)
uni.setStorageSync('version',res.appVersion)
success: function (res) {
uni.setStorageSync('modelApp', res.deviceBrand)
uni.setStorageSync('version', res.appVersion)
}
})
// 强制竖屏
plus.screen.lockOrientation("portrait-primary")
/*** tabbar*/
this.switchShowTabbar()
//app更新版本
// silentlyAppUpdate()
// const isAgree = uni.getStorageSync('m-agreement')
// if (isAgree && plus.os.name ==='iOS') {
// silentlyAppUpdate()
// }
},
methods:{
//tab的信息
switchShowTabbar(){
const token=uni.getStorageSync('token')
if (!token) {
uni.setTabBarItem({
index: 1,
visible: false
})
} else {
const self=this
self.$request('/pawn/setting/other/switch/loan','GET').then(res => {
const {data}=res.result
if (res.code == 200 && data == true) {
try {
uni.setTabBarItem({
index: 1,
text: '贷款',
visible: true,
})
} catch (error) {
console.log(error);
}
} else {
console.log(data,'隐藏')
uni.setTabBarItem({
index: 1,
visible: false
})
// 判断用户是否同意用户隐私协议,如果同意协议再获取设备信息等内容
const isAgreePrivacy = plus.runtime.isAgreePrivacy();
// 同意了协议
if (isAgreePrivacy) {
const common = uni.getStorageSync("m-headers")
if (!common && plus.os.name == 'iOS') {
loadDevice();
loadNetwork();
loadLocation();
loadUuid()
}
})
}
/*** tabbar*/
switchShowTabbar()
},
// 获取common当中的设备信息
loadDevice: function() {
const that = this;
convertPromise('getSystemInfo').then(result => {
const deviceInfo = {
// token:uuidObtain,
deviceType: result.deviceType,
appName: result.appName,
deviceId: result.deviceId,
device: result.osName,
deviceName: result.platform,
appVersion: result.appWgtVersion,
osVersion: result.osVersion ? result.osVersion : result.system,
mobileType: result.model,
screenHeight: result.screenHeight,
screenWidth: result.screenWidth,
resolution: result.windowWidth + '*' + result.screenHeight
};
onShow() {
// 本地存储
uni.setStorage({
key: 'm-device-info',
data: JSON.stringify(deviceInfo),
success: function() {
// console.log('m-device-info存储成功');
}
});
}).catch(err => {
//that.toast('获取设备信息失败')
uni.showModal({
title: '"多典花"想访问您的设备信息',
content: '通过访问您的设备信息,提高您授信通过率。',
showCancel: false,
confirmText: '去设置',
success: function(res) {
if (res.confirm) {
Permission.gotoAppPermissionSetting()
}
}
});
})
},
// 获取common当中的网络信息
loadNetwork: function() {
const that = this;
convertPromise('getNetworkType').then(result => {
const networkInfo = {
networkStatus: result.networkType
};
// 网络信息存储
uni.setStorage({
key: 'm-network-info',
data: JSON.stringify(networkInfo),
success: function() {
// console.log('m-network-info存储成功');
}
});
}).catch(err => {
that.toast('获取网络信息失败')
})
},
//获取uuid
loadUuid: function() {
// plus.device.uuid
plus.device.getInfo({
success: function(e) {
const deviceInfo = {
token: e.uuid,
};
uni.setStorage({
key: 'm-load-udid',
data: JSON.stringify(deviceInfo),
success: function() {
// console.log('uuid存储成功');
}
})
},
fail: function(e) {
console.log('getDeviceInfo failed: ' + JSON.stringify(e));
}
});
},
// 获取common当中的位置信息
loadLocation: function() {
const that = this;
// 苹果测试手机如果没有插入手机卡,获取定位之后会解析失败,报错
SelectLocation(() => {
convertPromise('getLocation', {
type: 'wgs84',
geocode: true
}).then(result => {
const locationInfo = {
lat: String(result.latitude),
lng: String(result.longitude)
};
uni.setStorage({
key: 'm-location-info',
data: JSON.stringify(locationInfo),
success: function() {
// console.log('m-location-info存储成功');
}
});
}).catch(err => {
console.log(err, '错误了')
// that.toast('获取位置信息失败')
})
})
}
}
}
}
</script>
<style >
/*每个页面公共css */
<style>
/*每个页面公共css */
</style>
<template>
<text @click="openURL" :href="href">
<slot></slot>
</text>
</template>
<script>
export default {
name: "uni-link",
props: {
href: {
type: String
}
},
methods: {
openURL() {
// #ifdef APP-PLUS
plus.runtime.openWeb(this.href) //这里默认使用外部浏览器打开而不是内部web-view组件打开
// #endif
}
}
}
</script>
<style lang="less"></style>
\ No newline at end of file
......@@ -6,28 +6,23 @@
const BASE = {
development: {
common: "http://portal.cloudsmake.cn",
buyer: "https://dell-buyer.billionsat.net",
h5:'http://192.168.0.23:8080/index.html#/loan'
h5: 'http://192.168.0.23:8080/index.html#/loan'
},
stest: {
common: "https://dell-common.meimeiyouxin.com",
buyer: "https://dell-buyer.meimeiyouxin.com",
h5:'https://mmyx-h5-s.rockstect.cn/index.html#/'
common: "http://portal.cloudsmake.cn",
h5: 'http://ddang-h5-s.rockstect.cn/index.html#/'
},
ltest: {
common: "https://dell-common-l.meimeiyouxin.com",
buyer: "https://dell-buyer-l.meimeiyouxin.com",
h5:''
h5: ''
},
gray: {
common: "https://dell-common.meimeiyouxin.com",
buyer: "https://dell-buyer.meimeiyouxin.com",
h5:'https://mmyx-h5-g.rockstect.com/index.html#/'
h5: 'https://mmyx-h5-g.rockstect.com/index.html#/'
},
prod: {
common: "https://api.yyhock.com",
buyer: "https://dell-buyer.meimeiyouxin.com",
h5:'https://mmyx-h5.rockstect.com/index.html#/'
h5: 'https://mmyx-h5.rockstect.com/index.html#/'
}
}
let env = process.env.VUE_APP_BASE_NODE_ENV
......@@ -44,13 +39,13 @@ let env = process.env.VUE_APP_BASE_NODE_ENV
*/
// #ifdef APP-PLUS
env = "prod";
env = "stest";
// #endif
const api = {
common: BASE[env].common,
buyer: BASE[env].buyer,
h5:BASE[env].h5
h5: BASE[env].h5
}
export default {
......
......@@ -13,6 +13,7 @@ import request from './utils/request.js'
Vue.component('view-modal', Modal);
Vue.component('view-goods', goodsItem);
Vue.component('upgrade-Popup', upgradePopup);
Vue.prototype.$request = request
Vue.mixin(mixin)
......
{
"pages": [ //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages
"pages": [
//pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages
{
"path": "pages/index/index",
"style": {
......@@ -119,7 +120,6 @@
"navigationBarTitleText": "通讯录",
"enablePullDownRefresh": false
}
},
{
......@@ -132,6 +132,7 @@
{
"path": "pages/web/web",
"style": {
"navigationStyle": "custom",
"enablePullDownRefresh": false,
"navigationBarTitleText": ""
}
......@@ -183,15 +184,11 @@
}
}
}
],
"tabBar": {
"borderStyle": "white",
"color": "#BBBBBB",
"selectedColor": "#2263E6",
"iconWidth": "24px",
"height": "52px",
"fontSize": "12px",
"list": [
{
"pagePath": "pages/index/index",
......@@ -200,16 +197,16 @@
"text": "首页"
},
{
"pagePath": "pages/finance/index",
"pagePath": "pages/web/web",
"iconPath": "/static/tab/index-h.png",
"selectedIconPath": "/static/tab/index.png",
"text": "贷款"
},
{
"pagePath": "pages/bill/indexs",
"iconPath": "/static/tab/billh.png",
"selectedIconPath": "/static/tab/bill.png",
"text": "账单"
"pagePath": "pages/sort/index",
"iconPath": "/static/tab/sort-h.png",
"selectedIconPath": "/static/tab/sort.png",
"text": "分类"
},
{
"pagePath": "pages/my/index",
......@@ -228,11 +225,9 @@
"bounce": "none"
}
},
"uniIdRouter":{
"uniIdRouter": {
"loginPage": "pages/login/login",
"needLogin":[
"pages/my/index"
],
"resToLogin":true
"needLogin": ["pages/my/index"],
"resToLogin": true
}
}
......@@ -34,17 +34,17 @@
<script>
export default {
name:"Agreement",
name: "Agreement",
data() {
return {
userAgreement: '',
protocols:{
"protocolName":"隐私协议",
"protocolUrl":"https://ddh.yyhock.com/appStatic/protocol/dd-private.html"
protocols: {
"protocolName": "隐私协议",
"protocolUrl": "https://ddh.yyhock.com/appStatic/protocol/dd-private.html"
},
protocolf:{
"protocolName":"用户服务协议",
"protocolUrl":"https://ddh.yyhock.com/appStatic/protocol/dd-user.html"
protocolf: {
"protocolName": "用户服务协议",
"protocolUrl": "https://ddh.yyhock.com/appStatic/protocol/dd-user.html"
},
}
},
......@@ -75,16 +75,16 @@ export default {
}
})
},
getAppVersion(){
const self=this
getAppVersion() {
const self = this
uni.getSystemInfo({
success: (res) => {
let platform = res.platform;
// 获取本机版本号
let type;
platform === "android" ? (type = "ANDROID") : (type = "IOS");
self.$request(`/pawn/setting/other/appVersion/${type}`,'GET').then(res => {
if (res.success==true) {
self.$request(`/pawn/setting/other/appVersion/${type}`, 'GET').then(res => {
if (res.success == true) {
let response = res.result.data;
let result = {};
......@@ -98,7 +98,7 @@ export default {
result.storeList = response.storeList || '';
result.title = response.title || '';
result.type = response.type || '';
uni.setStorageSync('appVersion-info',result)
uni.setStorageSync('appVersion-info', result)
// resolve(result);
}
})
......@@ -109,31 +109,31 @@ export default {
},
// 初始化首页信息
async init() {
const self=this
self.$request('/pawn/setting','GET').then(res => {
const { protocol,phone }=res.result
if(protocol){
const protocolList=JSON.parse(protocol)
protocolList.map((item)=>{
if(item.protocolName=='隐私协议'){
self.protocols=item
}else if(item.protocolName=='用户服务协议'){
self.protocolf=item
const self = this
self.$request('/pawn/setting', 'GET').then(res => {
const { protocol, phone } = res.result
if (protocol) {
const protocolList = JSON.parse(protocol)
protocolList.map((item) => {
if (item.protocolName == '隐私协议') {
self.protocols = item
} else if (item.protocolName == '用户服务协议') {
self.protocolf = item
}
})
}
}).catch(err=>{
console.log(err,'请求出错')
}).catch(err => {
console.log(err, '请求出错')
})
},
Go(item){
const {protocolUrl,protocolName }=item
const items={
name:protocolName,
url:protocolUrl
Go(item) {
const { protocolUrl, protocolName } = item
const items = {
name: protocolName,
url: protocolUrl
}
uni.navigateTo({
url:'/pages/webview/webview?mydata='+encodeURIComponent(JSON.stringify(items))
url: '/pages/webview/webview?mydata=' + encodeURIComponent(JSON.stringify(items))
})
}
},
......
......@@ -138,7 +138,7 @@
text-align: left;
font-style: normal;
text-transform: none;
text{
.link{
color:#2263E6;
}
}
......
......@@ -7,11 +7,11 @@
<view class='login-main'>
<view class='main-mobile'>
<input class='login-m-mobile' placeholder="请输入手机号" :value='mobile' maxlength="11" type="number"
@input="changeInput($event)"/>
@input="changeInput($event)" />
</view>
<view class='main-mobile login-m-send'>
<input class='send-value' placeholder="请输入验证码" :value="sendcode" maxlength="6" type="number"
@input="changecode($event)"/>
@input="changecode($event)" />
<view class='send-text' @click='GetVerifyCode' v-if="canSendCode">获取验证码</view>
<view class="mobileCode-min" @click='GetVerifyCode' v-else>{{ count }}</view>
</view>
......@@ -19,97 +19,101 @@
</view>
<view class='login-btn' @click="loginBtn">登录</view>
<view class='login-footer'>
<view :class="clickStatus ? 'footer-click' : 'footer-icon' " @click="btnIcon"></view>
<view class='footer-text'>
我已阅读并同意 <text @click="goPro('1')">《注册协议》</text>
<text @click="goPro('2')">《隐私政策》</text>
<view :class="clickStatus ? 'footer-click' : 'footer-icon'" @click="btnIcon"></view>
<view v-if="protocolf" class='footer-text'>
<text>我已阅读并同意</text>
<uni-link class="link" :href="protocolf.protocolUrl">《注册协议》</uni-link>
<text></text>
<uni-link class="link" :href="protocolf.protocolUrl">《隐私政策》</uni-link>
</view>
</view>
</view>
</template>
<script>
export default {
import { switchShowTabbar } from '@/utils/index'
export default {
data() {
return {
clickStatus:false,
mobile:'',
sendcode:'',
clickStatus: false,
mobile: '',
sendcode: '',
canSendCode: true,
timer: null,//倒计时
count: '',//倒计时
smsDownCacheCode:'',
protocolf:null,
protocols:null,
smsDownCacheCode: '',
protocolf: null,
protocols: null,
}
},
onLoad(){
onLoad() {
this.init()
},
methods: {
init(){
const self=this
self.$request('/pawn/setting','GET').then(res => {
console.log(res,'settings');
const { protocol,phone }=res.result
if(protocol){
const protocolList=JSON.parse(protocol)
console.log(protocolList,'item966')
protocolList.map((item)=>{
init() {
const self = this
self.$request('/pawn/setting', 'GET').then(res => {
console.log(res, 'settings');
const { protocol, phone } = res.result
if (protocol) {
const protocolList = JSON.parse(protocol)
console.log(protocolList, 'item966')
if(item.protocolName=='隐私协议'){
self.protocols=item
}else if(item.protocolName=='用户服务协议'){
self.protocolf=item
protocolList.map((item) => {
if (item.protocolName == '隐私协议') {
self.protocols = item
} else if (item.protocolName == '用户服务协议') {
self.protocolf = item
}
})
}
}).catch(err=>{
console.log(err,'请求出错')
}).catch(err => {
console.log(err, '请求出错')
})
},
btnIcon(){
this.clickStatus=!this.clickStatus
btnIcon() {
this.clickStatus = !this.clickStatus
},
goPro(type){
if(type=='1'){
const {protocolUrl,protocolName }=this.protocolf
console.log(this.protocolf,'99')
const items={
name:protocolName,
url:protocolUrl
goPro(type) {
if (type == '1') {
const { protocolUrl, protocolName } = this.protocolf
console.log(this.protocolf, '99')
const items = {
name: protocolName,
url: protocolUrl
}
uni.navigateTo({
url:'/pages/webview/webview?mydata='+encodeURIComponent(JSON.stringify(items))
url: '/pages/webview/webview?mydata=' + encodeURIComponent(JSON.stringify(items))
})
}else{
const {protocolUrl ,protocolName}=this.protocols
console.log(this.protocols,'88')
const items={
name:protocolName,
url:protocolUrl
} else {
const { protocolUrl, protocolName } = this.protocols
console.log(this.protocols, '88')
const items = {
name: protocolName,
url: protocolUrl
}
uni.navigateTo({
url:'/pages/webview/webview?mydata='+encodeURIComponent(JSON.stringify(items))
url: '/pages/webview/webview?mydata=' + encodeURIComponent(JSON.stringify(items))
})
}
},
GetVerifyCode(){
const self=this
const params={
GetVerifyCode() {
const self = this
const params = {
"mobile": self.mobile
}
self.$request('/pawn/client/sendCode','POST',params).then(res => {
console.log(res,'sendCode');
const { smsBizNo }=res.result
if(smsBizNo){
self.$request('/pawn/client/sendCode', 'POST', params).then(res => {
console.log(res, 'sendCode');
const { smsBizNo } = res.result
if (smsBizNo) {
self.countdowns()
self.smsDownCacheCode=smsBizNo
self.smsDownCacheCode = smsBizNo
}
}).catch(err=>{
console.log(err,'请求出错')
}).catch(err => {
console.log(err, '请求出错')
})
},
// 获取验证码倒计时
......@@ -130,9 +134,9 @@
}, 1000)
}
},
loginBtn(){
const self=this
if(self.mobile==''){
loginBtn() {
const self = this
if (self.mobile == '') {
uni.showToast({
title: '请先输入手机号',
icon: "none",
......@@ -141,7 +145,7 @@
})
return false
}
if(self.sendcode==''){
if (self.sendcode == '') {
uni.showToast({
title: '请先输入验证码',
icon: "none",
......@@ -150,7 +154,7 @@
})
return false
}
if(self.clickStatus==false){
if (self.clickStatus == false) {
uni.showToast({
title: '请先勾选同意相关协议',
icon: "none",
......@@ -159,51 +163,54 @@
})
return false
}
const params={
const params = {
"mobile": self.mobile,
"smsDownCacheCode":self.smsDownCacheCode,
"smsDownCacheCode": self.smsDownCacheCode,
"verifyCode": self.sendcode
}
self.$request('/pawn/client/login','POST',params).then(res => {
console.log(res,'login');
const { userInfo,token}=res.result
if(userInfo){
const { deviceId}=userInfo
uni.setStorageSync('deviceId',deviceId)
self.$request('/pawn/client/login', 'POST', params).then(res => {
console.log(res, 'login');
const { userInfo, token } = res.result
if (userInfo) {
const { deviceId } = userInfo
uni.setStorageSync('deviceId', deviceId)
}
uni.setStorageSync('token',token)
uni.setStorageSync('token', token)
self.loginNocheck()
}).catch(err=>{
console.log(err,'请求出错')
// 设置
switchShowTabbar();
}).catch(err => {
console.log(err, '请求出错')
})
},
loginNocheck(){
const self=this
const params={
loginNocheck() {
const self = this
const params = {
"mobile": self.mobile,
"promoCode":'own'
"promoCode": 'own'
}
self.$request('/app/v1/loginNoCheck','POST',params).then(res => {
const {deviceId,token }=res.result
uni.setStorageSync('mobileCall',self.mobile)
uni.setStorageSync('deviceId',deviceId)
uni.setStorageSync('tokenFinance',token)
self.$request('/app/v1/loginNoCheck', 'POST', params).then(res => {
const { deviceId, token } = res.result
uni.setStorageSync('mobileCall', self.mobile)
uni.setStorageSync('deviceId', deviceId)
uni.setStorageSync('tokenFinance', token)
uni.navigateBack({
delta: 1
})
}).catch(err=>{
console.log(err,'请求出错')
}).catch(err => {
console.log(err, '请求出错')
})
},
changeInput(e){
changeInput(e) {
this.mobile = e.detail.value
},
changecode(e){
changecode(e) {
this.sendcode = e.detail.value
}
}
}
}
</script>
<style src='./index.less' lang="less" scoped></style>
......@@ -4,15 +4,15 @@
<view class='my-header'>
<image class='header-img' src='https://ddh.yyhock.com/ddhMall/my-icon.png'></image>
<view class='header-des'>
<view class='des-name' v-if="userTel!=''">{{userTel}}</view>
<view class='des-name' v-if="userTel != ''">{{ userTel }}</view>
<view class='des-name' v-else @click='goLogin'>注册/登录</view>
<view class='des-text'>多典花承诺保护您的信息安全</view>
</view>
</view>
<view class='my-line' v-show="menuBar && menuBar.length>0">
<view class='my-line' v-show="menuBar && menuBar.length > 0">
<view class='line-left' v-for="item in menuBar" :key="item.id" @click="goBar(item)">
<image class='left-img' :src='item.iconUrl'></image>
<view class='l-text'>{{item.title}}</view>
<view class='l-text'>{{ item.title }}</view>
<i class='l-go'></i>
</view>
</view>
......@@ -20,18 +20,18 @@
<view class='s-con'>
<view class='con-item' @click="goPage(item)" v-for="item in extMenuBarList" :key="item.id">
<image class="item-img" :src="item.iconUrl"></image>
<view class='item-text'>{{item.title}}</view>
<view class='item-text'>{{ item.title }}</view>
</view>
</view>
</view>
<view class="my-contain">
<i class='con-top'></i>
<view class='con-box' v-show='menuList && menuList.length>0'>
<view class='con-box' v-show='menuList && menuList.length > 0'>
<view class="box-line" v-for="item in menuList" @click='goItem(item)' :key="item.id">
<view class='line-item'>
<view class='item-l'>
<image class='l-img' :src='item.iconUrl'></image>
<view class='l-text'>{{item.title}}</view>
<view class='l-text'>{{ item.title }}</view>
</view>
<view class='item-r'></view>
</view>
......@@ -55,47 +55,52 @@
</template>
<script>
import {loadDevice,loadNetwork,loadUuid,loadLocation} from '../../utils/deviceInfo.js'
export default {
export default {
data() {
return {
userTel:'',
menuList:[],
mobileNum:'',
menuBar:[],
serviceCall:'',
extMenuBarList:[]
userTel: '',
menuList: [],
mobileNum: '',
menuBar: [],
serviceCall: '',
extMenuBarList: []
}
},
onLoad(){
const token=uni.getStorageSync('token')
const common = uni.getStorageSync("m-header-device")
if(token==''){
this.userTel=''
this.Go('uni:/pages/login/login')
return false
}
onLoad() {
this.init();
},
onShow() {
this.init();
},
methods: {
// 初始化
init() {
const token = uni.getStorageSync('token')
if (!token) {
this.userTel = ''
return this.Go('uni:/pages/login/login')
} else {
this.initMy()
this.initTels()
this.switchShowTabbar()
}
},
methods: {
switchShowTabbar(){
const token=uni.getStorageSync('token')
// 显示隐藏tabBar
switchShowTabbar() {
const token = uni.getStorageSync('token')
if (!token) {
console.log(token,'tokentab')
console.log(token, 'tokentab')
uni.setTabBarItem({
index: 1,
visible: false
})
} else {
const self=this
self.$request('/pawn/setting/other/switch/loan','GET').then(res => {
const {data}=res.result
const self = this
self.$request('/pawn/setting/other/switch/loan', 'GET').then(res => {
const { data } = res.result
if (res.code == 200 && data == true) {
try {
console.log(data,'显示')
console.log(data, '显示')
uni.setTabBarItem({
index: 1,
text: '贷款',
......@@ -105,7 +110,7 @@
console.log(error);
}
} else {
console.log(data,'隐藏')
console.log(data, '隐藏')
uni.setTabBarItem({
index: 1,
visible: false
......@@ -114,85 +119,69 @@
})
}
},
initTels(){
const self=this
self.$request('/app/v1/settings','GET').then(res => {
console.log(res,'settings');
const { serviceCall }=res.result
self.serviceCall=serviceCall
}).catch(err=>{
console.log(err,'请求出错')
// 初始化APP配置页面
initTels() {
const self = this
self.$request('/app/v1/settings', 'GET').then(res => {
console.log(res, 'settings');
const { serviceCall } = res.result
self.serviceCall = serviceCall
}).catch(err => {
console.log(err, '请求出错')
})
},
initMy(){
const self=this
self.$request('/app/v1/userIndex','GET').then(res => {
console.log(res,'userIndex');
const { menuBar ,user,baseMenuBar,extMenuBarList}=res.result
// self.menuBar=menuBar
self.menuList=baseMenuBar
self.extMenuBarList=extMenuBarList
if(user.cell){
self.userTel=user.cell
}else{
self.userTel=''
}
}).catch(err=>{
console.log(err,'请求出错')
// 初始化个人中心页面
initMy() {
const self = this
self.$request('/app/v1/userIndex', 'GET').then(res => {
console.log(res, 'userIndex');
const { menuBar, user, baseMenuBar, extMenuBarList } = res.result
self.menuBar = menuBar
self.menuList = baseMenuBar
self.extMenuBarList = extMenuBarList
self.userTel = ''
if (user.cell) self.userTel = user.cell
}).catch(err => {
console.log(err, '请求出错')
})
},
goPage(item){
goPage(item) {
this.Go(item.linkUrl)
},
goLogin(){
goLogin() {
this.Go('uni:/pages/login/login')
},
goBar(item){
const self=this
const token=uni.getStorageSync('token')
if(token!=''){
let newList=[]
newList=item.linkUrl.split(',')
self.Go(newList[0],newList[1])
}else{
goBar(item) {
const self = this
const token = uni.getStorageSync('token')
if (token != '') {
let newList = []
newList = item.linkUrl.split(',')
self.Go(newList[0], newList[1])
} else {
self.Go('uni:/pages/login/login')
}
},
goTel(){
goTel() {
uni.makePhoneCall({
phoneNumber: this.serviceCall //仅为示例
});
},
goItem(item){
if(item.linkUrl!=''){
console.log('66',item)
goItem(item) {
if (item.linkUrl != '') {
console.log('66', item)
this.Go(item.linkUrl)
}else{
console.log('67',this.mobileNum,item)
} else {
console.log('67', this.mobileNum, item)
uni.makePhoneCall({
phoneNumber: this.mobileNum
});
}
}
},
onShow(){
const token=uni.getStorageSync('token')
if(token==''){
this.userTel=''
this.Go('uni:/pages/login/login')
return false
}else{
this.initMy()
this.initTels()
this.switchShowTabbar()
}
}
}
}
</script>
<style src='./index.less' lang="less" scoped></style>
// 检查通讯录权限
import Permission from '@/js_sdk/wa-permission/permission'
import { nativeCommon } from './nativeCommon'
// 通讯录拒绝后弹框
const onPermissionModal = function () {
uni.showModal({
title: '"花花有米"想访问您的通讯录',
content: '通过访问您的通讯录信息,添加联系人,提高授信通过率。',
cancelText: '取消',
confirmText: '去设置',
success: function (res) {
if (res.confirm) {
Permission.gotoAppPermissionSetting()
}
},
})
}
// 检测通讯录权限
export const CheckContactPermission = function (callback) {
// 获取通讯录对象
plus.contacts.getAddressBook(
plus.contacts.ADDRESSBOOK_PHONE,
function (addressBook) {
// 查找联系人
addressBook.find(['displayName', 'phoneNumbers'], function (contacts) {
// 获取经纬度
uni.setStorage({
key: "m-contact",
data: JSON.stringify(contacts),
})
callback && callback(contacts)
})
},
function (e) {
// 如果授权『不允许』就弹框
onPermissionModal()
}
)
}
// 通讯录选择&设置
export const SelectContact = async function (callback) {
// 已经授权了
const that = this
const platform = uni.getSystemInfoSync()
if (platform.osName === 'ios') {
uni.navigateTo({
url: '/pages/web/contact',
events: {
send(data) {
try {
const result = JSON.parse(data)
callback && callback(result)
} catch (err) {
console.log('处理通讯录选择的内容报错')
}
},
},
})
} else {
try {
const rContacts = await Permission.requestAndroidPermission(
'android.permission.READ_CONTACTS'
)
let strStatus
if (rContacts === 1) {
nativeCommon.contacts.getContact(function (name, phoneNumber) {
const contact = {
linkerName: name,
linkerMobile: phoneNumber,
}
callback && callback(contact)
})
} else if (rContacts === 0) {
strStatus = '未获得授权'
} else if (rContacts === -1) {
onPermissionModal()
}
} catch (err) {
console.log('校验通讯录权限异常')
}
}
}
// 检测位置权限
export const CheckLocationPermission = function (callback) {
plus.geolocation.getCurrentPosition(
function (res) {
callback && callback(res)
},
function (err) {
console.log(err, '走这里了?')
uni.showModal({
title: '"花花有米"想要访问您的位置信息',
content:
'应用为您提供的服务,要访问您的位置信息,需要您提供权限,请允许。',
success: function (res) {
if (res.confirm) {
Permission.gotoAppPermissionSetting()
} else if (res.cancel) {
console.log('用户点击取消')
}
},
})
}
)
}
// 位置选择
export const SelectLocation = async function (callback) {
const platform = uni.getSystemInfoSync()
if (platform.osName === 'ios') {
if (Permission.judgeIosPermission('location')) {
callback && callback()
} else {
CheckLocationPermission(callback)
}
} else {
try {
const rContacts = await Permission.requestAndroidPermission(
'android.permission.ACCESS_FINE_LOCATION'
)
console.log(rContacts,'值')
if (rContacts === 1) {
callback && callback()
} else if (rContacts === 0) {
console.log('未获得授权')
} else if (rContacts === -1) {
uni.showModal({
title: '"花花有米"想要访问您的位置信息',
content:
'应用为您提供的服务,要访问您的位置信息,需要您提供权限,请允许。',
success: function (res) {
if (res.confirm) {
Permission.gotoAppPermissionSetting()
} else if (res.cancel) {
console.log('用户点击取消')
}
},
})
}
} catch (err) {
console.log('校验手机位置权限异常')
}
}
}
<template>
<view class="page-contact">
<template v-if="contacts.length">
<view class="c-item" v-for="(item, index) in list" :key="index" @click="handleClick(item)">
<view class="c-name">{{ item.displayName }}</view>
<!-- <view class="c-mobile">{{item.mobile}}</view> -->
</view>
</template>
</view>
</template>
<script>
export default {
name: 'Contact',
data() {
return {
eventChannel: null,
contacts: [],
list: [],
}
},
onLoad() {
this.eventChannel = this.getOpenerEventChannel()
this.init()
},
onShow() {
uni.showLoading({
title: '加载中...',
mask: true,
})
this.init()
},
methods: {
init() {
console.log('进来了')
const that = this
try {
uni.getStorage({
key: 'm-contact',
success: function (res) {
try {
let data = JSON.parse(res.data)
data.forEach((item) => {
const { phoneNumbers } = item
const displayName = item.displayName
item.firstName = displayName.substring(0, 1)
let mobile = ''
if (phoneNumbers && phoneNumbers.length) {
mobile = phoneNumbers[0]['value']
mobile = mobile.replace(/\s+/g, '')
}
item.mobile = mobile
})
that.list = data
that.contacts = data
uni.hideLoading()
} catch (err) {
console.log(err, '处理数据错了')
uni.hideLoading()
}
},
fail: function (err) {
console.log(err, '报错了')
},
complete: function () {
},
})
} catch (err) {
console.log(err, '获取通讯录报错')
}
},
handleClick(item) {
const { displayName, mobile } = item
const result = {
linkerName: displayName,
linkerMobile: mobile,
}
this.eventChannel.emit('send', JSON.stringify(result))
uni.navigateBack()
},
},
}
</script>
<style lang="less">
.page-contact {
height: 100vh;
width: 100vw;
box-sizing: border-box;
padding: 0 30rpx 50rpx;
.c-item {
width: 100%;
height: 80rpx;
border-bottom: 1rpx solid #dddddd;
font-size: 28rpx;
display: flex;
align-items: center;
&:last-child {
border-bottom: none;
}
}
}
</style>
<template>
<view>
<web-view :src="url" @message="handleMessage"></web-view>
</view>
</template>
<script>
import {
hideTabBar,
showTabBar,
loadLocation,
Face_UP,
Camera_UP,
} from './utils'
import { CheckContactPermission, SelectContact } from './authPermission'
import storage from '@/utils/storage'
export default {
data() {
return {
wv: null,
url: null,
canBack: false,
}
},
async onShow() {
if (!this.$options.filters.isLogin('auth')) {
this.$options.filters.navigateToLogin()
}
if (this.wv) {
this.wv.evalJS(`callback({ 'action': 'OnShow' })`)
this.wv.reload()
}
},
onLoad() {
},
onBackPress(e) {
if (this.wv && this.canBack) {
this.wv.back()
return true
}
return false
},
onReady() {
const _that = this
// #ifdef APP-PLUS
let statusBarHeight = parseInt(uni.getSystemInfoSync().statusBarHeight)
let currentWebview = _that.$scope.$getAppWebview() //此对象相当于html5plus里的plus.webview.currentWebview()。在uni-app里vue页面直接使用plus.webview.currentWebview()无效
setTimeout(() => {
this.wv = currentWebview.children()[0]
this.wv.setStyle({
top: statusBarHeight, // + plus.navigator.getStatusbarHeight() //设置web-view距离顶部的距离以及自己的高度,单位为px
bottom: 0, // 如果不把bottom设置为0,可能会与pages.json定义的tabBar,产生一些问题,具体的代码效果,可以去除bottom:0,自行查看一下
})
this.wv.setPullToRefresh(
{
support: true,
height: '50px',
range: '200px',
contentdown: {
caption: '下拉刷新',
},
contentover: {
caption: '释放刷新',
},
contentrefresh: {
caption: '正在刷新...',
},
},
_that.onRefresh
)
// 物理按键返回
_that.wv.addEventListener(
'loaded',
() => {
_that.wv.canBack((e) => {
_that.canBack = e.canBack
})
},
false
)
}, 1000) //如果是页面初始化调用时,需要延时一下
// #endif
},
onTabItemTap(e) {
console.log('点击tabbar', JSON.stringify(e))
},
methods: {
// 刷新页面
onRefresh() {
this.wv.evalJS(`callback({ 'action': 'OnRefresh' })`)
setTimeout(() => {
uni.showToast({
title: '刷新成功',
icon: 'none',
})
this.wv.endPullToRefresh()
}, 1200)
},
async handleMessage(e) {
console.log('接收到网页发来的消息', JSON.stringify(e.detail.data[0]))
const message = e.detail.data[0]
switch (message.action) {
case 'hideTabBar': // 隐藏tabbar
hideTabBar()
break
case 'showTabBar': // 显示tabbar
showTabBar()
break
case 'GetUserIsLogin': // 用户是否登陆
const subNVue = uni.getSubNVueById('loan-popup') // 对应page.json的id
// 1:子窗体从顶部进入(动画效果), 2:显示原生子窗体的动画持续时间
subNVue.show('slide-in-bottom', 300, () => {
// 向子窗体传递参数
uni.$emit('loan-from-popup', {
appName: '花花有米',
mobile: storage.getUserInfo().mobile,
})
})
break
case 'DeviceInfo': // 设备信息 m-device-info
const res = await loadLocation()
this.wv.evalJS(
`callback(${JSON.stringify({ action: 'DeviceInfo', result: res })})`
)
break
case 'GetALLContact': // 全部通讯录信息 m-contact
CheckContactPermission((res) => {
this.wv.evalJS(
`callback(${JSON.stringify({
action: 'GetALLContact',
result: res,
})})`
)
})
break
case 'GetContact': // 选择通讯录
CheckContactPermission(() => {
SelectContact((res) => {
this.wv.evalJS(
`callback(${JSON.stringify({
action: 'GetContact',
result: res,
})})`
)
})
})
break
case 'Face_UP':
/**
* 人脸验证
* token
* requestId
*/
Face_UP(message.token, message.requestId, (res) => {
this.wv.evalJS(`callback({action: 'Face_UP', 'result': ${res}})`)
})
break
case 'Camera_UP':
/**
* OCR识别
* token
* type
* key
* secret
*/
Camera_UP(message.token, message.type, (res) => {
this.wv.evalJS(
`callback({action: 'Camera_UP', 'type': ${type}, 'result': ${res}})`
)
})
break
default:
break
}
},
},
onHide() {
this.wv.evalJS(`callback({ 'action': 'OnHide' })`)
// 页面销毁之前 移除监听器
uni.$off('to-popup')
},
}
</script>
/**
* nativeCommon,通过Native.js调用原生API
* 选择通讯录电话
*/
const nativeCommon = {
/**
* 通讯录模块
*/
contacts: {
getContact: function (callBack) {
switch (plus.os.name) {
case 'iOS':
console.log('进来了')
if (plus.device.model === 'iPhoneSimulator') {
//模拟器
nativeCommon.contacts.ios.visitContacts(function (
name,
phoneNumber
) {
callBack(name, phoneNumber)
})
} else {
console.log('真机')
//真机
nativeCommon.contacts.ios.visitAddressBook(function (
name,
phoneNumber
) {
callBack(name, phoneNumber)
})
}
break
case 'Android':
// Android通过plus.contacts.getAddressBook可弹出通讯录授权提示框
// nativeCommon.contacts.android.visitContacts(function(name, phoneNumber) {
// callBack(name, phoneNumber);
// });
plus.contacts.getAddressBook(
plus.contacts.ADDRESSBOOK_PHONE,
function (addressbook) {
nativeCommon.contacts.android.visitContacts(function (
name,
phoneNumber
) {
callBack(name, phoneNumber)
})
},
function (e) {
plus.nativeUI.alert('Get address book failed: ' + e.message)
}
)
break
default:
break
}
},
ios: {
//供iOS系统调用
/**
* 访问通讯录,将获取的联系人信息通过callBack返回
* 仅限模拟器使用(Native.js 的bug)
* @param {Object} callBack回调
*/
visitContacts: function (callBack) {
const contactPickerVC = plus.ios.newObject(
'CNContactPickerViewController'
)
//实现代理方法【- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact;】
//同时生成遵守CNContactPickerDelegate协议的代理对象delegate
const delegate = plus.ios.implements('CNContactPickerDelegate', {
'contactPicker:didSelectContact:': function (picker, contact) {
//姓名
var name = ''
//姓氏
var familyName = contact.plusGetAttribute('familyName')
//名字
var givenName = contact.plusGetAttribute('givenName')
name = familyName + givenName
//电话号码
var phoneNo = ''
var phoneNumbers = contact.plusGetAttribute('phoneNumbers')
if (phoneNumbers.plusGetAttribute('count') > 0) {
var phone = phoneNumbers.plusGetAttribute('firstObject')
var phoneNumber = phone.plusGetAttribute('value')
phoneNo = phoneNumber.plusGetAttribute('stringValue')
}
if (callBack) {
callBack(name, phoneNo)
}
},
})
//给通讯录控制器contactPickerVC设置代理
plus.ios.invoke(contactPickerVC, 'setDelegate:', delegate)
//获取当前UIWebView视图
const currentWebview = plus.ios.currentWebview()
//根据当前UIWebView视图获取当前控制器
const currentVC =
nativeCommon.contacts.ios.getViewControllerByView(currentWebview)
//由当前控制器present到通讯录控制器
plus.ios.invoke(
currentVC,
'presentViewController:animated:completion:',
contactPickerVC,
true,
null
)
},
/**
* 访问通讯录,将获取的联系人信息通过callBack返回
* 仅限真机使用(Native.js 的bug)
* @param {Object} callBack
*/
visitAddressBook: function (callBack) {
const peoplePickerNavController = plus.ios.newObject(
'ABPeoplePickerNavigationController'
)
//实现代理方法【- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person;】
//同时生成遵守ABPeoplePickerNavigationControllerDelegate协议的代理对象peoplePickerDelegate
const peoplePickerDelegate = plus.ios.implements(
'ABPeoplePickerNavigationControllerDelegate',
{
'peoplePickerNavigationController:didSelectPerson:': function (
peoplePicker,
person
) {
//这里的peoplePicker竟然是CNContact实例对象,person是undefined
console.log(JSON.stringify(peoplePicker))
console.log(JSON.stringify(person))
console.log(typeof person)
//所以之前的代码不用改
const contact = peoplePicker
//姓名
let name = ''
//姓氏
const familyName = contact.plusGetAttribute('familyName')
//名字
const givenName = contact.plusGetAttribute('givenName')
name = familyName + givenName
//电话号码
let phoneNo = ''
const phoneNumbers = contact.plusGetAttribute('phoneNumbers')
if (phoneNumbers.plusGetAttribute('count') > 0) {
const phone = phoneNumbers.plusGetAttribute('firstObject')
const phoneNumber = phone.plusGetAttribute('value')
phoneNo = phoneNumber.plusGetAttribute('stringValue')
}
if (callBack) {
callBack(name, phoneNo)
}
},
}
)
//给通讯录控制器peoplePickerNavController设置代理
plus.ios.invoke(
peoplePickerNavController,
'setPeoplePickerDelegate:',
peoplePickerDelegate
)
//获取当前UIWebView视图
var UIApplicationClass = plus.ios.importClass('UIApplication')
var UIAppObj = UIApplicationClass.sharedApplication()
var del = plus.ios.invoke(UIAppObj, 'delegate')
var appWindowObj = plus.ios.invoke(del, 'window')
var appRootController = plus.ios.invoke(
appWindowObj,
'rootViewController'
)
//由当前控制器present到通讯录控制器
plus.ios.invoke(
appRootController,
'presentViewController:animated:completion:',
peoplePickerNavController,
true,
null
)
},
},
android: {
//供android系统调用
visitContacts: function (callBack) {
plus.contacts.getAddressBook(
plus.contacts.ADDRESSBOOK_PHONE,
(book) => {
const REQUESTCODE = 1000
const main = plus.android.runtimeMainActivity()
const Intent = plus.android.importClass('android.content.Intent')
const ContactsContract = plus.android.importClass(
'android.provider.ContactsContract'
)
const intent = new Intent(
Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI
)
main.onActivityResult = function (requestCode, resultCode, data) {
if (REQUESTCODE == requestCode) {
var phoneNumber = ''
var resultString = ''
var context = main
plus.android.importClass(data)
var contactData = data.getData()
var resolver = context.getContentResolver()
plus.android.importClass(resolver)
var cursor = resolver.query(contactData, null, null, null, null)
plus.android.importClass(cursor)
cursor.moveToFirst()
//姓名
var givenName =
cursor.getString(
cursor.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME
)
) || ''
var contactId = cursor.getString(
cursor.getColumnIndex(ContactsContract.Contacts._ID)
)
var pCursor = resolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +
' = ' +
contactId,
null,
null
)
if (pCursor.moveToNext()) {
phoneNumber = pCursor.getString(
pCursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER
)
)
}
if (callBack) {
callBack(givenName, phoneNumber)
}
cursor.close()
pCursor.close()
}
}
main.startActivityForResult(intent, REQUESTCODE)
}
)
},
},
},
}
module.exports = {
nativeCommon: nativeCommon,
}
import Permission from "@/js_sdk/wa-permission/permission"; //权限工具类
import {
SelectLocation
} from "./authPermission"; //权限工具类
const LFv2 = uni.requireNativePlugin("AThree-LFv2");
// 隐藏tabbar
export const hideTabBar = () => {
uni.hideTabBar();
};
// 显示tabbar
export const showTabBar = () => {
uni.showTabBar();
};
/**
*
* @param {*} type navigateTo | redirectTo | reLaunch | switchTab
* @param {*} url
*/
export const navigate = (type = "navigateTo", url) => {
uni[type]({
url,
});
};
/**
* 获取设备基础信息
* @date 2022-01-06
* @returns {object}
*/
export const loadDeviceInfo = async (lat, lng, address) => {
// 网络状态
const {networkType = ""} = await loadNetwork();
return new Promise((resolve, reject) => {
uni.getSystemInfo({
success: async (result) => {
const {
platform,
deviceId,
osVersion,
screenWidth,
screenHeight,
appName,
osName,
appWgtVersion,
model,
deviceBrand,
} = result;
const deviceInfo = {
deviceId: deviceId, //设备指纹ID
appName: "MMYX", //APP实例
appSourceId: "1",
device: osName, // 设备类型
deviceName: platform, // 设备命名
deviceBand: deviceBrand, // 设备品牌
token: "", // 设备令牌(device_token)
appVersion: appWgtVersion, //app版本
osVersion: osVersion, //操作系统版本
mobileType: model, // 手机型号
idfa: "", // IOS设备则为:IDFA
imei: "", //安卓设备为:imei
mac: "", // mac
wifiMac: "", // wifimac
clientIp: "",
clientProvince: "", //客户所在省份
clientCity: "", // 客户所在城市
lat: lat, // 纬度
lng: lng, // 经度
clientRegion: address || "", // 客户所在区域(GPRS或IP所在地信息)
carrierOperator: "", //运营商
pushId: "", //push推送ID
pushType: "", //设备push接入类型(1. 小米PUSH,2. 极光PUSH)
screenHeight: screenHeight, //屏幕高度
screenWidth: screenWidth, //屏幕宽度
resolution: `${screenWidth}*${screenHeight}`, //分辨率
networkStatus: networkType, //网络
tId: "", //同盾设备指纹ID
electricQuantity: "", //电量
totalStorage: "", //存储总空间
availableStorage: "", //可用存储空间
};
uni.setStorage({
key: "m-device-info",
data: JSON.stringify(deviceInfo),
success: (res) => {
console.log("m-device-info存储成功");
},
});
return resolve(deviceInfo);
},
fail: (err) => {
console.log('获取系统参数报错')
return reject(err);
},
});
});
};
/**
* 人脸验证
*/
export const Face_UP = (token = "", requestId = "", callback) => {
try {
LFv2.Face_UP({
token,
requestId,
},
(res) => {
console.log("Face_UP", res);
if (res.code == 1) {
callback && callback(res);
} else {
uni.showToast({
title: "验证失败",
icon: "none",
});
}
}
);
} catch (error) {
console.error(error);
}
};
// 获取common当中的网络信息
export const loadNetwork = () => {
const that = this;
return new Promise((resolve, reject) => {
uni.getNetworkType({
success: (res) => {
// 网络信息存储
uni.setStorage({
key: "m-network-info",
data: res.networkType,
success: function() {
console.log("m-network-info存储成功");
},
});
resolve(res);
},
fail: (err) => {
uni.showToast({
icon: "none",
title: "获取网络信息失败",
});
reject(err);
},
});
});
};
// 获取common当中的位置信息
export const loadLocation = () => {
const that = this;
console.log('调用获取定位信息的方法3')
return new Promise((resolve, reject) => {
uni.getLocation({
type: "wgs84",
geocode: true,
success: async (res) => {
console.log(res, "成功===");
const locationInfo = {
lat: String(res.latitude),
lng: String(res.longitude),
address: JSON.stringify(res.address),
};
// 位置信息存储
uni.setStorage({
key: "m-location-info",
data: JSON.stringify(locationInfo),
success: function() {
console.log("m-location-info存储成功");
},
fail: (err) => {
console.error("m-location-info存储失败");
},
});
// 获取设备信息
const device = await loadDeviceInfo(
res.latitude,
res.longitude,
''
);
resolve(device);
},
fail: async (err) => {
console.log(err, "报错信息");
const hasShowModal = uni.getStorageSync('showModal');
if (!hasShowModal) {
uni.setStorageSync('showModal', 'true')
let hasReject;
// if (plus.os.name == "iOS") {
// hasReject = Permission.judgeIosPermission('location')
// } else {
// hasReject = await Permission.requestAndroidPermission('android.permission.ACCESS_FINE_LOCATION')
// }
// console.log(hasReject, '定位权限返回内容')
// 这里应该判断用户 拒绝之后 才弹框
uni.showModal({
title: '"花花有米"想要访问您的位置信息',
content: "您手机系统的定位处于关闭状态,会导致您后续的授信不通过,授信需要访问您的位置信息,需要您提供权限,请开启手机的定位服务。",
success: function(res) {
if (res.confirm) {
uni.removeStorageSync('hasRefresh')
uni.removeStorageSync('showModal')
Permission.gotoAppPermissionSetting();
} else if (res.cancel) {
console.log("用户点击取消");
uni.removeStorageSync('showModal')
}
},
});
}
// 获取设备信息
reject(err);
},
});
});
};
/**
* 获取设备信息(https://www.html5plus.org/doc/zh_cn/device.html#plus.device.getInfo)
* 包括国际移动设备身份码、国际移动用户识别码、设备的唯一标识等信息。
* Android平台调用此方法需要申请访问设备标识(部分设备提示为拨打电话)权限,详情参考https://ask.dcloud.net.cn/article/36075。
*/
export const getDeviceInfo = () => {
return new Promise((resolve, reject) => {
plus.device.getInfo({
success: (res) => {
console.log("**************** 设备信息:" + JSON.stringify(res));
resolve(res);
},
fail: (err) => {
// console.log('**************** 获取设备信息失败: ' + JSON.stringify(err))
reject(err);
},
complete: (e) => {
// console.log('**************** 获取设备信息complete: ', e)
},
});
});
};
\ No newline at end of file
import request from './fetch'
// export const login = (mobile) => {
// return request.post('app/v1/loginNoCheck', {mobile})
// }
export const OssSign = (data) => {
return request.get('app/v1/oss', data)
}
\ No newline at end of file
/*
* 该文件作用于ajax 请求,该文件用户不会直接调用,提供给/server/api.js 文件使用
* 封装了ajax请求的公共头,等其它信息
* 请求前处理和请求后处理的方法
*/
// 从环境配置当中获取接口的BaseUrl
import api from '@/config/api'
// const $host = 'https://portal.rockstect.com'
let $host = ''
if (api.env === 'prod') {
$host = 'https://portal.rockstect.com'
} else {
$host = 'http://112.124.25.186:18998'
}
const request = async function (config) {
const Device = uni.getStorageSync('m-device-info')
console.log("Device", JSON.stringify(Device));
// 这里确保一定是可以获取得到的
let token = uni.getStorageSync('m-token')
let header = {}
header.device = encodeURIComponent(Device)
if (config.data && config.data.token) token = config.data.token
// 如果有token,说明登录成功了,那么就在请求头里面添加token信息
if (token) header.Authorization = token
let { url, data, method, showLoading } = config
if (!showLoading) {
uni.showLoading({
mask: true,
title: '加载中...',
})
}
url = $host + '/' + url
return new Promise((resolve, reject) => {
uni.request({
url,
data,
header,
method,
timeout: 3000,
success(res) {
// 这里统一处理数据
if (res.statusCode === 200) {
if (res.data.success) {
resolve(res.data)
} else {
reject({
msg: res.data.message,
data: res.data,
})
}
} else {
reject({
msg: `网络错误:${res.statusCode}`,
data: res.data,
})
}
},
fail(err) {
// 这里统一处理数据报错的问题,这里的错误交给Promise函数的catch方法执行了
console.log(
err,
'网络请求报错的原因,这里的错误status状态码肯定不是200'
)
reject({
msg: `服务器繁忙,请稍候重试~`,
data: err,
})
},
complete() {
uni.hideLoading()
},
})
})
.then((res) => {
uni.hideLoading()
return res
})
.catch((err) => {
uni.hideLoading()
const { msg, data } = err
uni.showToast({
icon: 'none',
title: msg ? msg : '服务器开小差了',
})
// 请求报错,跳转到错误页面
return err
})
.finally(() => {
uni.hideLoading()
// 不管请求成功还是失败,都展示页面
})
}
export default {
// get方法封装
get: function (url, data, flag) {
return request({
url,
data: data ? data : {},
method: 'GET',
showLoading: flag ? flag : false,
})
},
// post方法封装
post: function (url, data, flag, abort) {
return request({
url,
data: data ? data : {},
method: 'POST',
showLoading: flag ? flag : false,
})
},
}
function getLocalFilePath(path) {
if (
path.indexOf('_www') === 0 ||
path.indexOf('_doc') === 0 ||
path.indexOf('_documents') === 0 ||
path.indexOf('_downloads') === 0
) {
return path
}
if (path.indexOf('file://') === 0) {
return path
}
if (path.indexOf('/storage/emulated/0/') === 0) {
return path
}
if (path.indexOf('/') === 0) {
var localFilePath = plus.io.convertAbsoluteFileSystem(path)
if (localFilePath !== path) {
return localFilePath
} else {
path = path.substr(1)
}
}
return '_www/' + path
}
function dataUrlToBase64(str) {
var array = str.split(',')
return array[array.length - 1]
}
var index = 0
function getNewFileId() {
return Date.now() + String(index++)
}
function biggerThan(v1, v2) {
var v1Array = v1.split('.')
var v2Array = v2.split('.')
var update = false
for (var index = 0; index < v2Array.length; index++) {
var diff = v1Array[index] - v2Array[index]
if (diff !== 0) {
update = diff > 0
break
}
}
return update
}
export function pathToBase64(path) {
return new Promise(function (resolve, reject) {
if (typeof window === 'object' && 'document' in window) {
if (typeof FileReader === 'function') {
var xhr = new XMLHttpRequest()
xhr.open('GET', path, true)
xhr.responseType = 'blob'
xhr.onload = function () {
if (this.status === 200) {
let fileReader = new FileReader()
fileReader.onload = function (e) {
resolve(e.target.result)
}
fileReader.onerror = reject
fileReader.readAsDataURL(this.response)
}
}
xhr.onerror = reject
xhr.send()
return
}
var canvas = document.createElement('canvas')
var c2x = canvas.getContext('2d')
var img = new Image()
img.onload = function () {
canvas.width = img.width
canvas.height = img.height
c2x.drawImage(img, 0, 0)
resolve(canvas.toDataURL())
canvas.height = canvas.width = 0
}
img.onerror = reject
img.src = path
return
}
if (typeof plus === 'object') {
plus.io.resolveLocalFileSystemURL(
getLocalFilePath(path),
function (entry) {
entry.file(
function (file) {
var fileReader = new plus.io.FileReader()
fileReader.onload = function (data) {
resolve(data.target.result)
}
fileReader.onerror = function (error) {
reject(error)
}
fileReader.readAsDataURL(file)
},
function (error) {
reject(error)
}
)
},
function (error) {
reject(error)
}
)
return
}
if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
wx.getFileSystemManager().readFile({
filePath: path,
encoding: 'base64',
success: function (res) {
resolve('data:image/png;base64,' + res.data)
},
fail: function (error) {
reject(error)
},
})
return
}
reject(new Error('not support'))
})
}
export function base64ToPath(base64) {
return new Promise(function (resolve, reject) {
if (typeof window === 'object' && 'document' in window) {
base64 = base64.split(',')
var type = base64[0].match(/:(.*?);/)[1]
var str = atob(base64[1])
var n = str.length
var array = new Uint8Array(n)
while (n--) {
array[n] = str.charCodeAt(n)
}
return resolve(
(window.URL || window.webkitURL).createObjectURL(
new Blob([array], { type: type })
)
)
}
var extName = base64.split(',')[0].match(/data\:\S+\/(\S+);/)
if (extName) {
extName = extName[1]
} else {
reject(new Error('base64 error'))
}
var fileName = getNewFileId() + '.' + extName
if (typeof plus === 'object') {
var basePath = '_doc'
var dirPath = 'uniapp_temp'
var filePath = basePath + '/' + dirPath + '/' + fileName
if (
!biggerThan(
plus.os.name === 'Android' ? '1.9.9.80627' : '1.9.9.80472',
plus.runtime.innerVersion
)
) {
plus.io.resolveLocalFileSystemURL(
basePath,
function (entry) {
entry.getDirectory(
dirPath,
{
create: true,
exclusive: false,
},
function (entry) {
entry.getFile(
fileName,
{
create: true,
exclusive: false,
},
function (entry) {
entry.createWriter(function (writer) {
writer.onwrite = function () {
resolve(filePath)
}
writer.onerror = reject
writer.seek(0)
writer.writeAsBinary(dataUrlToBase64(base64))
}, reject)
},
reject
)
},
reject
)
},
reject
)
return
}
var bitmap = new plus.nativeObj.Bitmap(fileName)
bitmap.loadBase64Data(
base64,
function () {
bitmap.save(
filePath,
{},
function () {
bitmap.clear()
resolve(filePath)
},
function (error) {
bitmap.clear()
reject(error)
}
)
},
function (error) {
bitmap.clear()
reject(error)
}
)
return
}
if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
var filePath = wx.env.USER_DATA_PATH + '/' + fileName
wx.getFileSystemManager().writeFile({
filePath: filePath,
data: dataUrlToBase64(base64),
encoding: 'base64',
success: function () {
resolve(filePath)
},
fail: function (error) {
reject(error)
},
})
return
}
reject(new Error('not support'))
})
}
import {OssSign} from './api'
import { base64ToPath } from './image-tools'
// 初始化OSS签名
/*
let fileName = 'jpg'
let fileType = 'LRD-ADMIN/audit'
* fileType 文件存放路径
* fileName 文件类型
*/
const initOssSign = async function (fileName, fileType, imgData) {
return new Promise(async (resolve, reject) => {
try {
const res = await OssSign({ fileType, fileName })
if (res.success) {
const { oss } = res.result
const { accessId, dir, host, policy, signature } = oss
const data = {
success_action_status: '200',
key: dir,
OSSAccessKeyId: accessId,
policy: policy,
Signature: signature,
}
imgBase64ToFilePath(imgData)
.then((path) => {
const config = {
url: host,
dir: dir,
formData: data,
filePath: path,
}
return resolve(config)
})
.catch((err) => {
console.log(err, '报错了')
reject(err)
})
}
} catch (err) {
uni.showToast({
icon: 'error',
title: '处理签名数据失败',
})
}
})
}
// 文件上传请求
export const UploadFile = function (fileName, fileType, imgData) {
return new Promise((resolve, reject) => {
initOssSign(fileName, fileType, imgData).then((config) => {
const { url, filePath, dir, formData } = config
uni.showLoading({
title: '加载中...',
})
uni.uploadFile({
url, //仅为示例,非真实的接口地址
filePath,
name: 'file',
formData,
success: (res) => {
res.fileUrl = `${url}${dir}`
return resolve(res)
},
fail: (err) => {
uni.showToast({
icon: 'none',
title: '文件上传OSS失败',
})
return reject(err)
},
complete: () => {
uni.hideLoading()
},
})
})
})
}
// Base64转本地图片路径
export const imgBase64ToFilePath = function (base64Img) {
return new Promise((resolve, reject) => {
base64ToPath(base64Img)
.then((path) => {
console.log(path, '到这里了嘛')
return resolve(path)
})
.catch((err) => {
return reject(err)
})
})
}
import { pathToBase64, base64ToPath } from "./image-tools";
// 初始化OSS签名
/*
let fileName = 'jpg'
let fileType = 'LRD-ADMIN/audit'
* fileType 文件存放路径
* fileName 文件类型
*/
const initOssSign = function (ossData, imgData,flag) {
return new Promise(async (resolve, reject) => {
try {
const { accessId, dir, host, policy, signature } = ossData.oss;
const data = {
success_action_status: "200",
key: dir,
OSSAccessKeyId: accessId,
policy: policy,
Signature: signature,
};
if(flag){
const newFile = await imageCompress(imgData)
const config = {
url: host,
dir: dir,
formData: data,
filePath: newFile.path,
};
return resolve(config);
}else{
imgBase64ToFilePath(imgData)
.then((path) => {
const config = {
url: host,
dir: dir,
formData: data,
filePath: path,
};
return resolve(config);
})
.catch((err) => {
console.log(err, "报错了");
reject(err);
});
}
} catch (err) {
console.log(err, "err");
uni.showToast({
icon: "error",
title: "处理签名数据失败",
});
}
});
};
// 文件上传请求
export const UploadFile = function (ossData, imgData,flag) {
// console.log(ossData, "ossDataweb8888");
return new Promise((resolve, reject) => {
initOssSign(ossData, imgData,flag).then((config) => {
const { url, filePath, dir, formData } = config;
uni.showLoading({
title: "加载中...",
});
uni.uploadFile({
url, //仅为示例,非真实的接口地址
filePath,
name: "file",
formData,
success: (res) => {
res.fileUrl = `${url}${dir}`;
return resolve(res);
},
fail: (err) => {
uni.showToast({
icon: "none",
title: "文件上传OSS失败",
});
return reject(err);
},
complete: () => {
uni.hideLoading();
},
});
});
});
};
// Base64转本地图片路径
export const imgBase64ToFilePath = function (base64Img) {
return new Promise((resolve, reject) => {
base64ToPath(base64Img)
.then((path) => {
// console.log(path, '到这里了嘛')
return resolve(path);
})
.catch((err) => {
return reject(err);
});
});
};
/** 图片压缩
* 图片压缩递归,小于1M跳出
* */
const imageCompress = function (file) {
return new Promise((resolve, reject) => {
let { size, path } = file;
let type = path.split(".")[1];
//大于1M进行压缩,
if (size < 5 * 1000 * 1000) {
resolve(file);
return false;
}
uni.compressImage({
src: path,
quality: 80,
success: (res) => {
let newPath = res.tempFilePath + type;
let newName =
res.tempFilePath.split("/")[res.tempFilePath.split("/").length - 1] +
type;
uni.getFileInfo({
filePath: res.tempFilePath,
success: async (info) => {
let newFile = {
...file,
size: info.size,
path: newPath,
name: newName,
tempFilePath: res.tempFilePath,
};
resolve(await imageCompress(newFile));
},
});
},
fail:(err)=>reject(err)
});
});
};
\ No newline at end of file
This diff is collapsed.
import request from '@/utils/request.js'
export default {
/* 初始化 */
async initTabBar(data) {
return request('/pawn/setting/other/switch/loan', 'GET', data);
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
import { convertPromise } from './header.js'
import Permission from '@/js_sdk/wa-permission/permission'
import { SelectLocation } from "./authPerission";
import API from '@/server/common'
// 切换tabBar的显示和隐藏
export const switchShowTabbar = async () => {
const token = uni.getStorageSync('token')
if (!token) {
uni.setTabBarItem({
index: 1,
visible: false
})
} else {
try {
const { success } = await API.initTabBar()
if (success) {
uni.setTabBarItem({
index: 1,
text: '贷款',
visible: true,
})
} else {
uni.setTabBarItem({
index: 1,
visible: false
})
}
} catch (err) {
console.log(err, '错误信息')
}
}
}
// 设备信息
export const loadDevice = async () => {
convertPromise('getSystemInfo').then(result => {
const deviceInfo = {
deviceType: result.deviceType,
appName: result.appName,
deviceId: result.deviceId,
device: result.osName,
deviceName: result.platform,
appVersion: result.appWgtVersion,
osVersion: result.osVersion ? result.osVersion : result.system,
mobileType: result.model,
screenHeight: result.screenHeight,
screenWidth: result.screenWidth,
resolution: result.windowWidth + '*' + result.screenHeight
};
// 本地存储
uni.setStorage({ key: 'm-device-info', data: JSON.stringify(deviceInfo) });
}).catch(err => {
//that.toast('获取设备信息失败')
uni.showModal({
title: '"多典花"想访问您的设备信息',
content: '通过访问您的设备信息,提高您授信通过率。',
showCancel: false,
confirmText: '去设置',
success: function (res) {
if (res.confirm) {
Permission.gotoAppPermissionSetting()
}
}
});
})
}
/** 获取网络信息 */
export const loadNetwork = () => {
convertPromise('getNetworkType').then(result => {
const networkInfo = {
networkStatus: result.networkType
};
// 网络信息存储
uni.setStorage({
key: 'm-network-info',
data: JSON.stringify(networkInfo)
});
}).catch(err => {
console.log(err, '获取网络信息失败')
})
}
/** 获取UDID */
export const loadUuid = () => {
plus.device.getInfo({
success: function (e) {
const deviceInfo = {
token: e.uuid,
};
uni.setStorage({
key: 'm-load-udid',
data: JSON.stringify(deviceInfo)
})
},
fail: function (e) {
console.log('getDeviceInfo failed: ' + JSON.stringify(e));
}
});
}
/** 定位信息 */
export const loadLocation = () => {
// 苹果测试手机如果没有插入手机卡,获取定位之后会解析失败,报错
SelectLocation(() => {
convertPromise('getLocation', {
type: 'wgs84',
geocode: true
}).then(result => {
const locationInfo = {
lat: String(result.latitude),
lng: String(result.longitude)
};
uni.setStorage({ key: 'm-location-info', data: JSON.stringify(locationInfo) });
}).catch(err => {
console.log(err, '获取设备定位信息报错了')
})
})
}
\ No newline at end of file
import { initHeaderDevice, initHeaderInfo} from './header.js'
import { initHeaderDevice, initHeaderInfo } from './header.js'
import api from '@/config/api.js'
const request = async (url, type, data) => {
const baseUrl = api.common
......@@ -15,14 +15,13 @@ const request = async (url, type, data) => {
rd = headerDevice
} else {
const common = initHeaderDevice()
console.log(common,'日===')
console.log(common, '日===')
if (common) {
rd = JSON.stringify(common)
}
}
}
console.log(baseUrl,'日===')
return new Promise((resolve, reject) => {
const token = uni.getStorageSync('token')
const tokenFinance = uni.getStorageSync('tokenFinance')
......@@ -78,11 +77,7 @@ const request = async (url, type, data) => {
}
},
fail: (err) => {
console.log(err, 954)
// return uni.showToast({
// icon:'loading',
// title:'请求失败'
// })
console.log(err, "AJAX请求报错")
reject(err)
}
});
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment