diff --git a/App.vue b/App.vue index cb17a2b..c64ecb2 100644 --- a/App.vue +++ b/App.vue @@ -13,6 +13,7 @@ initEvent } from "@/utils/uniMPevent.js"; let jpushModule = uni.requireNativePlugin("JG-JPush"); + import uniMP from '@/utils/uniMP.js'; // #endif import { checkLogin @@ -115,8 +116,7 @@ let messageID = result.messageID let title = result.title let content = result.content - let extras = result.extras - + let extras = result.extras.type if (result.extras.type == 'ORDER_CREATE' && result.extras.mp3.length > 0) { if (result.extras.mp3[0] == '微信') this.audioTeam.push('/static/audio/wechat.MP3') if (result.extras.mp3[0] == '支付宝') this.audioTeam.push('/static/audio/pay.MP3') @@ -147,11 +147,21 @@ // this.audioTeam.push(result.extras.type); // } } + + console.log("收到消息") + console.log(result) // 点击事件 if (notificationEventType == 'notificationOpened') { - uni.navigateTo({ - url: result.extras.route - }) + if (result.extras.type == 2) { + let data = result.extras.group_data + data.route = result.extras.route + data.type = 2 + uniMP.loadAppletMP(data) + } else { + uni.navigateTo({ + url: result.extras.route + }) + } } }) diff --git a/api/store.js b/api/store.js index e4b2f32..0e0c90b 100644 --- a/api/store.js +++ b/api/store.js @@ -28,6 +28,11 @@ export function getProductParmas(id, data) { noAuth: true }); } + +export function getUnimpInfo() { + return request.get('intention/publish'); +} + /** * 获取店铺推荐商品 * @param int id @@ -567,6 +572,17 @@ export function getParmasValue(id) { noAuth: true }); } + +/** + * 获取参数值列表 + * @param int id + * + */ +export function getIntention(uid) { + return request.get(`intention/info/${uid}`); +} + + /** * 到货通知 * diff --git a/api/user.js b/api/user.js index 41cb19c..d0119f2 100644 --- a/api/user.js +++ b/api/user.js @@ -13,9 +13,9 @@ import Cache from '@/utils/cache'; * 获取版本信息 */ export function Appversion(data) { - return request.get(`app/version`, data, { - noAuth: true - }); + return request.get(`app/version`, data, { + noAuth: true + }); } /** * 获取用户信息 @@ -117,6 +117,17 @@ export function registerForget(data) { noAuth: true }); } + + +/** + * 一键登录 + */ +export function phonelogin(data) { + return request.post("auth/phonelogin", data, { + noAuth: true + }); +} + /** * 获取用户中心菜单 * @@ -257,7 +268,14 @@ export function extractCash(data) { * 申请提现 */ export function getAdminApplyAPI(merId, data) { - return request.get(`admin/${merId}/apply`, data); + return request.get(`admin/${merId}/apply`, data); +} + +/** + * 新商户 + */ +export function isNewMer(uid, mer_id, data) { + return request.post(`auth/guide/${uid}/${mer_id}`, data); } /** * 提现银行/提现最低金额 diff --git a/components/orderGoods/index.vue b/components/orderGoods/index.vue index 2beaad7..164d4d3 100644 --- a/components/orderGoods/index.vue +++ b/components/orderGoods/index.vue @@ -39,7 +39,7 @@ 申请退款 + @click.stop="showTips=true,refundItem=item">申请退款 退款中 x {{item.product_num - item.refund_num}} @@ -113,7 +113,7 @@ 申请退款 + @click.stop="showTips=true,refundItem=item">申请退款 去评价 已评价 @@ -121,6 +121,22 @@ + + + + + 温馨提示 + + + 下单后1小时内申请退款可极速退款 + + + + + + + + @@ -169,14 +185,14 @@ type: String, default: '', }, - pay_type:{ - type: [Number, String], - default: 0, - }, - status:{ - type: [Number, String], - default: 0, - }, + pay_type: { + type: [Number, String], + default: 0, + }, + status: { + type: [Number, String], + default: 0, + }, jump: { type: Boolean, default: false, @@ -187,14 +203,16 @@ return {}; } }, - sale_type: { - type: [Number, String], - default: 1, - }, + sale_type: { + type: [Number, String], + default: 1, + }, }, computed: mapGetters(['viewColor']), data() { return { + showTips: false, //退款提示弹窗 + refundItem: null, domain: HTTP_REQUEST_URL, totalNmu: '', isTimePay: false, //是否到支付时间 @@ -245,7 +263,8 @@ let id = res.data.product_assist_set_id; uni.hideLoading(); uni.navigateTo({ - url: '/pages/activity/assist_detail/index?id=' + id + '&sale_type=' + this.sale_type + url: '/pages/activity/assist_detail/index?id=' + id + + '&sale_type=' + this.sale_type }); }).catch((err) => { uni.showToast({ @@ -257,6 +276,7 @@ }, // 退款 refund(item) { + if (this.showTips) this.showTips = false; // #ifdef MP openOrderRefundSubscribe().then(() => { uni.hideLoading(); @@ -281,12 +301,14 @@ if (this.evaluate == 0 || this.evaluate == 9 || this.orderData.is_virtual != 0) { uni.navigateTo({ url: '/pages/users/refund/confirm?order_id=' + this.orderId + '&type=1' + '&ids=' + item - .order_product_id + '&refund_type=1&order_type=' + this.orderData.order_type + '&sale_type=' + this.sale_type + .order_product_id + '&refund_type=1&order_type=' + this.orderData.order_type + + '&sale_type=' + this.sale_type }) } else { uni.navigateTo({ url: '/pages/users/refund/select?order_id=' + this.orderId + '&type=1&order_type=' + this - .orderData.order_type + '&ids=' + item.order_product_id + '&sale_type=' + this.sale_type + .orderData.order_type + '&ids=' + item.order_product_id + '&sale_type=' + this + .sale_type }) } // #endif @@ -459,4 +481,21 @@ background: #F0F0F0; } } + + .tips { + width: 590rpx; + height: 354rpx; + background-color: white; + border-radius: 16rpx; + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + box-sizing: border-box; + padding: 50rpx 40rpx; + display: flex; + flex-direction: column; + justify-content: space-between; + align-items: center; + } \ No newline at end of file diff --git a/manifest.json b/manifest.json index 838486c..aec1b5c 100644 --- a/manifest.json +++ b/manifest.json @@ -1,352 +1,353 @@ { - "name" : "惠农生活", - "appid" : "__UNI__3A527D1", - "description" : "", - "versionName" : "2.0.52", - "versionCode" : 2052, - "transformPx" : false, - /* 5+App特有相关 */ - "app-plus" : { - "titleNView" : true, - "usingComponents" : true, - "nvueCompiler" : "uni-app", - "nvueStyleCompiler" : "uni-app", - "compilerVersion" : 3, - "compatible" : { - "ignoreVersion" : true //true表示忽略版本检查提示框,HBuilderX1.9.0及以上版本支持 - }, - "splashscreen" : { - "alwaysShowBeforeRender" : false, - "waiting" : false, - "autoclose" : true, - "delay" : 0 - }, - /* 模块配置 */ - "modules" : { - "VideoPlayer" : {}, - "OAuth" : {}, - "Payment" : {}, - "Share" : {}, - "iBeacon" : {}, - "Maps" : {}, - "Geolocation" : {}, - "UniMP" : { - "description" : "uni小程序" - }, - "Push" : {}, - "Barcode" : {}, - "Camera" : {} - }, - "safearea" : { - "bottom" : { - "offset" : "none" - } - }, - /* 应用发布信息 */ - "distribute" : { - /* android打包配置 */ - "android" : { - "permissions" : [ - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "", - "" - ], - "abiFilters" : [ "armeabi-v7a", "arm64-v8a", "x86" ], - "permissionExternalStorage" : { - "request" : "none", - "prompt" : "应用保存运行状态等信息,需要获取读写手机存储(系统提示为访问设备上的照片、媒体内容和文件)权限,请允许。" - }, - "permissionPhoneState" : { - "request" : "none" //拨打电话权限关闭 - }, - "minSdkVersion" : 23, - "targetSdkVersion" : 30 - }, - /* ios打包配置 */ - "ios" : { - "privacyDescription" : { - "NSPhotoLibraryUsageDescription" : "上传用户头像保存分享海报", - "NSPhotoLibraryAddUsageDescription" : "上传用户头像保存分享海报", - "NSCameraUsageDescription" : "上传用户头像保存分享海报", - "NSLocationWhenInUseUsageDescription" : "根据客户地理位置推荐最近门店", - "NSLocationAlwaysUsageDescription" : "根据客户地理位置推荐最近门店" - }, - "idfa" : false, - "dSYMs" : false - }, - /* SDK配置 */ - "sdkConfigs" : { - "maps" : { - "amap" : { - "appkey_ios" : "0a3202688624938fd5d2f37b52c30d5d", - "appkey_android" : "0354f5ddc11e2ea76c5aac647f44d945", - "name" : "amapIvoVHpJR" - } - }, - "payment" : { - "weixin" : { - "__platform__" : [ "ios", "android" ], - "appid" : "wx2e8f79ff281284f5", - "UniversalLinks" : "https://shop.lihaink.cn/" - } - }, - "share" : { - "weixin" : { - "appid" : "wx2e8f79ff281284f5", - "UniversalLinks" : "https://shop.lihaink.cn/" - } - }, - "geolocation" : { - "amap" : { - "name" : "amapIvoVHpJR", - "__platform__" : [ "ios", "android" ], - "appkey_ios" : "0a3202688624938fd5d2f37b52c30d5d", - "appkey_android" : "0354f5ddc11e2ea76c5aac647f44d945" - } - }, - "push" : {}, - "oauth" : { - "weixin" : { - "appid" : "wx2e8f79ff281284f5", - "UniversalLinks" : "https://shop.lihaink.cn/" - } - }, - "ad" : {} - }, - "icons" : { - "android" : { - "hdpi" : "unpackage/res/icons/72x72.png", - "xhdpi" : "unpackage/res/icons/96x96.png", - "xxhdpi" : "unpackage/res/icons/144x144.png", - "xxxhdpi" : "unpackage/res/icons/192x192.png" - }, - "ios" : { - "appstore" : "unpackage/res/icons/1024x1024.png", - "ipad" : { - "app" : "unpackage/res/icons/76x76.png", - "app@2x" : "unpackage/res/icons/152x152.png", - "notification" : "unpackage/res/icons/20x20.png", - "notification@2x" : "unpackage/res/icons/40x40.png", - "proapp@2x" : "unpackage/res/icons/167x167.png", - "settings" : "unpackage/res/icons/29x29.png", - "settings@2x" : "unpackage/res/icons/58x58.png", - "spotlight" : "unpackage/res/icons/40x40.png", - "spotlight@2x" : "unpackage/res/icons/80x80.png" - }, - "iphone" : { - "app@2x" : "unpackage/res/icons/120x120.png", - "app@3x" : "unpackage/res/icons/180x180.png", - "notification@2x" : "unpackage/res/icons/40x40.png", - "notification@3x" : "unpackage/res/icons/60x60.png", - "settings@2x" : "unpackage/res/icons/58x58.png", - "settings@3x" : "unpackage/res/icons/87x87.png", - "spotlight@2x" : "unpackage/res/icons/80x80.png", - "spotlight@3x" : "unpackage/res/icons/120x120.png" - } - } - }, - "splashscreen" : { - "useOriginalMsgbox" : true, - "androidStyle" : "common" - } - }, - "nativePlugins" : { - "JG-JCore" : { - "JPUSH_APPKEY_IOS" : "8a5efd65cda14fafa6e64ad3", - "JPUSH_CHANNEL_IOS" : "8a5efd65cda14fafa6e64ad3", - "JPUSH_APPKEY_ANDROID" : "b5f679f4357018605ea6fd2e", - "JPUSH_CHANNEL_ANDROID" : "", - "__plugin_info__" : { - "name" : "JG-JCore", - "description" : "极光推送JCore插件", - "platforms" : "Android,iOS", - "url" : "", - "android_package_name" : "uni.UNI3A527D1", - "ios_bundle_id" : "", - "isCloud" : false, - "bought" : -1, - "pid" : "", - "parameters" : { - "JPUSH_APPKEY_IOS" : { - "des" : "[iOS]极光portal配置应用信息时分配的AppKey", - "key" : "JCore:APP_KEY", - "value" : "daebe19b547c43128796a078" - }, - "JPUSH_CHANNEL_IOS" : { - "des" : "[iOS]用于统计分发渠道,不需要可填默认值developer-default", - "key" : "JCore:CHANNEL", - "value" : "" - }, - "JPUSH_APPKEY_ANDROID" : { - "des" : "[Android]极光portal配置应用信息时分配的AppKey", - "key" : "JPUSH_APPKEY", - "value" : "" - }, - "JPUSH_CHANNEL_ANDROID" : { - "des" : "[Android]用于统计分发渠道,不需要可填默认值developer-default", - "key" : "JPUSH_CHANNEL", - "value" : "" - } - } - } - }, - "JG-JPush" : { - "JPUSH_ISPRODUCTION_IOS" : "true", - "JPUSH_ADVERTISINGID_IOS" : "", - "JPUSH_DEFAULTINITJPUSH_IOS" : "true", - "JPUSH_OPPO_APPKEY" : "", - "JPUSH_OPPO_APPID" : "", - "JPUSH_OPPO_APPSECRET" : "", - "JPUSH_VIVO_APPKEY" : "", - "JPUSH_VIVO_APPID" : "", - "JPUSH_MEIZU_APPKEY" : "", - "JPUSH_MEIZU_APPID" : "", - "JPUSH_XIAOMI_APPKEY" : "", - "JPUSH_XIAOMI_APPID" : "", - "__plugin_info__" : { - "name" : "JG-JPush", - "description" : "极光推送Hbuilder插件", - "platforms" : "Android,iOS", - "url" : "", - "android_package_name" : "uni.UNI3A527D1", - "ios_bundle_id" : "", - "isCloud" : false, - "bought" : -1, - "pid" : "", - "parameters" : { - "JPUSH_ISPRODUCTION_IOS" : { - "des" : "[iOS]是否是生产环境,是填true,不是填false或者不填", - "key" : "JPush:ISPRODUCTION", - "value" : "" - }, - "JPUSH_ADVERTISINGID_IOS" : { - "des" : "[iOS]广告标识符(IDFA)如果不需要使用IDFA,可不填", - "key" : "JPush:ADVERTISINGID", - "value" : "" - }, - "JPUSH_DEFAULTINITJPUSH_IOS" : { - "des" : "[iOS]是否默认初始化,是填true,不是填false或者不填", - "key" : "JPush:DEFAULTINITJPUSH", - "value" : "" - }, - "JPUSH_OPPO_APPKEY" : { - "des" : "厂商OPPO-appkey,示例:OP-12345678", - "key" : "OPPO_APPKEY", - "value" : "" - }, - "JPUSH_OPPO_APPID" : { - "des" : "厂商OPPO-appId,示例:OP-12345678", - "key" : "OPPO_APPID", - "value" : "" - }, - "JPUSH_OPPO_APPSECRET" : { - "des" : "厂商OPPO-appSecret,示例:OP-12345678", - "key" : "OPPO_APPSECRET", - "value" : "" - }, - "JPUSH_VIVO_APPKEY" : { - "des" : "厂商VIVO-appkey,示例:12345678", - "key" : "com.vivo.push.api_key", - "value" : "" - }, - "JPUSH_VIVO_APPID" : { - "des" : "厂商VIVO-appId,示例:12345678", - "key" : "com.vivo.push.app_id", - "value" : "" - }, - "JPUSH_MEIZU_APPKEY" : { - "des" : "厂商MEIZU-appKey,示例:MZ-12345678", - "key" : "MEIZU_APPKEY", - "value" : "" - }, - "JPUSH_MEIZU_APPID" : { - "des" : "厂商MEIZU-appId,示例:MZ-12345678", - "key" : "MEIZU_APPID", - "value" : "" - }, - "JPUSH_XIAOMI_APPKEY" : { - "des" : "厂商XIAOMI-appKey,示例:MI-12345678", - "key" : "XIAOMI_APPKEY", - "value" : "" - }, - "JPUSH_XIAOMI_APPID" : { - "des" : "厂商XIAOMI-appId,示例:MI-12345678", - "key" : "XIAOMI_APPID", - "value" : "" - } - } - } - } - } - }, - /* 快应用特有相关 */ - "quickapp" : {}, - /* 小程序特有相关 */ - "mp-weixin" : { - "appid" : "wx5fb1cc8edb3f8baa", - "setting" : { - "urlCheck" : false, - "minified" : true, - "postcss" : true, - "es6" : true - }, - "permission" : { - "scope.userLocation" : { - "desc" : "获取您的位置" - } - }, - "requiredPrivateInfos" : [ "getLocation", "chooseAddress" ], - "usingComponents" : true, - "__usePrivacyCheck__" : true - }, - "mp-alipay" : { - "usingComponents" : true - }, - "mp-baidu" : { - "usingComponents" : true - }, - "mp-toutiao" : { - "usingComponents" : true - }, - "h5" : { - "devServer" : { - "https" : false - }, - "router" : { - "mode" : "history", - "base" : "" - }, - "domain" : "", - "sdkConfigs" : { - "maps" : { - "qqmap" : { - "key" : "SMJBZ-WCHK4-ZPZUA-DSIXI-XDDVQ-XWFX7" - } - } - }, - "title" : "加载中...", - "template" : "template.h5.html", - "optimization" : { - "treeShaking" : { - "enable" : true - } - } - } + "name": "惠农生活", + "appid": "__UNI__3A527D1", + "description": "", + "versionName": "2.0.53", + "versionCode": 2053, + "transformPx": false, + /* 5+App特有相关 */ + "app-plus": { + "titleNView": true, + "usingComponents": true, + "nvueCompiler": "uni-app", + "nvueStyleCompiler": "uni-app", + "compilerVersion": 3, + "compatible": { + "ignoreVersion": true //true表示忽略版本检查提示框,HBuilderX1.9.0及以上版本支持 + }, + "splashscreen": { + "alwaysShowBeforeRender": false, + "waiting": false, + "autoclose": true, + "delay": 0 + }, + /* 模块配置 */ + "modules": { + "VideoPlayer": {}, + "OAuth": {}, + "Payment": {}, + "Share": {}, + "iBeacon": {}, + "Maps": {}, + "Geolocation": {}, + "UniMP": { + "description": "uni小程序" + }, + "Push": {}, + "Barcode": {}, + "Camera": {} + }, + "safearea": { + "bottom": { + "offset": "none" + } + }, + /* 应用发布信息 */ + "distribute": { + /* android打包配置 */ + "android": { + "permissions": [ + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "", + "" + ], + "abiFilters": ["armeabi-v7a", "arm64-v8a", "x86"], + "permissionExternalStorage": { + "request": "none", + "prompt": "应用保存运行状态等信息,需要获取读写手机存储(系统提示为访问设备上的照片、媒体内容和文件)权限,请允许。" + }, + "permissionPhoneState": { + "request": "none" //拨打电话权限关闭 + }, + "minSdkVersion": 23, + "targetSdkVersion": 30 + }, + /* ios打包配置 */ + "ios": { + "privacyDescription": { + "NSPhotoLibraryUsageDescription": "上传用户头像保存分享海报", + "NSPhotoLibraryAddUsageDescription": "上传用户头像保存分享海报", + "NSCameraUsageDescription": "上传用户头像保存分享海报", + "NSLocationWhenInUseUsageDescription": "根据客户地理位置推荐最近门店", + "NSLocationAlwaysUsageDescription": "根据客户地理位置推荐最近门店" + }, + "idfa": false, + "dSYMs": false + }, + /* SDK配置 */ + "sdkConfigs": { + "maps": { + "amap": { + "appkey_ios": "0a3202688624938fd5d2f37b52c30d5d", + "appkey_android": "0354f5ddc11e2ea76c5aac647f44d945", + "name": "amapIvoVHpJR" + } + }, + "payment": { + "weixin": { + "__platform__": ["ios", "android"], + "appid": "wx2e8f79ff281284f5", + "UniversalLinks": "https://shop.lihaink.cn/" + } + }, + "share": { + "weixin": { + "appid": "wx2e8f79ff281284f5", + "UniversalLinks": "https://shop.lihaink.cn/" + } + }, + "geolocation": { + "amap": { + "name": "amapIvoVHpJR", + "__platform__": ["ios", "android"], + "appkey_ios": "0a3202688624938fd5d2f37b52c30d5d", + "appkey_android": "0354f5ddc11e2ea76c5aac647f44d945" + } + }, + "push": {}, + "oauth": { + "weixin": { + "appid": "wx2e8f79ff281284f5", + "UniversalLinks": "https://shop.lihaink.cn/" + }, + "univerify": {} + }, + "ad": {} + }, + "icons": { + "android": { + "hdpi": "unpackage/res/icons/72x72.png", + "xhdpi": "unpackage/res/icons/96x96.png", + "xxhdpi": "unpackage/res/icons/144x144.png", + "xxxhdpi": "unpackage/res/icons/192x192.png" + }, + "ios": { + "appstore": "unpackage/res/icons/1024x1024.png", + "ipad": { + "app": "unpackage/res/icons/76x76.png", + "app@2x": "unpackage/res/icons/152x152.png", + "notification": "unpackage/res/icons/20x20.png", + "notification@2x": "unpackage/res/icons/40x40.png", + "proapp@2x": "unpackage/res/icons/167x167.png", + "settings": "unpackage/res/icons/29x29.png", + "settings@2x": "unpackage/res/icons/58x58.png", + "spotlight": "unpackage/res/icons/40x40.png", + "spotlight@2x": "unpackage/res/icons/80x80.png" + }, + "iphone": { + "app@2x": "unpackage/res/icons/120x120.png", + "app@3x": "unpackage/res/icons/180x180.png", + "notification@2x": "unpackage/res/icons/40x40.png", + "notification@3x": "unpackage/res/icons/60x60.png", + "settings@2x": "unpackage/res/icons/58x58.png", + "settings@3x": "unpackage/res/icons/87x87.png", + "spotlight@2x": "unpackage/res/icons/80x80.png", + "spotlight@3x": "unpackage/res/icons/120x120.png" + } + } + }, + "splashscreen": { + "useOriginalMsgbox": true, + "androidStyle": "common" + } + }, + "nativePlugins": { + "JG-JCore": { + "JPUSH_APPKEY_IOS": "8a5efd65cda14fafa6e64ad3", + "JPUSH_CHANNEL_IOS": "8a5efd65cda14fafa6e64ad3", + "JPUSH_APPKEY_ANDROID": "b5f679f4357018605ea6fd2e", + "JPUSH_CHANNEL_ANDROID": "", + "__plugin_info__": { + "name": "JG-JCore", + "description": "极光推送JCore插件", + "platforms": "Android,iOS", + "url": "", + "android_package_name": "uni.UNI3A527D1", + "ios_bundle_id": "", + "isCloud": false, + "bought": -1, + "pid": "", + "parameters": { + "JPUSH_APPKEY_IOS": { + "des": "[iOS]极光portal配置应用信息时分配的AppKey", + "key": "JCore:APP_KEY", + "value": "daebe19b547c43128796a078" + }, + "JPUSH_CHANNEL_IOS": { + "des": "[iOS]用于统计分发渠道,不需要可填默认值developer-default", + "key": "JCore:CHANNEL", + "value": "" + }, + "JPUSH_APPKEY_ANDROID": { + "des": "[Android]极光portal配置应用信息时分配的AppKey", + "key": "JPUSH_APPKEY", + "value": "" + }, + "JPUSH_CHANNEL_ANDROID": { + "des": "[Android]用于统计分发渠道,不需要可填默认值developer-default", + "key": "JPUSH_CHANNEL", + "value": "" + } + } + } + }, + "JG-JPush": { + "JPUSH_ISPRODUCTION_IOS": "true", + "JPUSH_ADVERTISINGID_IOS": "", + "JPUSH_DEFAULTINITJPUSH_IOS": "true", + "JPUSH_OPPO_APPKEY": "", + "JPUSH_OPPO_APPID": "", + "JPUSH_OPPO_APPSECRET": "", + "JPUSH_VIVO_APPKEY": "", + "JPUSH_VIVO_APPID": "", + "JPUSH_MEIZU_APPKEY": "", + "JPUSH_MEIZU_APPID": "", + "JPUSH_XIAOMI_APPKEY": "", + "JPUSH_XIAOMI_APPID": "", + "__plugin_info__": { + "name": "JG-JPush", + "description": "极光推送Hbuilder插件", + "platforms": "Android,iOS", + "url": "", + "android_package_name": "uni.UNI3A527D1", + "ios_bundle_id": "", + "isCloud": false, + "bought": -1, + "pid": "", + "parameters": { + "JPUSH_ISPRODUCTION_IOS": { + "des": "[iOS]是否是生产环境,是填true,不是填false或者不填", + "key": "JPush:ISPRODUCTION", + "value": "" + }, + "JPUSH_ADVERTISINGID_IOS": { + "des": "[iOS]广告标识符(IDFA)如果不需要使用IDFA,可不填", + "key": "JPush:ADVERTISINGID", + "value": "" + }, + "JPUSH_DEFAULTINITJPUSH_IOS": { + "des": "[iOS]是否默认初始化,是填true,不是填false或者不填", + "key": "JPush:DEFAULTINITJPUSH", + "value": "" + }, + "JPUSH_OPPO_APPKEY": { + "des": "厂商OPPO-appkey,示例:OP-12345678", + "key": "OPPO_APPKEY", + "value": "" + }, + "JPUSH_OPPO_APPID": { + "des": "厂商OPPO-appId,示例:OP-12345678", + "key": "OPPO_APPID", + "value": "" + }, + "JPUSH_OPPO_APPSECRET": { + "des": "厂商OPPO-appSecret,示例:OP-12345678", + "key": "OPPO_APPSECRET", + "value": "" + }, + "JPUSH_VIVO_APPKEY": { + "des": "厂商VIVO-appkey,示例:12345678", + "key": "com.vivo.push.api_key", + "value": "" + }, + "JPUSH_VIVO_APPID": { + "des": "厂商VIVO-appId,示例:12345678", + "key": "com.vivo.push.app_id", + "value": "" + }, + "JPUSH_MEIZU_APPKEY": { + "des": "厂商MEIZU-appKey,示例:MZ-12345678", + "key": "MEIZU_APPKEY", + "value": "" + }, + "JPUSH_MEIZU_APPID": { + "des": "厂商MEIZU-appId,示例:MZ-12345678", + "key": "MEIZU_APPID", + "value": "" + }, + "JPUSH_XIAOMI_APPKEY": { + "des": "厂商XIAOMI-appKey,示例:MI-12345678", + "key": "XIAOMI_APPKEY", + "value": "" + }, + "JPUSH_XIAOMI_APPID": { + "des": "厂商XIAOMI-appId,示例:MI-12345678", + "key": "XIAOMI_APPID", + "value": "" + } + } + } + } + } + }, + /* 快应用特有相关 */ + "quickapp": {}, + /* 小程序特有相关 */ + "mp-weixin": { + "appid": "wx5fb1cc8edb3f8baa", + "setting": { + "urlCheck": false, + "minified": true, + "postcss": true, + "es6": true + }, + "permission": { + "scope.userLocation": { + "desc": "获取您的位置" + } + }, + "requiredPrivateInfos": ["getLocation", "chooseAddress"], + "usingComponents": true, + "__usePrivacyCheck__": true + }, + "mp-alipay": { + "usingComponents": true + }, + "mp-baidu": { + "usingComponents": true + }, + "mp-toutiao": { + "usingComponents": true + }, + "h5": { + "devServer": { + "https": false + }, + "router": { + "mode": "history", + "base": "" + }, + "domain": "", + "sdkConfigs": { + "maps": { + "qqmap": { + "key": "SMJBZ-WCHK4-ZPZUA-DSIXI-XDDVQ-XWFX7" + } + } + }, + "title": "加载中...", + "template": "template.h5.html", + "optimization": { + "treeShaking": { + "enable": true + } + } + } } diff --git a/pages.json b/pages.json index 8f2929b..95dee66 100644 --- a/pages.json +++ b/pages.json @@ -19,7 +19,33 @@ "enablePullDownRefresh": true, // #endif "app-plus": { - "scrollIndicator": false //禁用原生导航栏 + "scrollIndicator": false, //禁用原生导航栏 + "subNVues": [{ + "id": "concatIndex", // 唯一标识 + "path": "pages/index/subnvue/concat", // 页面路径 + "type": "popup", + "style": { + "position": "absolute", + "dock": "right", + "width": "750rpx", + "height": "1000px", + "background": "rgba(0,0,0,0.2)" + } + }, + { + "id": "newUser", // 唯一标识 + "path": "pages/index/subnvue/newUser", // 页面路径 + "type": "popup", + "style": { + "position": "absolute", + "dock": "right", + "width": "750rpx", + "height": "1000px", + "background": "rgba(0,0,0,0.2)" + } + } + + ] } } }, { @@ -35,8 +61,21 @@ "enablePullDownRefresh": true, "navigationBarTitleText": "工作台", "navigationStyle": "custom", - "backgroundColorTop": "#40AE36", - "backgroundTextStyle": "light" + "app-plus": { + "scrollIndicator": false, //禁用原生导航栏 + "subNVues": [{ + "id": "concat", // 唯一标识 + "path": "pages/gather/subnvue/concat", // 页面路径 + "type": "popup", + "style": { + "position": "absolute", + "dock": "right", + "width": "750rpx", + "height": "1500rpx", + "background": "rgba(0,0,0,0.2)" + } + }] + } } }, { "path": "pages/order_addcart/order_addcart", @@ -56,7 +95,22 @@ "style": { "enablePullDownRefresh": true, "navigationBarTitleText": "个人中心", - "navigationStyle": "custom" + "navigationStyle": "custom", + "app-plus": { + "scrollIndicator": false, //禁用原生导航栏 + "subNVues": [{ + "id": "userSubnvu", // 唯一标识 + "path": "pages/user/subnvue/index", // 页面路径 + "type": "popup", + "style": { + "position": "absolute", + "dock": "right", + "width": "750rpx", + "height": "1500rpx", + "background": "rgba(0,0,0,0.2)" + } + }] + } } }, { @@ -816,7 +870,14 @@ "path": "settled/index", "style": { "navigationBarTitleText": "商家入驻", - "navigationStyle": "custom" + "navigationStyle": "custom", + "enablePullDownRefresh": false + } + }, + { + "path": "settled/index1", + "style": { + "navigationBarTitleText": "商家入驻" } }, { diff --git a/pages/gather/gather.vue b/pages/gather/gather.vue index 8dcaf02..2691c56 100644 --- a/pages/gather/gather.vue +++ b/pages/gather/gather.vue @@ -175,19 +175,18 @@ - - - + + 删除 {{ item.name }} @@ -213,6 +212,7 @@ + 添加 {{ item.name }} @@ -248,6 +248,9 @@ } from "@/api/public"; // #ifdef APP-PLUS import uniMP from '@/utils/uniMP.js'; + import { + isNewMer + } from '@/api/user.js'; // #endif export default { @@ -256,6 +259,8 @@ }, data() { return { + subNVue: null, + elInfo: '', imgUrls: [{ img: 'https://lihai001.oss-cn-chengdu.aliyuncs.com/def/e2f0520240203154207556.png' }], @@ -291,13 +296,23 @@ computed: { ...mapGetters(['userInfo', 'location', 'isLogin']) }, + created() {}, + onLoad() { + this.subNVue = uni.getSubNVueById('concat') + let that = this + uni.$on('diverGatherSubEmit', function(data) { + that.clickMenu(that.nowMenuList[0]) + }) + + }, onShow() { + let that = this this.street = this.$store.state.storage.address.townName; this.getNav(); if (this.isLogin) { this.emptyText = '暂无可用应用' this.jurisdiction = false - this.initAllAppLet(); + this.initAllAppLet(true); } else { this.emptyText = '请登录' this.jurisdiction = true @@ -313,13 +328,38 @@ menu = []; } this.nowMenuList = menu; + + // #ifdef APP-PLUS + if (Boolean(this.userInfo.service?.mer_id)) { + isNewMer(this.userInfo.uid, this.userInfo.service?.mer_id).then( + res => { + if (res.data == 'true') { + setTimeout(() => { + const query = uni.createSelectorQuery().in(this); + query + .select(".gatherDiver") + .boundingClientRect((data) => { + let info = JSON.stringify(data) + that.elInfo = data + that.openDiver() + }) + .exec(); + }, 500) + } + }) + } + // #endif + }, onPullDownRefresh() { this.getUserInfo() uni.stopPullDownRefresh() }, beforeDestroy() {}, - mounted() {}, + onReady() { + // #ifdef APP-PLUS + // #endif + }, // #ifdef APP-PLUS onPageScroll(e) { const scrollTop = e.scrollTop; @@ -346,15 +386,9 @@ } }, methods: { - /** - * 获取个人用户信息 - */ - getUserInfo: function() { - let that = this; - getUserInfo().then(res => { - showTab(res.data); - this.userInfo = res.data; - }); + openDiver() { + this.subNVue.show('zoom-out', 300) + uni.$emit('diverGatherEmit', this.elInfo); }, changeSwiper(e) { if (e.length > 0 && e[1].value) { @@ -430,13 +464,13 @@ } }) }, - initAllAppLet() { + initAllAppLet(flag) { applet().then(res => { this.AllMenuList = res.data; - this.initMenu(); + this.initMenu(flag); this.showControllerAllLet(); }).catch(e => { - console.log(e); + // console.log(e); }) }, // 根据类型来判断是否显示 @@ -450,7 +484,7 @@ } }, // 初始化菜单 - initMenu() { + initMenu(flag = false) { let nowMenu = uni.getStorageSync('gatherMenuList'); try { let list = JSON.parse(nowMenu || '[]'); @@ -460,8 +494,12 @@ if (list.find(t => t.name == item.name)?.name != item.name) all.push(item); else now.push(item) }) + if (flag && !now.length) { + this.$set(now, 0, all[0]) + } this.AllMenuList = all; this.nowMenuList = now; + } catch (e) { this.nowMenuList = []; } @@ -490,7 +528,6 @@ }, getUniMp(data) { let that = this; - // #ifdef APP-PLUS if (data.version) return uniMP.loadAppletMP(data); else switch (data.type) { @@ -510,14 +547,6 @@ return; // #endif // #ifdef H5 - // if (type == 2) { - // this.navigator(`/pages/moreProject/moreProject`); - // } else { - // uni.showToast({ - // icon: 'none', - // title: 'H5不支持打开小程序' - // }) - // } uni.showToast({ icon: 'none', title: 'H5不支持打开小程序' @@ -526,7 +555,6 @@ }, navigator(url, t) { - // if (this.userInfoData.is_wsxx === 0 && t != '商户设置') return Toast("请完善商户信息"); uni.navigateTo({ url: url }) @@ -534,6 +562,8 @@ getUserInfo: function() { let that = this; getUserInfo().then(res => { + showTab(res.data); + that.userInfo = res.data; that.userInfoData = res.data; that.$store.commit('SET_USERINFO', res.data); // console.log(res.data.service); diff --git a/pages/gather/subnvue/concat.nvue b/pages/gather/subnvue/concat.nvue new file mode 100644 index 0000000..6176600 --- /dev/null +++ b/pages/gather/subnvue/concat.nvue @@ -0,0 +1,193 @@ + + + + + \ No newline at end of file diff --git a/pages/helpPeople/helpPeople.vue b/pages/helpPeople/helpPeople.vue index 836f6a4..2422d16 100644 --- a/pages/helpPeople/helpPeople.vue +++ b/pages/helpPeople/helpPeople.vue @@ -18,6 +18,13 @@ 我是农民用户 + + + + 我是商户 + + @@ -37,7 +44,9 @@ url }) }, - navSw(url) { + navSw(url, isNewStore) { + uni.setStorageSync('newStore', Boolean(isNewStore)) + // return uni.switchTab({ url: url }) diff --git a/pages/index/index.vue b/pages/index/index.vue index b49b590..e423478 100644 --- a/pages/index/index.vue +++ b/pages/index/index.vue @@ -11,7 +11,8 @@ + @changeDiy="changeDiy"> + @@ -280,7 +281,7 @@ - + @@ -297,7 +298,8 @@ var statusBarHeight = uni.getSystemInfoSync().statusBarHeight + 'px'; let app = getApp(); import { - getUserInfo + getUserInfo, + isNewMer } from '@/api/user.js'; import { getDiy, @@ -450,6 +452,8 @@ }, data() { return { + subNvue: null, + diverFlag: true, domain: HTTP_REQUEST_URL, couponTypeMsg: { 10: '通用券', @@ -543,7 +547,8 @@ preview: false, isSupport: true, isIndexClick: true, - scrollTop: 0 + scrollTop: 0, + // newStore: }; }, @@ -615,7 +620,14 @@ }; }, // #endif + created(options) { + let routes = getCurrentPages(); // 获取当前打开过的页面路由数组 + let curRoute = routes[routes.length - 1].route //获取当前页面路由 + this.activeRouter = '/' + curRoute + }, onLoad(options) { + + let that = this this._options = options; this.diyId = options.diyId || 0; @@ -633,14 +645,10 @@ that.pageLoad(options); this.$store.dispatch('INIT_CONFIG'); }, - created(options) { - let routes = getCurrentPages(); // 获取当前打开过的页面路由数组 - let curRoute = routes[routes.length - 1].route //获取当前页面路由 - this.activeRouter = '/' + curRoute - }, - onShow() { - let that = this; + onShow() { + if (uni.getStorageSync('newStore')) this.openDiver(); + let that = this; that.isIntegral = uni.getStorageSync('isIntegral') // #ifdef APP-PLUS if (that.appUpdate.openUpgrade == '1') { @@ -688,7 +696,48 @@ }, 50) // #endif }, + methods: { + /*新商户引导页相关*/ + openDiver() { + // #ifdef APP + this.subNvue = uni.getSubNVueById('newUser') + this.subNvue.show('slide-in-left', 300) + uni.$on('offSubnvue', () => { + this.subNvue.hide('slide-out-left') + if (uni.getStorageSync("newStore")) { + uni.switchTab({ + url: '/pages/user/index' + }) + } + }); + // uni.$on('diverIndexSubEmit', () => { + // this.subNvue.hide('slide-out-left') + // uni.switchTab({ + // url: '/pages/gather/gather' + // }) + // }) + // #endif + + }, + /* 新商户发布商品引导页 */ + openListGoodsDiver() { + if (Boolean(this.userInfo.service?.mer_id)) { + uni.$on('diverIndexSubEmit', () => { + this.subNvue.hide('slide-out-left') + uni.switchTab({ + url: '/pages/gather/gather' + }) + }) + isNewMer(this.userInfo.uid, this.userInfo.service?.mer_id).then( + res => { + if (res.data == 'true') { + this.subNvue = uni.getSubNVueById('concatIndex') + this.subNvue.show('slide-in-left', 300) + } + }) + } + }, loadCoupon() { if (!this.showCoupon && !uni.getStorageSync('show_coupon') && uni.getStorageSync('is_new_user')) { getNewPeopleCouponLst().then(res => { @@ -1026,6 +1075,9 @@ showTab(res.data); that.userInfo = res.data; this.$store.commit('SET_USERINFO', res.data); + // #ifdef APP + this.openListGoodsDiver() + // #endif }); }, // 记录会员访问 @@ -1286,6 +1338,9 @@ } } }, + onReady() { + + } }; \ No newline at end of file diff --git a/pages/index/subnvue/newUser.nvue b/pages/index/subnvue/newUser.nvue new file mode 100644 index 0000000..2ac0b25 --- /dev/null +++ b/pages/index/subnvue/newUser.nvue @@ -0,0 +1,166 @@ + + + + + \ No newline at end of file diff --git a/pages/store/applicationRecord/index.vue b/pages/store/applicationRecord/index.vue index f3f47ea..028f5f5 100644 --- a/pages/store/applicationRecord/index.vue +++ b/pages/store/applicationRecord/index.vue @@ -1,7 +1,50 @@ @@ -48,7 +55,9 @@ // | Author: CRMEB Team // +---------------------------------------------------------------------- const app = getApp(); - import { mapGetters} from "vuex"; + import { + mapGetters + } from "vuex"; import sendVerifyCode from "@/mixins/SendVerifyCode"; import { registerVerify, @@ -56,19 +65,25 @@ getCodeApi, getCaptcha } from "@/api/user"; - import { validatorDefaultCatch } from "@/utils/dialog"; + import { + validatorDefaultCatch + } from "@/utils/dialog"; import attrs, { required, alpha_num, chs_phone } from "@/utils/validate"; - import { configMap } from '@/utils'; - import { HTTP_REQUEST_URL } from '@/config/app'; - import Verify from '@/components/verify/verify.vue'; + import { + configMap + } from '@/utils'; + import { + HTTP_REQUEST_URL + } from '@/config/app'; + import Verify from '@/components/verify/verify.vue'; export default { name: "RetrievePassword", - components: { - Verify + components: { + Verify }, mixins: [sendVerifyCode], data: function() { @@ -85,16 +100,14 @@ }; }, computed: configMap(['login_logo'], mapGetters(['viewColor'])), - onReady() { - }, - mounted: function() { - }, + onReady() {}, + mounted: function() {}, methods: { back() { uni.navigateBack(); }, again() { - this.codeUrl = VUE_APP_API_URL + "/captcha?" + this.keyCode + Date.parse(new Date()); + this.codeUrl = VUE_APP_API_URL + "/captcha?" + this.keyCode + Date.parse(new Date()); }, async code(data) { @@ -108,7 +121,7 @@ await registerVerify({ phone: that.account, type: 'change_pwd', - captchaType: 'blockPuzzle', + captchaType: 'blockPuzzle', captchaVerification: data.captchaVerification }) .then(res => { @@ -169,7 +182,7 @@ }) }); }, - success(data) { + success(data) { this.$refs.verify.hide(); this.code(data); }, @@ -180,13 +193,15 @@ }; + \ No newline at end of file diff --git a/pages/users/user_about/index.vue b/pages/users/user_about/index.vue index c6636ac..96ef21c 100644 --- a/pages/users/user_about/index.vue +++ b/pages/users/user_about/index.vue @@ -42,7 +42,9 @@ userOut, getLogout } from '@/api/user.js' - import { mapGetters } from "vuex"; + import { + mapGetters + } from "vuex"; export default { name: 'user_about', data() { @@ -63,7 +65,7 @@ this.setTitle(this.type) }, methods: { - toCancel(){ + toCancel() { uni.redirectTo({ url: '/pages/users/user_about/index?from=the_cancellation_prompt' }) @@ -77,37 +79,41 @@ mask: true }); this.moal = false; - (new Promise(call=>{ + (new Promise(call => { userOut().then(res => { - if(res.data.status === 200){ + if (res.data.status === 200) { uni.hideLoading() call() - }else{ + } else { uni.showModal({ title: '提示', content: res.message, - success: ({confirm}) => { + success: ({ + confirm + }) => { if (confirm) { - userOut({key: res.data.result.key}).then(res => { + userOut({ + key: res.data.result.key + }).then(res => { uni.hideLoading() - if(res.data.status === 200){ + if (res.data.status === 200) { call() - }else{ + } else { this.$util.Tips({ title: res.message }); } }) - }else{ + } else { uni.hideLoading() } } }); } }) - })).then(v=>{ + })).then(v => { this.$store.commit("LOGOUT"); - setTimeout(()=>{ + setTimeout(() => { uni.reLaunch({ url: '/pages/index/index' }); @@ -133,7 +139,7 @@ this.loaded = false; cacheInfo(this.type).then(res => { this.data = res.data[this.type] - if(res.data.title) { + if (res.data.title) { uni.setNavigationBarTitle({ title: res.data.title }) @@ -181,19 +187,23 @@ padding: 30rpx; color: #282828; } + .cancelTxt { overflow: hidden; overflow-y: auto; - image{ + + image { max-width: 100%; } } + .cancel { position: fixed; bottom: 60rpx; left: 0; z-index: 1; width: 100%; + .checkbox { display: flex; align-items: center; @@ -201,21 +211,26 @@ margin: 0 auto; font-size: 24rpx; font-weight: 400; + span { margin-left: 5rpx; } + .font { color: var(--view-theme); font-style: normal; } + .iconfont { font-size: 28rpx; margin-right: 15rpx; } - .icon-xuanzhong1{ + + .icon-xuanzhong1 { color: var(--view-theme); } } + .btn { width: 690rpx; height: 90rpx; @@ -231,6 +246,7 @@ } } } + .outMoal { width: 100%; height: 100%; @@ -242,6 +258,7 @@ display: flex; align-items: center; justify-content: center; + .box { position: fixed; width: 590rpx; @@ -251,15 +268,18 @@ border-radius: 20rpx; text-align: center; padding: 50rpx; + .title { font-size: 30rpx; font-weight: 600; color: #282828; } + .moalBtn { margin-top: 43rpx; display: flex; justify-content: space-between; + .ok { width: 234rpx; height: 66rpx; @@ -269,6 +289,7 @@ line-height: 66rpx; color: var(--view-theme); } + .no { width: 234rpx; height: 66rpx; @@ -281,4 +302,4 @@ } } } - + \ No newline at end of file diff --git a/pages/users/user_info/index.vue b/pages/users/user_info/index.vue index 43a74c5..960ba28 100644 --- a/pages/users/user_info/index.vue +++ b/pages/users/user_info/index.vue @@ -246,14 +246,14 @@ * */ uploadpic: async function() { - // #ifdef APP-PLUS - let result = await this.$store.dispatch("permission/requestPermissions", - 'CAMERA') - if (result !== 1) return; - result = await this.$store.dispatch("permission/requestPermissions", - 'READ_EXTERNAL_STORAGE') - if (result !== 1) return; - // #endif + // #ifdef APP-PLUS + let result = await this.$store.dispatch("permission/requestPermissions", + 'CAMERA') + if (result !== 1) return; + result = await this.$store.dispatch("permission/requestPermissions", + 'READ_EXTERNAL_STORAGE') + if (result !== 1) return; + // #endif let that = this; if (that.open_update_info == 0) { return; @@ -354,7 +354,7 @@ title: '提示', content: '确认退出登录?', success: function(res) { - uni.setStorageSync('tabbar_sale_type', 1); + uni.setStorageSync('tabbar_sale_type', 1); if (res.confirm) { getLogout() .then(res => { @@ -677,10 +677,11 @@ width: 690rpx; height: 90rpx; border-radius: 45rpx; - margin: 80rpx auto 0 auto; + margin: 80rpx auto 40rpx auto; color: var(--view-theme); background-color: #ffffff; border: 1px solid var(--view-theme); + } .avatar-box { diff --git a/static/css/base.css b/static/css/base.css index 1fc7ce7..38d2842 100644 --- a/static/css/base.css +++ b/static/css/base.css @@ -412,4 +412,15 @@ checkbox .uni-checkbox-input.uni-checkbox-input-checked::before { width: 100%; height: 80rpx; overflow: hidden +} + + +@font-face { + font-family: PF; + src: url('/static/font/PingFangMedium.ttf'); +} + +@font-face { + font-family: PFR; + src: url('/static/font/PingFangRegular.ttf'); } \ No newline at end of file diff --git a/static/font/PingFangMedium.ttf b/static/font/PingFangMedium.ttf new file mode 100644 index 0000000..e7a83ac Binary files /dev/null and b/static/font/PingFangMedium.ttf differ diff --git a/static/font/PingFangRegular.ttf b/static/font/PingFangRegular.ttf new file mode 100644 index 0000000..cb66bdd Binary files /dev/null and b/static/font/PingFangRegular.ttf differ diff --git a/static/images/YDT.png b/static/images/YDT.png new file mode 100644 index 0000000..5fcaa8b Binary files /dev/null and b/static/images/YDT.png differ diff --git a/static/images/diverPointer.png b/static/images/diverPointer.png new file mode 100644 index 0000000..edd4fad Binary files /dev/null and b/static/images/diverPointer.png differ diff --git a/static/images/eye.png b/static/images/eye.png new file mode 100644 index 0000000..2dd5181 Binary files /dev/null and b/static/images/eye.png differ diff --git a/static/images/greenLine.png b/static/images/greenLine.png new file mode 100644 index 0000000..f7d7d09 Binary files /dev/null and b/static/images/greenLine.png differ diff --git a/static/images/greenLineDown.png b/static/images/greenLineDown.png new file mode 100644 index 0000000..46cc650 Binary files /dev/null and b/static/images/greenLineDown.png differ diff --git a/static/images/offeye.png b/static/images/offeye.png new file mode 100644 index 0000000..c391c3d Binary files /dev/null and b/static/images/offeye.png differ diff --git a/static/images/pointer.png b/static/images/pointer.png new file mode 100644 index 0000000..251271c Binary files /dev/null and b/static/images/pointer.png differ diff --git a/static/images/starpng.png b/static/images/starpng.png new file mode 100644 index 0000000..51c1e52 Binary files /dev/null and b/static/images/starpng.png differ diff --git a/static/images/tabSc.png b/static/images/tabSc.png new file mode 100644 index 0000000..5a4ff90 Binary files /dev/null and b/static/images/tabSc.png differ diff --git a/static/images/ydwd.png b/static/images/ydwd.png new file mode 100644 index 0000000..5a4ff90 Binary files /dev/null and b/static/images/ydwd.png differ diff --git a/store/modules/app.js b/store/modules/app.js index 6d58ea6..294527c 100644 --- a/store/modules/app.js +++ b/store/modules/app.js @@ -9,17 +9,19 @@ // +---------------------------------------------------------------------- import { getUserInfo, - Appversion + Appversion } from "../../api/user.js"; import { LOGIN_STATUS, UID, - USER_INFO + USER_INFO } from '../../config/cache'; import Cache from '../../utils/cache'; // #ifdef APP-PLUS import Updater from '@/uni_modules/guyue-updater/index'; -import { Toast } from "../../libs/uniApi.js"; +import { + Toast +} from "../../libs/uniApi.js"; // #endif @@ -28,42 +30,44 @@ const state = { token: Cache.get(LOGIN_STATUS) || null, uuid: uni.getStorageSync('uuid') || "", backgroundColor: "#fff", - userInfo: (typeof Cache.get('USER_INFO') == 'string' ? JSON.parse(Cache.get('USER_INFO')) : Cache.get('USER_INFO'))||{}, + userInfo: (typeof Cache.get('USER_INFO') == 'string' ? JSON.parse(Cache.get('USER_INFO')) : Cache.get( + 'USER_INFO')) || {}, uid: Cache.get(UID) || null, globalData: uni.getStorageSync('GLOBAL_DATA') || {}, homeActive: false, copyPwd: null, - pageFooter:uni.getStorageSync('pageFoot') || {}, + pageFooter: uni.getStorageSync('pageFoot') || {}, keyColor: Cache.get('KEY_COLOR') || '_default', - viewColor: Cache.get('VIEW_COLOR') || '--view-theme: #E93323;--view-assist:#FF7612;--view-priceColor:#E93323;--view-bgColor:rgba(255, 118, 18,.1);--view-minorColor:rgba(233, 51, 35,.1);--view-bntColor11:#FDA923;--view-bntColor12:#FD6523;--view-bntColor21:#F11B09;--view-bntColor22:#F67A38;', + viewColor: Cache.get('VIEW_COLOR') || + '--view-theme: #E93323;--view-assist:#FF7612;--view-priceColor:#E93323;--view-bgColor:rgba(255, 118, 18,.1);--view-minorColor:rgba(233, 51, 35,.1);--view-bntColor11:#FDA923;--view-bntColor12:#FD6523;--view-bntColor21:#F11B09;--view-bntColor22:#F67A38;', }; const mutations = { - setLocation(state, data) { - state.location = data - Cache.set('LOCATION_DATA', data); - }, + setLocation(state, data) { + state.location = data + Cache.set('LOCATION_DATA', data); + }, LOGIN(state, opt) { state.token = opt.token; Cache.set(LOGIN_STATUS, opt.token, opt.time); uni.removeStorageSync('auth_token'); }, - SET_USERINFO(state, opt){ - state.userInfo = opt; - Cache.set(USER_INFO, opt); - }, - SETUID(state,val){ + SET_USERINFO(state, opt) { + state.userInfo = opt; + Cache.set(USER_INFO, opt); + }, + SETUID(state, val) { state.uid = val; Cache.set(UID, val); }, - SETUUID(state,val){ + SETUUID(state, val) { state.uuid = val; uni.setStorageSync('uuid', val) }, UPDATE_LOGIN(state, token) { state.token = token; }, - + LOGOUT(state) { state.token = null; state.uid = null @@ -99,7 +103,7 @@ const mutations = { uni.setStorageSync('GLOBAL_DATA', key); state.globalData = key; }, - FOOT_UPLOAD(state,data){ + FOOT_UPLOAD(state, data) { state.pageFooter = data } }; @@ -122,78 +126,77 @@ const actions = { }); }, - async INIT_CONFIG({ - state, - commit - }, data = false) { - if(data) { - uni.showLoading({ - title: '加载中' - }) - await uni.$u.sleep(500) - } - - // #ifdef APP-PLUS - let os = uni.getSystemInfoSync(); - let apptype; - if (os.osName == 'ios') { - apptype = 2 - } else { - apptype = 1 - } - console.log({ - version: os.appWgtVersion, - type: apptype, - phone_brand:os.brand - }); - Appversion({ - version: os.appWgtVersion, - type: apptype, - phone_brand:os.brand - }).then((res) => { - console.log(res); - if(data) uni.hideLoading() - if (Object.keys(res.data.appInfo).length > 0) { - // if(res.data.appInfo.version) uni.showLoading({ - // title: '检查更新中' - // }) - // 版本更新 - if (compareVersions(res.data.appInfo.version, os.appWgtVersion) == 1) { - try { - let info = res.data.appInfo || {}; - let version = { - title: info.title || '发现新版本', - content: info.content || '修复了部分BUG', - versionName: info.version || '1.0.1', - brand:res.data.appInfo.phone_brand, - downUrl: info.dow_url || '', - force: info.force == 1 ? true : false, // 是否强制更新 - quiet: info.quiet == 1 ? true : false // 是否静默更新 - } - Updater.update(version,res.data.appInfo); - } catch (e) { - console.log(e); - Toast(e) - } - // uni.hideLoading(); - } - else { - if(data) Toast('已经是最新版本了') - } - - } else { - if(data) Toast('已经是最新版本了') - } - }).catch((err) => { - console.log(err); - if(data) uni.hideLoading() - Toast(err.msg||err.message||err) - // console.log(err) - }) - - - // #endif - } + async INIT_CONFIG({ + state, + commit + }, data = false) { + if (data) { + uni.showLoading({ + title: '加载中' + }) + await uni.$u.sleep(500) + } + + // #ifdef APP-PLUS + let os = uni.getSystemInfoSync(); + let apptype; + if (os.osName == 'ios') { + apptype = 2 + } else { + apptype = 1 + } + // console.log({ + // version: os.appWgtVersion, + // type: apptype, + // phone_brand:os.brand + // }); + Appversion({ + version: os.appWgtVersion, + type: apptype, + phone_brand: os.brand + }).then((res) => { + // console.log(res); + if (data) uni.hideLoading() + if (Object.keys(res.data.appInfo).length > 0) { + // if(res.data.appInfo.version) uni.showLoading({ + // title: '检查更新中' + // }) + // 版本更新 + if (compareVersions(res.data.appInfo.version, os.appWgtVersion) == 1) { + try { + let info = res.data.appInfo || {}; + let version = { + title: info.title || '发现新版本', + content: info.content || '修复了部分BUG', + versionName: info.version || '1.0.1', + brand: res.data.appInfo.phone_brand, + downUrl: info.dow_url || '', + force: info.force == 1 ? true : false, // 是否强制更新 + quiet: info.quiet == 1 ? true : false // 是否静默更新 + } + Updater.update(version, res.data.appInfo); + } catch (e) { + console.log(e); + Toast(e) + } + // uni.hideLoading(); + } else { + if (data) Toast('已经是最新版本了') + } + + } else { + if (data) Toast('已经是最新版本了') + } + }).catch((err) => { + console.log(err); + if (data) uni.hideLoading() + Toast(err.msg || err.message || err) + // console.log(err) + }) + + + // #endif + } }; function compareVersions(version1, version2) { @@ -216,4 +219,4 @@ export default { state, mutations, actions -}; +}; \ No newline at end of file diff --git a/uni.scss b/uni.scss index 1b6e6d5..05ee476 100644 --- a/uni.scss +++ b/uni.scss @@ -15,7 +15,7 @@ /* 颜色变量 */ /* 行为相关颜色 */ -$uni-color-primary: #007aff; +$uni-color-primary: #20B128; $uni-color-success: #4cd964; $uni-color-warning: #f0ad4e; $uni-color-error: #dd524d; diff --git a/uniCloud-aliyun/cloudfunctions/oneClickLoginFn/index.js b/uniCloud-aliyun/cloudfunctions/oneClickLoginFn/index.js new file mode 100644 index 0000000..51899fb --- /dev/null +++ b/uniCloud-aliyun/cloudfunctions/oneClickLoginFn/index.js @@ -0,0 +1,35 @@ +// 下面仅展示客户端使用post方式发送content-type为application/json请求的场景 +exports.main = async (event) => { + let body = event.body + if (event.isBase64Encoded) { + body = Buffer.from(body, 'base64') + } + const { + access_token, + openid + } = JSON.parse(body) + if (!access_token || !openid) { + return { // 不建议把完整手机号返回给前端 + success: false, + error: { + code: 'params is not fund', + message: '参数错误', + } + } + } + const res = await uniCloud.getPhoneNumber({ + provider: 'univerify', + appid: '__UNI__3A527D1', // DCloud appid,不同于callFunction方式调用,使用云函数Url化需要传递DCloud appid参数!!! + access_token: access_token, + openid: openid + }) + console.log(res); // res里包含手机号 + return { // 不建议把完整手机号返回给前端 + success: true, + info: { + code: 0, + message: '获取手机号成功', + data: res, + } + } +} \ No newline at end of file diff --git a/uniCloud-aliyun/cloudfunctions/oneClickLoginFn/package.json b/uniCloud-aliyun/cloudfunctions/oneClickLoginFn/package.json new file mode 100644 index 0000000..7f4ea72 --- /dev/null +++ b/uniCloud-aliyun/cloudfunctions/oneClickLoginFn/package.json @@ -0,0 +1,8 @@ +{ + "name": "oneClickLoginFn", + "dependencies": {}, + "extensions": { + "uni-cloud-jql": {}, + "uni-cloud-verify": {} + } +} \ No newline at end of file diff --git a/uniCloud-aliyun/database/JQL查询.jql b/uniCloud-aliyun/database/JQL查询.jql new file mode 100644 index 0000000..35d21de --- /dev/null +++ b/uniCloud-aliyun/database/JQL查询.jql @@ -0,0 +1,12 @@ +// 本文件用于,使用JQL语法操作项目关联的uniCloud空间的数据库,方便开发调试和远程数据库管理 +// 编写clientDB的js API(也支持常规js语法,比如var),可以对云数据库进行增删改查操作。不支持uniCloud-db组件写法 +// 可以全部运行,也可以选中部分代码运行。点击工具栏上的运行按钮或者按下【F5】键运行代码 +// 如果文档中存在多条JQL语句,只有最后一条语句生效 +// 如果混写了普通js,最后一条语句需是数据库操作语句 +// 此处代码运行不受DB Schema的权限控制,移植代码到实际业务中注意在schema中配好permission +// 不支持clientDB的action +// 数据库查询有最大返回条数限制,详见:https://uniapp.dcloud.net.cn/uniCloud/cf-database.html#limit +// 详细JQL语法,请参考:https://uniapp.dcloud.net.cn/uniCloud/jql.html + +// 下面示例查询uni-id-users表的所有数据 +db.collection('uni-id-users').get(); diff --git a/uni_modules/uni-config-center/changelog.md b/uni_modules/uni-config-center/changelog.md new file mode 100644 index 0000000..57dbcb5 --- /dev/null +++ b/uni_modules/uni-config-center/changelog.md @@ -0,0 +1,6 @@ +## 0.0.3(2022-11-11) +- 修复 config 方法获取根节点为数组格式配置时错误的转化为了对象的Bug +## 0.0.2(2021-04-16) +- 修改插件package信息 +## 0.0.1(2021-03-15) +- 初始化项目 diff --git a/uni_modules/uni-config-center/package.json b/uni_modules/uni-config-center/package.json new file mode 100644 index 0000000..bace866 --- /dev/null +++ b/uni_modules/uni-config-center/package.json @@ -0,0 +1,81 @@ +{ + "id": "uni-config-center", + "displayName": "uni-config-center", + "version": "0.0.3", + "description": "uniCloud 配置中心", + "keywords": [ + "配置", + "配置中心" +], + "repository": "", + "engines": { + "HBuilderX": "^3.1.0" + }, +"dcloudext": { + "sale": { + "regular": { + "price": "0.00" + }, + "sourcecode": { + "price": "0.00" + } + }, + "contact": { + "qq": "" + }, + "declaration": { + "ads": "无", + "data": "无", + "permissions": "无" + }, + "npmurl": "", + "type": "unicloud-template-function" + }, + "directories": { + "example": "../../../scripts/dist" + }, + "uni_modules": { + "dependencies": [], + "encrypt": [], + "platforms": { + "cloud": { + "tcb": "y", + "aliyun": "y" + }, + "client": { + "App": { + "app-vue": "u", + "app-nvue": "u" + }, + "H5-mobile": { + "Safari": "u", + "Android Browser": "u", + "微信浏览器(Android)": "u", + "QQ浏览器(Android)": "u" + }, + "H5-pc": { + "Chrome": "u", + "IE": "u", + "Edge": "u", + "Firefox": "u", + "Safari": "u" + }, + "小程序": { + "微信": "u", + "阿里": "u", + "百度": "u", + "字节跳动": "u", + "QQ": "u" + }, + "快应用": { + "华为": "u", + "联盟": "u" + }, + "Vue": { + "vue2": "y", + "vue3": "u" + } + } + } + } +} diff --git a/uni_modules/uni-config-center/readme.md b/uni_modules/uni-config-center/readme.md new file mode 100644 index 0000000..03f7fc2 --- /dev/null +++ b/uni_modules/uni-config-center/readme.md @@ -0,0 +1,93 @@ +# 为什么使用uni-config-center + +实际开发中很多插件需要配置文件才可以正常运行,如果每个插件都单独进行配置的话就会产生下面这样的目录结构 + +```bash +cloudfunctions +└─────common 公共模块 + ├─plugin-a // 插件A对应的目录 + │ ├─index.js + │ ├─config.json // plugin-a对应的配置文件 + │ └─other-file.cert // plugin-a依赖的其他文件 + └─plugin-b // plugin-b对应的目录 + ├─index.js + └─config.json // plugin-b对应的配置文件 +``` + +假设插件作者要发布一个项目模板,里面使用了很多需要配置的插件,无论是作者发布还是用户使用都是一个大麻烦。 + +uni-config-center就是用了统一管理这些配置文件的,使用uni-config-center后的目录结构如下 + +```bash +cloudfunctions +└─────common 公共模块 + ├─plugin-a // 插件A对应的目录 + │ └─index.js + ├─plugin-b // plugin-b对应的目录 + │ └─index.js + └─uni-config-center + ├─index.js // config-center入口文件 + ├─plugin-a + │ ├─config.json // plugin-a对应的配置文件 + │ └─other-file.cert // plugin-a依赖的其他文件 + └─plugin-b + └─config.json // plugin-b对应的配置文件 +``` + +使用uni-config-center后的优势 + +- 配置文件统一管理,分离插件主体和配置信息,更新插件更方便 +- 支持对config.json设置schema,插件使用者在HBuilderX内编写config.json文件时会有更好的提示(后续HBuilderX会提供支持) + +# 用法 + +在要使用uni-config-center的公共模块或云函数内引入uni-config-center依赖,请参考:[使用公共模块](https://uniapp.dcloud.net.cn/uniCloud/cf-common) + +```js +const createConfig = require('uni-config-center') + +const uniIdConfig = createConfig({ + pluginId: 'uni-id', // 插件id + defaultConfig: { // 默认配置 + tokenExpiresIn: 7200, + tokenExpiresThreshold: 600, + }, + customMerge: function(defaultConfig, userConfig) { // 自定义默认配置和用户配置的合并规则,不设置的情况侠会对默认配置和用户配置进行深度合并 + // defaudltConfig 默认配置 + // userConfig 用户配置 + return Object.assign(defaultConfig, userConfig) + } +}) + + +// 以如下配置为例 +// { +// "tokenExpiresIn": 7200, +// "passwordErrorLimit": 6, +// "bindTokenToDevice": false, +// "passwordErrorRetryTime": 3600, +// "app-plus": { +// "tokenExpiresIn": 2592000 +// }, +// "service": { +// "sms": { +// "codeExpiresIn": 300 +// } +// } +// } + +// 获取配置 +uniIdConfig.config() // 获取全部配置,注意:uni-config-center内不存在对应插件目录时会返回空对象 +uniIdConfig.config('tokenExpiresIn') // 指定键值获取配置,返回:7200 +uniIdConfig.config('service.sms.codeExpiresIn') // 指定键值获取配置,返回:300 +uniIdConfig.config('tokenExpiresThreshold', 600) // 指定键值获取配置,如果不存在则取传入的默认值,返回:600 + +// 获取文件绝对路径 +uniIdConfig.resolve('custom-token.js') // 获取uni-config-center/uni-id/custom-token.js文件的路径 + +// 引用文件(require) +uniIDConfig.requireFile('custom-token.js') // 使用require方式引用uni-config-center/uni-id/custom-token.js文件。文件不存在时返回undefined,文件内有其他错误导致require失败时会抛出错误。 + +// 判断是否包含某文件 +uniIDConfig.hasFile('custom-token.js') // 配置目录是否包含某文件,true: 文件存在,false: 文件不存在 +``` \ No newline at end of file diff --git a/uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/index.js b/uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/index.js new file mode 100644 index 0000000..00ba62f --- /dev/null +++ b/uni_modules/uni-config-center/uniCloud/cloudfunctions/common/uni-config-center/index.js @@ -0,0 +1 @@ +"use strict";var t=require("fs"),r=require("path");function e(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var n=e(t),o=e(r),i="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var u=function(t){var r={exports:{}};return t(r,r.exports),r.exports}((function(t,r){var e="__lodash_hash_undefined__",n=9007199254740991,o="[object Arguments]",u="[object Function]",c="[object Object]",a=/^\[object .+?Constructor\]$/,f=/^(?:0|[1-9]\d*)$/,s={};s["[object Float32Array]"]=s["[object Float64Array]"]=s["[object Int8Array]"]=s["[object Int16Array]"]=s["[object Int32Array]"]=s["[object Uint8Array]"]=s["[object Uint8ClampedArray]"]=s["[object Uint16Array]"]=s["[object Uint32Array]"]=!0,s[o]=s["[object Array]"]=s["[object ArrayBuffer]"]=s["[object Boolean]"]=s["[object DataView]"]=s["[object Date]"]=s["[object Error]"]=s[u]=s["[object Map]"]=s["[object Number]"]=s[c]=s["[object RegExp]"]=s["[object Set]"]=s["[object String]"]=s["[object WeakMap]"]=!1;var l="object"==typeof i&&i&&i.Object===Object&&i,h="object"==typeof self&&self&&self.Object===Object&&self,p=l||h||Function("return this")(),_=r&&!r.nodeType&&r,v=_&&t&&!t.nodeType&&t,d=v&&v.exports===_,y=d&&l.process,g=function(){try{var t=v&&v.require&&v.require("util").types;return t||y&&y.binding&&y.binding("util")}catch(t){}}(),b=g&&g.isTypedArray;function j(t,r,e){switch(e.length){case 0:return t.call(r);case 1:return t.call(r,e[0]);case 2:return t.call(r,e[0],e[1]);case 3:return t.call(r,e[0],e[1],e[2])}return t.apply(r,e)}var w,O,m,A=Array.prototype,z=Function.prototype,M=Object.prototype,x=p["__core-js_shared__"],C=z.toString,F=M.hasOwnProperty,U=(w=/[^.]+$/.exec(x&&x.keys&&x.keys.IE_PROTO||""))?"Symbol(src)_1."+w:"",S=M.toString,I=C.call(Object),P=RegExp("^"+C.call(F).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),T=d?p.Buffer:void 0,q=p.Symbol,E=p.Uint8Array,$=T?T.allocUnsafe:void 0,D=(O=Object.getPrototypeOf,m=Object,function(t){return O(m(t))}),k=Object.create,B=M.propertyIsEnumerable,N=A.splice,L=q?q.toStringTag:void 0,R=function(){try{var t=vt(Object,"defineProperty");return t({},"",{}),t}catch(t){}}(),G=T?T.isBuffer:void 0,V=Math.max,W=Date.now,H=vt(p,"Map"),J=vt(Object,"create"),K=function(){function t(){}return function(r){if(!xt(r))return{};if(k)return k(r);t.prototype=r;var e=new t;return t.prototype=void 0,e}}();function Q(t){var r=-1,e=null==t?0:t.length;for(this.clear();++r-1},X.prototype.set=function(t,r){var e=this.__data__,n=nt(e,t);return n<0?(++this.size,e.push([t,r])):e[n][1]=r,this},Y.prototype.clear=function(){this.size=0,this.__data__={hash:new Q,map:new(H||X),string:new Q}},Y.prototype.delete=function(t){var r=_t(this,t).delete(t);return this.size-=r?1:0,r},Y.prototype.get=function(t){return _t(this,t).get(t)},Y.prototype.has=function(t){return _t(this,t).has(t)},Y.prototype.set=function(t,r){var e=_t(this,t),n=e.size;return e.set(t,r),this.size+=e.size==n?0:1,this},Z.prototype.clear=function(){this.__data__=new X,this.size=0},Z.prototype.delete=function(t){var r=this.__data__,e=r.delete(t);return this.size=r.size,e},Z.prototype.get=function(t){return this.__data__.get(t)},Z.prototype.has=function(t){return this.__data__.has(t)},Z.prototype.set=function(t,r){var e=this.__data__;if(e instanceof X){var n=e.__data__;if(!H||n.length<199)return n.push([t,r]),this.size=++e.size,this;e=this.__data__=new Y(n)}return e.set(t,r),this.size=e.size,this};var it,ut=function(t,r,e){for(var n=-1,o=Object(t),i=e(t),u=i.length;u--;){var c=i[it?u:++n];if(!1===r(o[c],c,o))break}return t};function ct(t){return null==t?void 0===t?"[object Undefined]":"[object Null]":L&&L in Object(t)?function(t){var r=F.call(t,L),e=t[L];try{t[L]=void 0;var n=!0}catch(t){}var o=S.call(t);n&&(r?t[L]=e:delete t[L]);return o}(t):function(t){return S.call(t)}(t)}function at(t){return Ct(t)&&ct(t)==o}function ft(t){return!(!xt(t)||function(t){return!!U&&U in t}(t))&&(zt(t)?P:a).test(function(t){if(null!=t){try{return C.call(t)}catch(t){}try{return t+""}catch(t){}}return""}(t))}function st(t){if(!xt(t))return function(t){var r=[];if(null!=t)for(var e in Object(t))r.push(e);return r}(t);var r=yt(t),e=[];for(var n in t)("constructor"!=n||!r&&F.call(t,n))&&e.push(n);return e}function lt(t,r,e,n,o){t!==r&&ut(r,(function(i,u){if(o||(o=new Z),xt(i))!function(t,r,e,n,o,i,u){var a=gt(t,e),f=gt(r,e),s=u.get(f);if(s)return void rt(t,e,s);var l=i?i(a,f,e+"",t,r,u):void 0,h=void 0===l;if(h){var p=Ot(f),_=!p&&At(f),v=!p&&!_&&Ft(f);l=f,p||_||v?Ot(a)?l=a:Ct(j=a)&&mt(j)?l=function(t,r){var e=-1,n=t.length;r||(r=Array(n));for(;++e-1&&t%1==0&&t0){if(++r>=800)return arguments[0]}else r=0;return t.apply(void 0,arguments)}}(pt);function jt(t,r){return t===r||t!=t&&r!=r}var wt=at(function(){return arguments}())?at:function(t){return Ct(t)&&F.call(t,"callee")&&!B.call(t,"callee")},Ot=Array.isArray;function mt(t){return null!=t&&Mt(t.length)&&!zt(t)}var At=G||function(){return!1};function zt(t){if(!xt(t))return!1;var r=ct(t);return r==u||"[object GeneratorFunction]"==r||"[object AsyncFunction]"==r||"[object Proxy]"==r}function Mt(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=n}function xt(t){var r=typeof t;return null!=t&&("object"==r||"function"==r)}function Ct(t){return null!=t&&"object"==typeof t}var Ft=b?function(t){return function(r){return t(r)}}(b):function(t){return Ct(t)&&Mt(t.length)&&!!s[ct(t)]};function Ut(t){return mt(t)?tt(t,!0):st(t)}var St,It=(St=function(t,r,e){lt(t,r,e)},ht((function(t,r){var e=-1,n=r.length,o=n>1?r[n-1]:void 0,i=n>2?r[2]:void 0;for(o=St.length>3&&"function"==typeof o?(n--,o):void 0,i&&function(t,r,e){if(!xt(e))return!1;var n=typeof r;return!!("number"==n?mt(e)&&dt(r,e.length):"string"==n&&r in e)&&jt(e[r],t)}(r[0],r[1],i)&&(o=n<3?void 0:o,n=1),t=Object(t);++ec.call(t,r);class f{constructor({pluginId:t,defaultConfig:r={},customMerge:e,root:n}){this.pluginId=t,this.defaultConfig=r,this.pluginConfigPath=o.default.resolve(n||__dirname,t),this.customMerge=e,this._config=void 0}resolve(t){return o.default.resolve(this.pluginConfigPath,t)}hasFile(t){return n.default.existsSync(this.resolve(t))}requireFile(t){try{return require(this.resolve(t))}catch(t){if("MODULE_NOT_FOUND"===t.code)return;throw t}}_getUserConfig(){return this.requireFile("config.json")}config(t,r){if(!this._config){const t=this._getUserConfig();this._config=Array.isArray(t)?t:(this.customMerge||u)(this.defaultConfig,t)}let e=this._config;return t?function(t,r,e){if("number"==typeof r)return t[r];if("symbol"==typeof r)return a(t,r)?t[r]:e;const n="string"!=typeof(o=r)?o:o.split(".").reduce(((t,r)=>(r.split(/\[([^}]+)\]/g).forEach((r=>r&&t.push(r))),t)),[]);var o;let i=t;for(let t=0;tparseInt(e)):void 0}function o(e,t){const n=r(e),i=r(t);return n?i?function(e,t){const n=Math.max(e.length,t.length);for(let i=0;ir)return 1;if(n=e)throw new Error("Config error, tokenExpiresThreshold should be less than tokenExpiresIn");t>e/2&&console.warn(`Please check whether the tokenExpiresThreshold configuration is set too large, tokenExpiresThreshold: ${t}, tokenExpiresIn: ${e}`)}get customToken(){return this.uniId.interceptorMap.get("customToken")}isTokenInDb(e){return o(e,"1.0.10")>=0}async getUserRecord(){if(this.userRecord)return this.userRecord;const e=await C.doc(this.uid).get();if(this.userRecord=e.data[0],!this.userRecord)throw{errCode:n.ACCOUNT_NOT_EXISTS};switch(this.userRecord.status){case void 0:case 0:break;case 1:throw{errCode:n.ACCOUNT_BANNED};case 2:throw{errCode:n.ACCOUNT_AUDITING};case 3:throw{errCode:n.ACCOUNT_AUDIT_FAILED};case 4:throw{errCode:n.ACCOUNT_CLOSED}}if(this.oldTokenPayload){if(this.isTokenInDb(this.oldTokenPayload.uniIdVersion)){if(-1===(this.userRecord.token||[]).indexOf(this.oldToken))throw{errCode:n.CHECK_TOKEN_FAILED}}if(this.userRecord.valid_token_date&&this.userRecord.valid_token_date>1e3*this.oldTokenPayload.iat)throw{errCode:n.TOKEN_EXPIRED}}return this.userRecord}async updateUserRecord(e){await C.doc(this.uid).update(e)}async getUserPermission(){if(this.userPermission)return this.userPermission;const e=(await this.getUserRecord()).role||[];if(0===e.length)return this.userPermission={role:[],permission:[]},this.userPermission;if(e.includes("admin"))return this.userPermission={role:e,permission:[]},this.userPermission;const t=await T.where({role_id:_.in(e)}).get(),n=(i=t.data.reduce((e,t)=>(t.permission&&e.push(...t.permission),e),[]),Array.from(new Set(i)));var i;return this.userPermission={role:e,permission:n},this.userPermission}async _createToken({uid:e,role:t,permission:i}={}){if(!t||!i){const e=await this.getUserPermission();t=e.role,i=e.permission}let r={uid:e,role:t,permission:i};if(this.uniId.interceptorMap.has("customToken")){const n=this.uniId.interceptorMap.get("customToken");if("function"!=typeof n)throw new Error("Invalid custom token file");r=await n({uid:e,role:t,permission:i})}const o=Date.now(),{tokenSecret:s,tokenExpiresIn:c,maxTokenLength:a=10}=this.config,u=g({...r,uniIdVersion:"1.0.17"},s,{expiresIn:c}),d=await this.getUserRecord(),l=(d.token||[]).filter(e=>{try{const t=this._checkToken(e);if(d.valid_token_date&&d.valid_token_date>1e3*t.iat)return!1}catch(e){if(e.errCode===n.TOKEN_EXPIRED)return!1}return!0});return l.push(u),l.length>a&&l.splice(0,l.length-a),await this.updateUserRecord({last_login_ip:this.clientInfo.clientIP,last_login_date:o,token:l}),{token:u,tokenExpired:o+1e3*c}}async createToken({uid:e,role:t,permission:i}={}){if(!e)throw{errCode:n.PARAM_REQUIRED,errMsgValue:{param:"uid"}};this.uid=e;const{token:r,tokenExpired:o}=await this._createToken({uid:e,role:t,permission:i});return{errCode:0,token:r,tokenExpired:o}}async refreshToken({token:e}={}){if(!e)throw{errCode:n.PARAM_REQUIRED,errMsgValue:{param:"token"}};this.oldToken=e;const t=this._checkToken(e);this.uid=t.uid,this.oldTokenPayload=t;const{uid:i}=t,{role:r,permission:o}=await this.getUserPermission(),{token:s,tokenExpired:c}=await this._createToken({uid:i,role:r,permission:o});return{errCode:0,token:s,tokenExpired:c}}_checkToken(e){const{tokenSecret:t}=this.config;let i;try{i=k(e,t)}catch(e){if("TokenExpiredError"===e.name)throw{errCode:n.TOKEN_EXPIRED};throw{errCode:n.CHECK_TOKEN_FAILED}}return i}async checkToken(e,{autoRefresh:t=!0}={}){if(!e)throw{errCode:n.PARAM_REQUIRED,errMsgValue:{param:"token"}};this.oldToken=e;const i=this._checkToken(e);this.uid=i.uid,this.oldTokenPayload=i;const{tokenExpiresThreshold:r}=this.config,{uid:o,role:s,permission:c}=i,a={role:s,permission:c};if(!s&&!c){const{role:e,permission:t}=await this.getUserPermission();a.role=e,a.permission=t}if(!r||!t){const e={code:0,errCode:0,...i,...a};return delete e.uniIdVersion,e}const u=Date.now();let d={};1e3*i.exp-u<1e3*r&&(d=await this._createToken({uid:o}));const l={code:0,errCode:0,...i,...a,...d};return delete l.uniIdVersion,l}}var E=Object.freeze({__proto__:null,checkToken:async function(e,{autoRefresh:t=!0}={}){return new m({uniId:this}).checkToken(e,{autoRefresh:t})},createToken:async function({uid:e,role:t,permission:n}={}){return new m({uniId:this}).createToken({uid:e,role:t,permission:n})},refreshToken:async function({token:e}={}){return new m({uniId:this}).refreshToken({token:e})}});const w=require("uni-config-center")({pluginId:"uni-id"});class x{constructor({context:e,clientInfo:t,config:n}={}){this._clientInfo=e?function(e){return{appId:e.APPID,platform:e.PLATFORM,locale:e.LOCALE,clientIP:e.CLIENTIP,deviceId:e.DEVICEID}}(e):t,this._config=n,this.config=this._getOriginConfig(),this.interceptorMap=new Map,w.hasFile("custom-token.js")&&this.setInterceptor("customToken",require(w.resolve("custom-token.js")));this._i18n=uniCloud.initI18n({locale:this._clientInfo.locale,fallbackLocale:"zh-Hans",messages:JSON.parse(JSON.stringify(d))}),d[this._i18n.locale]||this._i18n.setLocale("zh-Hans")}setInterceptor(e,t){this.interceptorMap.set(e,t)}_t(...e){return this._i18n.t(...e)}_parseOriginConfig(e){return Array.isArray(e)?e:e[0]?Object.values(e):e}_getOriginConfig(){if(this._config)return this._config;if(w.hasFile("config.json")){let e;try{e=w.config()}catch(e){throw new Error("Invalid uni-id config file\n"+e.message)}return this._parseOriginConfig(e)}try{return this._parseOriginConfig(require("uni-id/config.json"))}catch(e){throw new Error("Invalid uni-id config file")}}_getAppConfig(){const e=this._getOriginConfig();return Array.isArray(e)?e.find(e=>e.dcloudAppid===this._clientInfo.appId)||e.find(e=>e.isDefaultConfig):e}_getPlatformConfig(){const e=this._getAppConfig();if(!e)throw new Error(`Config for current app (${this._clientInfo.appId}) was not found, please check your config file or client appId`);let t;switch(["app-plus","app-android","app-ios"].indexOf(this._clientInfo.platform)>-1&&(this._clientInfo.platform="app"),"h5"===this._clientInfo.platform&&(this._clientInfo.platform="web"),this._clientInfo.platform){case"web":t="h5";break;case"app":t="app-plus"}const n=[{tokenExpiresIn:7200,tokenExpiresThreshold:1200,passwordErrorLimit:6,passwordErrorRetryTime:3600},e];t&&e[t]&&n.push(e[t]),n.push(e[this._clientInfo.platform]);const i=Object.assign(...n);return["tokenSecret","tokenExpiresIn"].forEach(e=>{if(!i||!i[e])throw new Error(`Config parameter missing, ${e} is required`)}),i}_getConfig(){return this._getPlatformConfig()}}for(const e in E)x.prototype[e]=E[e];function y(e){const t=new x(e);return new Proxy(t,{get(e,t){if(t in e&&0!==t.indexOf("_")){if("function"==typeof e[t])return(n=e[t],function(){let e;try{e=n.apply(this,arguments)}catch(e){if(a(e))return c.call(this,e),e;throw e}return i(e)?e.then(e=>(a(e)&&c.call(this,e),e),e=>{if(a(e))return c.call(this,e),e;throw e}):(a(e)&&c.call(this,e),e)}).bind(e);if("context"!==t&&"config"!==t)return e[t]}var n}})}x.prototype.createInstance=y;const A={createInstance:y};module.exports=A; diff --git a/uni_modules/uni-id-common/uniCloud/cloudfunctions/common/uni-id-common/package.json b/uni_modules/uni-id-common/uniCloud/cloudfunctions/common/uni-id-common/package.json new file mode 100644 index 0000000..4986a12 --- /dev/null +++ b/uni_modules/uni-id-common/uniCloud/cloudfunctions/common/uni-id-common/package.json @@ -0,0 +1 @@ +{"name":"uni-id-common","version":"1.0.17","description":"uni-id token生成、校验、刷新","main":"index.js","homepage":"https://uniapp.dcloud.io/uniCloud/uni-id-common.html","repository":{"type":"git","url":"git+https://gitee.com/dcloud/uni-id-common.git"},"author":"DCloud","license":"Apache-2.0","dependencies":{"uni-config-center":"file:../../../../../uni-config-center/uniCloud/cloudfunctions/common/uni-config-center"}} diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/bridge-error.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/bridge-error.js new file mode 100644 index 0000000..95160a4 --- /dev/null +++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/bridge-error.js @@ -0,0 +1,26 @@ +'use strict'; + +class BridgeError extends Error { + + constructor(code, message) { + super(message) + + this._code = code + } + + get code() { + return this._code + } + + get errCode() { + return this._code + } + + get errMsg() { + return this.message + } +} + +module.exports = { + BridgeError +} diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/config.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/config.js new file mode 100644 index 0000000..d083f00 --- /dev/null +++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/config.js @@ -0,0 +1,124 @@ +'use strict'; + +const { + ProviderType +} = require('./consts.js') + +const configCenter = require('uni-config-center') + +// 多维数据为兼容uni-id以前版本配置 +const OauthConfig = { + 'weixin-app': [ + ['app', 'oauth', 'weixin'], + ['app-plus', 'oauth', 'weixin'] + ], + 'weixin-mp': [ + ['mp-weixin', 'oauth', 'weixin'] + ], + 'weixin-h5': [ + ['web', 'oauth', 'weixin-h5'], + ['h5-weixin', 'oauth', 'weixin'], + ['h5', 'oauth', 'weixin'] + ], + 'weixin-web': [ + ['web', 'oauth', 'weixin-web'] + ], + 'qq-app': [ + ['app', 'oauth', 'qq'], + ['app-plus', 'oauth', 'qq'] + ], + 'qq-mp': [ + ['mp-qq', 'oauth', 'qq'] + ] +} + +const Support_Platforms = [ + ProviderType.WEIXIN_MP, + ProviderType.WEIXIN_H5, + ProviderType.WEIXIN_APP, + ProviderType.WEIXIN_WEB, + ProviderType.QQ_MP, + ProviderType.QQ_APP +] + +class ConfigBase { + + constructor() { + const uniIdConfigCenter = configCenter({ + pluginId: 'uni-id' + }) + + this._uniIdConfig = uniIdConfigCenter.config() + } + + getAppConfig(appid) { + if (Array.isArray(this._uniIdConfig)) { + return this._uniIdConfig.find((item) => { + return (item.dcloudAppid === appid) + }) + } + return this._uniIdConfig + } +} + +class AppConfig extends ConfigBase { + + constructor() { + super() + } + + get(appid, platform) { + if (!this.isSupport(platform)) { + return null + } + + let appConfig = this.getAppConfig(appid) + if (!appConfig) { + return null + } + + return this.getOauthConfig(appConfig, platform) + } + + isSupport(platformName) { + return (Support_Platforms.indexOf(platformName) >= 0) + } + + getOauthConfig(appConfig, platformName) { + let treePath = OauthConfig[platformName] + let node = this.findNode(appConfig, treePath) + if (node && node.appid && node.appsecret) { + return { + appid: node.appid, + secret: node.appsecret + } + } + return null + } + + findNode(treeNode, arrayPath) { + let node = treeNode + for (let treePath of arrayPath) { + for (let name of treePath) { + const currentNode = node[name] + if (currentNode) { + node = currentNode + } else { + node = null + break + } + } + if (node === null) { + node = treeNode + } else { + break + } + } + return node + } +} + + +module.exports = { + AppConfig +}; \ No newline at end of file diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/consts.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/consts.js new file mode 100644 index 0000000..4c666e9 --- /dev/null +++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/consts.js @@ -0,0 +1,30 @@ +'use strict'; + +const TAG = "UNI_OPEN_BRIDGE" + +const HTTP_STATUS = { + SUCCESS: 200 +} + +const ProviderType = { + WEIXIN_MP: 'weixin-mp', + WEIXIN_H5: 'weixin-h5', + WEIXIN_APP: 'weixin-app', + WEIXIN_WEB: 'weixin-web', + QQ_MP: 'qq-mp', + QQ_APP: 'qq-app' +} + +// old +const PlatformType = ProviderType + +const ErrorCodeType = { + SYSTEM_ERROR: TAG + "_SYSTEM_ERROR" +} + +module.exports = { + HTTP_STATUS, + ProviderType, + PlatformType, + ErrorCodeType +} diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/index.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/index.js new file mode 100644 index 0000000..fc23cd9 --- /dev/null +++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/index.js @@ -0,0 +1,317 @@ +'use strict'; + +const { + PlatformType, + ProviderType, + ErrorCodeType +} = require('./consts.js') + +const { + AppConfig +} = require('./config.js') + +const { + Storage +} = require('./storage.js') + +const { + BridgeError +} = require('./bridge-error.js') + +const { + WeixinServer +} = require('./weixin-server.js') + +const appConfig = new AppConfig() + +class AccessToken extends Storage { + + constructor() { + super('access-token', ['provider', 'appid']) + } + + async update(key) { + super.update(key) + + const result = await this.getByWeixinServer(key) + + return this.set(key, result.value, result.duration) + } + + async fallback(key) { + return this.getByWeixinServer(key) + } + + async getByWeixinServer(key) { + const oauthConfig = appConfig.get(key.dcloudAppid, key.provider) + let methodName + if (key.provider === ProviderType.WEIXIN_MP) { + methodName = 'GetMPAccessTokenData' + } else if (key.provider === ProviderType.WEIXIN_H5) { + methodName = 'GetH5AccessTokenData' + } else { + throw new BridgeError(ErrorCodeType.SYSTEM_ERROR, "provider invalid") + } + + const responseData = await WeixinServer[methodName](oauthConfig) + + const duration = responseData.expires_in || (60 * 60 * 2) + delete responseData.expires_in + + return { + value: responseData, + duration + } + } +} + +class UserAccessToken extends Storage { + + constructor() { + super('user-access-token', ['provider', 'appid', 'openid']) + } +} + +class SessionKey extends Storage { + + constructor() { + super('session-key', ['provider', 'appid', 'openid']) + } +} + +class Encryptkey extends Storage { + + constructor() { + super('encrypt-key', ['provider', 'appid', 'openid']) + } + + async update(key) { + super.update(key) + + const result = await this.getByWeixinServer(key) + + return this.set(key, result.value, result.duration) + } + + getKeyString(key) { + return `${super.getKeyString(key)}-${key.version}` + } + + getExpiresIn(value) { + if (value <= 0) { + return 60 + } + return value + } + + async fallback(key) { + return this.getByWeixinServer(key) + } + + async getByWeixinServer(key) { + const accessToken = await Factory.Get(AccessToken, key) + const userSession = await Factory.Get(SessionKey, key) + + const responseData = await WeixinServer.GetUserEncryptKeyData({ + openid: key.openid, + access_token: accessToken.access_token, + session_key: userSession.session_key + }) + + const keyInfo = responseData.key_info_list.find((item) => { + return item.version === key.version + }) + + if (!keyInfo) { + throw new BridgeError(ErrorCodeType.SYSTEM_ERROR, 'key version invalid') + } + + const value = { + encrypt_key: keyInfo.encrypt_key, + iv: keyInfo.iv + } + + return { + value, + duration: keyInfo.expire_in + } + } +} + +class Ticket extends Storage { + + constructor() { + super('ticket', ['provider', 'appid']) + } + + async update(key) { + super.update(key) + + const result = await this.getByWeixinServer(key) + + return this.set(key, result.value, result.duration) + } + + async fallback(key) { + return this.getByWeixinServer(key) + } + + async getByWeixinServer(key) { + const accessToken = await Factory.Get(AccessToken, { + dcloudAppid: key.dcloudAppid, + provider: ProviderType.WEIXIN_H5 + }) + + const responseData = await WeixinServer.GetH5TicketData(accessToken) + + const duration = responseData.expires_in || (60 * 60 * 2) + delete responseData.expires_in + delete responseData.errcode + delete responseData.errmsg + + return { + value: responseData, + duration + } + } +} + + +const Factory = { + + async Get(T, key, fallback) { + Factory.FixOldKey(key) + return Factory.MakeUnique(T).get(key, fallback) + }, + + async Set(T, key, value, expiresIn) { + Factory.FixOldKey(key) + return Factory.MakeUnique(T).set(key, value, expiresIn) + }, + + async Remove(T, key) { + Factory.FixOldKey(key) + return Factory.MakeUnique(T).remove(key) + }, + + async Update(T, key) { + Factory.FixOldKey(key) + return Factory.MakeUnique(T).update(key) + }, + + FixOldKey(key) { + if (!key.provider) { + key.provider = key.platform + } + + const configData = appConfig.get(key.dcloudAppid, key.provider) + if (!configData) { + throw new BridgeError(ErrorCodeType.SYSTEM_ERROR, 'appid or provider invalid') + } + key.appid = configData.appid + }, + + MakeUnique(T) { + return new T() + } +} + + +// exports + +async function getAccessToken(key, fallback) { + return Factory.Get(AccessToken, key, fallback) +} + +async function setAccessToken(key, value, expiresIn) { + return Factory.Set(AccessToken, key, value, expiresIn) +} + +async function removeAccessToken(key) { + return Factory.Remove(AccessToken, key) +} + +async function updateAccessToken(key) { + return Factory.Update(AccessToken, key) +} + +async function getUserAccessToken(key, fallback) { + return Factory.Get(UserAccessToken, key, fallback) +} + +async function setUserAccessToken(key, value, expiresIn) { + return Factory.Set(UserAccessToken, key, value, expiresIn) +} + +async function removeUserAccessToken(key) { + return Factory.Remove(UserAccessToken, key) +} + +async function getSessionKey(key, fallback) { + return Factory.Get(SessionKey, key, fallback) +} + +async function setSessionKey(key, value, expiresIn) { + return Factory.Set(SessionKey, key, value, expiresIn) +} + +async function removeSessionKey(key) { + return Factory.Remove(SessionKey, key) +} + +async function getEncryptKey(key, fallback) { + return Factory.Get(Encryptkey, key, fallback) +} + +async function setEncryptKey(key, value, expiresIn) { + return Factory.Set(Encryptkey, key, value, expiresIn) +} + +async function removeEncryptKey(key) { + return Factory.Remove(Encryptkey, key) +} + +async function updateEncryptKey(key) { + return Factory.Update(Encryptkey, key) +} + +async function getTicket(key, fallback) { + return Factory.Get(Ticket, key, fallback) +} + +async function setTicket(key, value, expiresIn) { + return Factory.Set(Ticket, key, value, expiresIn) +} + +async function removeTicket(key) { + return Factory.Remove(Ticket, key) +} + +async function updateTicket(key) { + return Factory.Update(Ticket, key) +} + +module.exports = { + getAccessToken, + setAccessToken, + removeAccessToken, + updateAccessToken, + getUserAccessToken, + setUserAccessToken, + removeUserAccessToken, + getSessionKey, + setSessionKey, + removeSessionKey, + getEncryptKey, + setEncryptKey, + removeEncryptKey, + updateEncryptKey, + getTicket, + setTicket, + removeTicket, + updateTicket, + ProviderType, + PlatformType, + WeixinServer, + ErrorCodeType +} diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/package.json b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/package.json new file mode 100644 index 0000000..a017b49 --- /dev/null +++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/package.json @@ -0,0 +1,15 @@ +{ + "name": "uni-open-bridge-common", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "uni-config-center": "file:../../../../../uni-config-center/uniCloud/cloudfunctions/common/uni-config-center" + } +} \ No newline at end of file diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/storage.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/storage.js new file mode 100644 index 0000000..bfb13a1 --- /dev/null +++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/storage.js @@ -0,0 +1,111 @@ +'use strict'; + +const { + Validator +} = require('./validator.js') + +const { + CacheKeyCascade +} = require('./uni-cloud-cache.js') + +const { + BridgeError +} = require('./bridge-error.js') + +class Storage { + + constructor(type, keys) { + this._type = type || null + this._keys = keys || [] + } + + async get(key, fallback) { + this.validateKey(key) + const result = await this.create(key, fallback).get() + return result.value + } + + async set(key, value, expiresIn) { + this.validateKey(key) + this.validateValue(value) + const expires_in = this.getExpiresIn(expiresIn) + if (expires_in !== 0) { + await this.create(key).set(this.getValue(value), expires_in) + } + } + + async remove(key) { + this.validateKey(key) + await this.create(key).remove() + } + + // virtual + async update(key) { + this.validateKey(key) + } + + async ttl(key) { + this.validateKey(key) + // 后续考虑支持 + } + + async fallback(key) {} + + getKeyString(key) { + const keyArray = [Storage.Prefix] + this._keys.forEach((name) => { + keyArray.push(key[name]) + }) + keyArray.push(this._type) + return keyArray.join(':') + } + + getValue(value) { + return value + } + + getExpiresIn(value) { + if (value !== undefined) { + return value + } + return -1 + } + + validateKey(key) { + Validator.Key(this._keys, key) + } + + validateValue(value) { + Validator.Value(value) + } + + create(key, fallback) { + const keyString = this.getKeyString(key) + const options = { + layers: [{ + type: 'database', + key: keyString + }, { + type: 'redis', + key: keyString + }] + } + + const _this = this + return new CacheKeyCascade({ + ...options, + fallback: async function() { + if (fallback) { + return fallback(key) + } else if (_this.fallback) { + return _this.fallback(key) + } + } + }) + } +} +Storage.Prefix = "uni-id" + +module.exports = { + Storage +}; diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/uni-cloud-cache.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/uni-cloud-cache.js new file mode 100644 index 0000000..2e4286b --- /dev/null +++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/uni-cloud-cache.js @@ -0,0 +1,324 @@ +const db = uniCloud.database() + +function getType(value) { + return Object.prototype.toString.call(value).slice(8, -1).toLowerCase() +} + +const validator = { + key: function(value) { + const err = new Error('Invalid key') + if (typeof value !== 'string') { + throw err + } + const valueTrim = value.trim() + if (!valueTrim || valueTrim !== value) { + throw err + } + }, + value: function(value) { + // 仅作简单校验 + const type = getType(value) + const validValueType = ['null', 'number', 'string', 'array', 'object'] + if (validValueType.indexOf(type) === -1) { + throw new Error('Invalid value type') + } + }, + duration: function(value) { + const err = new Error('Invalid duration') + if (value === undefined) { + return + } + if (typeof value !== 'number' || value === 0) { + throw err + } + } +} + +/** + * 入库时 expired 为过期时间对应的时间戳,永不过期用-1表示 + * 返回结果时 与redis对齐,-1表示永不过期,-2表示已过期或不存在 + */ +class DatabaseCache { + constructor({ + collection = 'opendb-open-data' + } = {}) { + this.type = 'db' + this.collection = db.collection(collection) + } + + _serializeValue(value) { + return value === undefined ? null : JSON.stringify(value) + } + + _deserializeValue(value) { + return value ? JSON.parse(value) : value + } + + async set(key, value, duration) { + validator.key(key) + validator.value(value) + validator.duration(duration) + value = this._serializeValue(value) + await this.collection.doc(key).set({ + value, + expired: duration && duration !== -1 ? Date.now() + (duration * 1000) : -1 + }) + } + + async _getWithDuration(key) { + const getKeyRes = await this.collection.doc(key).get() + const record = getKeyRes.data[0] + if (!record) { + return { + value: null, + duration: -2 + } + } + const value = this._deserializeValue(record.value) + const expired = record.expired + if (expired === -1) { + return { + value, + duration: -1 + } + } + const duration = expired - Date.now() + if (duration <= 0) { + await this.remove(key) + return { + value: null, + duration: -2 + } + } + return { + value, + duration: Math.floor(duration / 1000) + } + } + + async get(key, { + withDuration = true + } = {}) { + const result = await this._getWithDuration(key) + if (!withDuration) { + delete result.duration + } + return result + } + + async remove(key) { + await this.collection.doc(key).remove() + } +} + +class RedisCache { + constructor() { + this.type = 'redis' + this.redis = uniCloud.redis() + } + + _serializeValue(value) { + return value === undefined ? null : JSON.stringify(value) + } + + _deserializeValue(value) { + return value ? JSON.parse(value) : value + } + + async set(key, value, duration) { + validator.key(key) + validator.value(value) + validator.duration(duration) + value = this._serializeValue(value) + if (!duration || duration === -1) { + await this.redis.set(key, value) + } else { + await this.redis.set(key, value, 'EX', duration) + } + } + + async get(key, { + withDuration = false + } = {}) { + let value = await this.redis.get(key) + value = this._deserializeValue(value) + if (!withDuration) { + return { + value + } + } + const durationSecond = await this.redis.ttl(key) + let duration + switch (durationSecond) { + case -1: + duration = -1 + break + case -2: + duration = -2 + break + default: + duration = durationSecond + break + } + return { + value, + duration + } + } + + async remove(key) { + await this.redis.del(key) + } +} + +class Cache { + constructor({ + type, + collection + } = {}) { + if (type === 'database') { + return new DatabaseCache({ + collection + }) + } else if (type === 'redis') { + return new RedisCache() + } else { + throw new Error('Invalid cache type') + } + } +} + +class CacheKey { + constructor({ + type, + collection, + cache, + key, + fallback + } = {}) { + this.cache = cache || new Cache({ + type, + collection + }) + this.key = key + this.fallback = fallback + } + + async set(value, duration) { + await this.cache.set(this.key, value, duration) + } + + async setWithSync(value, duration, syncMethod) { + await Promise.all([ + this.set(this.key, value, duration), + syncMethod(value, duration) + ]) + } + + async get() { + let { + value, + duration + } = await this.cache.get(this.key) + if (value !== null && value !== undefined) { + return { + value, + duration + } + } + if (!this.fallback) { + return { + value: null, + duration: -2 + } + } + const fallbackResult = await this.fallback() + value = fallbackResult.value + duration = fallbackResult.duration + if (value !== null && duration !== undefined) { + await this.cache.set(this.key, value, duration) + } + return { + value, + duration + } + } + + async remove() { + await this.cache.remove(this.key) + } +} + +class CacheKeyCascade { + constructor({ + layers, // [{cache, type, collection, key}] 从低级到高级排序,[DbCacheKey, RedisCacheKey] + fallback + } = {}) { + this.layers = layers + this.cacheLayers = [] + let lastCacheKey + for (let i = 0; i < layers.length; i++) { + const { + type, + cache, + collection, + key + } = layers[i] + const lastCacheKeyTemp = lastCacheKey + try { + const currentCacheKey = new CacheKey({ + type, + collection, + cache, + key, + fallback: i === 0 ? fallback : function() { + return lastCacheKeyTemp.get() + } + }) + this.cacheLayers.push(currentCacheKey) + lastCacheKey = currentCacheKey + } catch (e) {} + } + this.highLevelCache = lastCacheKey + } + + async set(value, duration) { + return Promise.all( + this.cacheLayers.map(item => { + return item.set(value, duration) + }) + ) + } + + async setWithSync(value, duration, syncMethod) { + const setPromise = this.cacheLayers.map(item => { + return item.set(value, duration) + }) + return Promise.all( + [ + ...setPromise, + syncMethod(value, duration) + ] + ) + } + + async get() { + return this.highLevelCache.get() + } + + async remove() { + await Promise.all( + this.cacheLayers.map(cacheKeyItem => { + return cacheKeyItem.remove() + }) + ) + } +} + +module.exports = { + Cache, + DatabaseCache, + RedisCache, + CacheKey, + CacheKeyCascade +} diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/validator.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/validator.js new file mode 100644 index 0000000..47a455b --- /dev/null +++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/validator.js @@ -0,0 +1,31 @@ +const Validator = { + + Key(keyArray, parameters) { + for (let i = 0; i < keyArray.length; i++) { + const keyName = keyArray[i] + if (typeof parameters[keyName] !== 'string') { + Validator.ThrowNewError(`Invalid ${keyName}`) + } + if (parameters[keyName].length < 1) { + Validator.ThrowNewError(`Invalid ${keyName}`) + } + } + }, + + Value(value) { + if (value === undefined) { + Validator.ThrowNewError('Invalid Value') + } + if (typeof value !== 'object') { + Validator.ThrowNewError('Invalid Value Type') + } + }, + + ThrowNewError(message) { + throw new Error(message) + } +} + +module.exports = { + Validator +} diff --git a/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/weixin-server.js b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/weixin-server.js new file mode 100644 index 0000000..ef476f1 --- /dev/null +++ b/uni_modules/uni-open-bridge-common/uniCloud/cloudfunctions/common/uni-open-bridge-common/weixin-server.js @@ -0,0 +1,203 @@ +'use strict'; + +const crypto = require('crypto') + +const { + HTTP_STATUS +} = require('./consts.js') + +const { + BridgeError +} = require('./bridge-error.js') + +class WeixinServer { + + constructor(options = {}) { + this._appid = options.appid + this._secret = options.secret + } + + getAccessToken() { + return uniCloud.httpclient.request(WeixinServer.AccessToken_Url, { + dataType: 'json', + method: 'POST', + contentType: 'json', + data: { + appid: this._appid, + secret: this._secret, + grant_type: "client_credential" + } + }) + } + + // 使用客户端获取的 code 从微信服务器换取 openid,code 仅可使用一次 + codeToSession(code) { + return uniCloud.httpclient.request(WeixinServer.Code2Session_Url, { + dataType: 'json', + data: { + appid: this._appid, + secret: this._secret, + js_code: code, + grant_type: 'authorization_code' + } + }) + } + + getUserEncryptKey({ + access_token, + openid, + session_key + }) { + console.log(access_token, openid, session_key); + const signature = crypto.createHmac('sha256', session_key).update('').digest('hex') + return uniCloud.httpclient.request(WeixinServer.User_Encrypt_Key_Url, { + dataType: 'json', + method: 'POST', + dataAsQueryString: true, + data: { + access_token, + openid: openid, + signature: signature, + sig_method: 'hmac_sha256' + } + }) + } + + getH5AccessToken() { + return uniCloud.httpclient.request(WeixinServer.AccessToken_H5_Url, { + dataType: 'json', + method: 'GET', + data: { + appid: this._appid, + secret: this._secret, + grant_type: "client_credential" + } + }) + } + + getH5Ticket(access_token) { + return uniCloud.httpclient.request(WeixinServer.Ticket_Url, { + dataType: 'json', + dataAsQueryString: true, + method: 'POST', + data: { + access_token + } + }) + } + + getH5AccessTokenForEip() { + return uniCloud.httpProxyForEip.postForm(WeixinServer.AccessToken_H5_Url, { + appid: this._appid, + secret: this._secret, + grant_type: "client_credential" + }, { + dataType: 'json' + }) + } + + getH5TicketForEip(access_token) { + return uniCloud.httpProxyForEip.postForm(WeixinServer.Ticket_Url, { + access_token + }, { + dataType: 'json', + dataAsQueryString: true + }) + } +} + +WeixinServer.AccessToken_Url = 'https://api.weixin.qq.com/cgi-bin/stable_token' +WeixinServer.Code2Session_Url = 'https://api.weixin.qq.com/sns/jscode2session' +WeixinServer.User_Encrypt_Key_Url = 'https://api.weixin.qq.com/wxa/business/getuserencryptkey' +WeixinServer.AccessToken_H5_Url = 'https://api.weixin.qq.com/cgi-bin/token' +WeixinServer.Ticket_Url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi' + +WeixinServer.GetMPAccessToken = function(options) { + return new WeixinServer(options).getAccessToken() +} + +WeixinServer.GetCodeToSession = function(options) { + return new WeixinServer(options).codeToSession(options.code) +} + +WeixinServer.GetUserEncryptKey = function(options) { + return new WeixinServer(options).getUserEncryptKey(options) +} + +WeixinServer.GetH5AccessToken = function(options) { + return new WeixinServer(options).getH5AccessToken() +} + +WeixinServer.GetH5Ticket = function(options) { + return new WeixinServer(options).getH5Ticket(options.access_token) +} + +//////////////////////////////////////////////////////////////// + +function isAliyun() { + return (uniCloud.getCloudInfos()[0].provider === 'aliyun') +} + +WeixinServer.GetResponseData = function(response) { + console.log("WeixinServer::response", response) + + if (!(response.status === HTTP_STATUS.SUCCESS || response.statusCodeValue === HTTP_STATUS.SUCCESS)) { + throw new BridgeError(response.status || response.statusCodeValue, response.status || response.statusCodeValue) + } + + const responseData = response.data || response.body + + if (responseData.errcode !== undefined && responseData.errcode !== 0) { + throw new BridgeError(responseData.errcode, responseData.errmsg) + } + + return responseData +} + +WeixinServer.GetMPAccessTokenData = async function(options) { + const response = await new WeixinServer(options).getAccessToken() + return WeixinServer.GetResponseData(response) +} + +WeixinServer.GetCodeToSessionData = async function(options) { + const response = await new WeixinServer(options).codeToSession(options.code) + return WeixinServer.GetResponseData(response) +} + +WeixinServer.GetUserEncryptKeyData = async function(options) { + const response = await new WeixinServer(options).getUserEncryptKey(options) + return WeixinServer.GetResponseData(response) +} + +WeixinServer.GetH5AccessTokenData = async function(options) { + const ws = new WeixinServer(options) + let response + if (isAliyun()) { + response = await ws.getH5AccessTokenForEip() + if (typeof response === 'string') { + response = JSON.parse(response) + } + } else { + response = await ws.getH5AccessToken() + } + return WeixinServer.GetResponseData(response) +} + +WeixinServer.GetH5TicketData = async function(options) { + const ws = new WeixinServer(options) + let response + if (isAliyun()) { + response = await ws.getH5TicketForEip(options.access_token) + if (typeof response === 'string') { + response = JSON.parse(response) + } + } else { + response = await ws.getH5Ticket(options.access_token) + } + return WeixinServer.GetResponseData(response) +} + + +module.exports = { + WeixinServer +} diff --git a/utils/uniMP.js b/utils/uniMP.js index 7ac5c78..df8b11b 100644 --- a/utils/uniMP.js +++ b/utils/uniMP.js @@ -1,3 +1,6 @@ +import { + Toast +} from "../libs/uniApi"; import { getGXconfig, miniapp @@ -32,11 +35,8 @@ function compareVersions(version1, version2) { const loadMP = async (id) => { appid = id; let info = await getGXconfig(); - console.log('最新版本', info.data); - // return ; uni.$emit('showLoading', true, '初始化中'); mp.getUniMPVersion(id, (ret) => { - console.log('当前版本', ret); let flag; if (ENV == 'prod') { flag = false @@ -47,18 +47,19 @@ const loadMP = async (id) => { true) { let count = 0; timer = setInterval(() => { - if (count < 100 && count > 0) uni.$emit('showLoading', true, `初始化中... ${count}%`) + if (count < 100 && count > 0) uni.$emit('showLoading', true, + `初始化中... ${count}%`) else uni.$emit('showLoading', true, `初始化中... 99%`) }, 200) let downloadTask = uni.downloadFile({ url: info.data.version_info?.dow_url, + // url: "https://lihai001.oss-cn-chengdu.aliyuncs.com/attach/36e40202405031202367449.wgt", success(res) { wgtFile = res.tempFilePath; - console.log('初始化完成', wgtFile); - setTimeout(()=>{ - installMP(); - clearInterval(timer); - timer = null; + setTimeout(() => { + installMP(); + clearInterval(timer); + timer = null; }, 700) }, fail(res) { @@ -83,7 +84,7 @@ const loadMP = async (id) => { //加载商城小程序 const loadMPx = async (id) => { - + appid = id; let info = await miniapp(); console.log('最新版本', info.data); @@ -103,19 +104,20 @@ const loadMPx = async (id) => { true) { let count = 0; timer = setInterval(() => { - if (count < 100 && count > 0) uni.$emit('showLoading', true, `初始化中... ${count}%`) + if (count < 100 && count > 0) uni.$emit('showLoading', true, + `初始化中... ${count}%`) else uni.$emit('showLoading', true, `初始化中... 99%`) }, 200) let downloadTask = uni.downloadFile({ - url: info.data.appInfo.dow_url, + url: './__UNI__7626C0F.wgt', success(res) { wgtFile = res.tempFilePath; console.log('初始化完成', wgtFile); - setTimeout(()=>{ - installMP(); - clearInterval(timer); - timer = null; + setTimeout(() => { + installMP(); + clearInterval(timer); + timer = null; }, 700) }, fail(res) { @@ -125,7 +127,6 @@ const loadMPx = async (id) => { } }); downloadTask.onProgressUpdate((res) => { - // console.log('初始化进度' + res.progress); if (res.progress > count) count += 10; if (count >= 90) { clearInterval(timer); @@ -141,67 +142,71 @@ const loadMPx = async (id) => { // 按信息接口加载小程序 const loadMPurl = async (e) => { appid = e.id; - let FURL = e.url; + let FURL = e.url; uni.$emit('showLoading', true, `初始化中...`) - uni.request({ - url: FURL, - method: 'GET', - success: (fileInfo) => { - mp.getUniMPVersion(appid, (ret) => { - console.log('当前版本', ret); - let flag; - if (ENV == 'prod') { - flag = false - } else { - flag = true - } - if (0 != ret.code || compareVersions(fileInfo.data?.data?.version, ret.versionInfo.name) == 1 || flag == - true) { - let count = 0; - timer = setInterval(() => { - if (count < 100 && count > 0) uni.$emit('showLoading', true, `初始化中... ${count}%`) - else uni.$emit('showLoading', true, `初始化中... 99%`) - }, 200) - let downloadTask = uni.downloadFile({ - url: fileInfo.data?.data?.down_url, - success(res) { - wgtFile = res.tempFilePath; - console.log('初始化完成', wgtFile); - setTimeout(()=>{ - installMP(); - clearInterval(timer); - timer = null; - }, 700) - }, - fail(res) { - clearInterval(timer); - timer = null; - uni.hideLoading(); - } - }); - downloadTask.onProgressUpdate((res) => { - // console.log('初始化进度' + res.progress); - if (res.progress > count) count += 10; - if (count >= 90) { - clearInterval(timer); - timer = null; - } - }); - } else { - open() - } - }); - - }, - fail:(err)=> { - console.log('错误:', err); - } - }) - + uni.request({ + url: FURL, + method: 'GET', + success: (fileInfo) => { + mp.getUniMPVersion(appid, (ret) => { + console.log('当前版本', ret); + let flag; + if (ENV == 'prod') { + flag = false + } else { + flag = true + } + if (0 != ret.code || compareVersions(fileInfo.data?.data?.version, ret + .versionInfo.name) == 1 || flag == + true) { + let count = 0; + timer = setInterval(() => { + if (count < 100 && count > 0) uni.$emit('showLoading', true, + `初始化中... ${count}%`) + else uni.$emit('showLoading', true, `初始化中... 99%`) + }, 200) + let downloadTask = uni.downloadFile({ + url: fileInfo.data?.data?.down_url, + success(res) { + wgtFile = res.tempFilePath; + console.log('初始化完成', wgtFile); + setTimeout(() => { + installMP(); + clearInterval(timer); + timer = null; + }, 700) + }, + fail(res) { + clearInterval(timer); + timer = null; + uni.hideLoading(); + } + }); + downloadTask.onProgressUpdate((res) => { + // console.log('初始化进度' + res.progress); + if (res.progress > count) count += 10; + if (count >= 90) { + clearInterval(timer); + timer = null; + } + }); + } else { + open() + } + }); + + }, + fail: (err) => { + console.log('错误:', err); + } + }) + }; // 商城配置的小程序 const loadAppletMP = async (data) => { + // console.log(data) + // return appid = data.app_id; // return ; uni.$emit('showLoading', true, '初始化中'); @@ -212,22 +217,32 @@ const loadAppletMP = async (data) => { } else { flag = true } + if (data.showToast) { + uni.showLoading({ + title: '正在加载中...' + }); + } + if (0 != ret.code || compareVersions(data.version, ret.versionInfo.name) == 1 || flag == true) { let count = 0; timer = setInterval(() => { - if (count < 100 && count > 0) uni.$emit('showLoading', true, `初始化中... ${count}%`) + if (count < 100 && count > 0) uni.$emit('showLoading', true, + `初始化中... ${count}%`) else uni.$emit('showLoading', true, `初始化中... 99%`) }, 200) + + let downloadTask = uni.downloadFile({ url: data.url, + // url: "https://lihai001.oss-cn-chengdu.aliyuncs.com/attach/3ffde202405031254278460.wgt", success(res) { wgtFile = res.tempFilePath; console.log('初始化完成', wgtFile); - setTimeout(()=>{ - installMP(); - clearInterval(timer); - timer = null; + setTimeout(() => { + installMP(data); + clearInterval(timer); + timer = null; }, 700) }, fail(res) { @@ -237,7 +252,6 @@ const loadAppletMP = async (data) => { } }); downloadTask.onProgressUpdate((res) => { - // console.log('初始化进度' + res.progress); if (res.progress > count) count += 10; if (count >= 90) { clearInterval(timer); @@ -253,39 +267,38 @@ const loadAppletMP = async (data) => { // 按远程文件地址加载小程序 const loadMPdns = async (e) => { appid = e.id; - let FURL = e.url; + let FURL = e.url; uni.$emit('showLoading', true, `初始化中...`) - let count = 0; - timer = setInterval(() => { - if (count < 100 && count > 0) uni.$emit('showLoading', true, `初始化中... ${count}%`) - else uni.$emit('showLoading', true, `初始化中... 99%`) - }, 200) - let downloadTask = uni.downloadFile({ - url: FURL, - success(res) { - wgtFile = res.tempFilePath; - console.log('初始化完成', wgtFile); - setTimeout(()=>{ - installMP(); - clearInterval(timer); - timer = null; - }, 700) - }, - fail(res) { - clearInterval(timer); - timer = null; - uni.hideLoading(); - } - }); - downloadTask.onProgressUpdate((res) => { - // console.log('初始化进度' + res.progress); - if (res.progress > count) count += 10; - if (count >= 90) { - clearInterval(timer); - timer = null; - } - }); - + let count = 0; + timer = setInterval(() => { + if (count < 100 && count > 0) uni.$emit('showLoading', true, `初始化中... ${count}%`) + else uni.$emit('showLoading', true, `初始化中... 99%`) + }, 200) + let downloadTask = uni.downloadFile({ + url: FURL, + success(res) { + wgtFile = res.tempFilePath; + console.log('初始化完成', wgtFile); + setTimeout(() => { + installMP(); + clearInterval(timer); + timer = null; + }, 700) + }, + fail(res) { + clearInterval(timer); + timer = null; + uni.hideLoading(); + } + }); + downloadTask.onProgressUpdate((res) => { + if (res.progress > count) count += 10; + if (count >= 90) { + clearInterval(timer); + timer = null; + } + }); + }; // 小程序版本信息 @@ -298,19 +311,19 @@ const getVersion = (id) => { }) } // 初始化小程序 -const installMP = () => { +const installMP = (data) => { mp.getUniMPVersion(appid, (ret) => { - doInstallMP(); + doInstallMP(data); console.log('getUniMPVersion: ' + JSON.stringify(ret)); }); }; -const doInstallMP = () => { +const doInstallMP = (data) => { mp.installUniMP({ appid: appid, wgtFile: wgtFile }, (r) => { if (0 == r.code) { - open(); + open(data); } else { uni.hideLoading(); clearInterval(timer); @@ -326,7 +339,8 @@ const doInstallMP = () => { }; const open = (id = null) => { - uni.$emit('showLoading', false); + uni.hideLoading() + uni.$emit('showLoading', false); let token = uni.getStorageSync('LOGIN_STATUS_TOKEN'); if (!token) return uni.showToast({ icon: 'none', @@ -334,13 +348,12 @@ const open = (id = null) => { }) let avatar = store?.state?.userInfo?.avatar; mp.openUniMP({ - appid: id || appid, + appid: typeof(id) == 'object' ? appid : (id || appid), extraData: { uniMP: true, token: token, avatar: avatar, }, - // path: '/pages/index/index?unimp=true' }, (ret) => { uni.hideLoading(); if (0 != ret.code) { @@ -350,7 +363,16 @@ const open = (id = null) => { showCancel: false }); } - console.log('openUniMP: ' + JSON.stringify(ret)); + + if (id.type == 2) { + setTimeout(() => { + console.log("发送给小程序的", id) + mp.sendUniMPEvent(appid, 'tocustomlist', id, (ret) => { + console.log("开始发送消息") + }); + }, 1000) + } + }); } @@ -358,9 +380,9 @@ export default { loadMP, loadMPurl, loadMPx, - loadMPdns, + loadMPdns, installMP, - loadAppletMP, + loadAppletMP, doInstallMP, getVersion, open diff --git a/utils/uniMPevent.js b/utils/uniMPevent.js index 5f38d08..50efc13 100644 --- a/utils/uniMPevent.js +++ b/utils/uniMPevent.js @@ -4,10 +4,9 @@ import { test } from "@/utils/uniMPfunction.js" -export const initEvent = () => { +export const initEvent = (data) => { mp.onUniMPEventReceive(async (ret) => { - console.log('小程序事件: ', ret); - + console.log('小程序事件: ', data); // 用户如果没有注册商户 从小程序返回 入驻页面 if (ret.event == 'closeAppToOpenShop') { mp.closeUniMP(ret.fromAppid, (ret) => { @@ -34,20 +33,6 @@ export const initEvent = () => { console.log('获取定位'); let res = await uniMPgetLocation(); console.log(res); - // plus.geolocation.getCurrentPosition(function(position) { - // console.log('经度:' + position.coords.longitude); - // console.log('纬度:' + position.coords.latitude); - // // that.markers[1].latitude = position.coords.longitude; - // // that.markers[1].longitude = position.coords.longitude; - // mp.sendUniMPEvent( - // ret.fromAppid, - // 'getLocation', {...position.coords}, - // (ret) => { - // console.log('Host sendEvent: ' + JSON.stringify(ret)); - // }); - // }, function(error) { - // console.error('获取位置失败:', error.message); - // }, {provider:'gps'}); mp.sendUniMPEvent( ret.fromAppid, 'getLocation', { @@ -72,6 +57,10 @@ export const initEvent = () => { console.log('Host sendEvent: ' + JSON.stringify(ret)); }); } + + + + if (ret.event == 'log') { // console.log('2222222')