WxHelper.ts 13.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460

// import UserManager from "../manager/UserManager";

import DataService from "../wxsdk/service/DataService";
import AlipayApi from "../wxsdk/alipay/AlipayApi";
import { SDKTools } from "./SDKTools";

/** WXapi */
export class WxHelper {

    /** 手机设备信息 */
    public static SystemInfo: SystemInfoSyncReturnValue;

    /** 微信用户信息 */
    public static userInfo: WxUserInfo;
    public static get isOperable() {
        return (cc.sys.platform === cc.sys.WECHAT_GAME || cc.sys.platform === cc.sys.ALIPAY_GAME)
    }

    /** 获取设备信息 */
    public static getSystemInfo() {
        if (typeof my !== 'undefined') this.SystemInfo = my.getSystemInfoSync();
    }

    /** 像开放数据域发送信息 */
    public static postMessage(eventType: string, data?: any): void {
        if (typeof my === 'undefined' || !this.checkVerison('1.9.92')) return;
        my.getOpenDataContext().postMessage({
            eventType: eventType,
            data: data
        });

    }

    /** 更新微信开放数据榜单数据 */
    public static updateWxRank(score: number) {

        if (typeof wx === 'undefined' || !this.checkVerison('1.9.92')) return;
        let data = {
            score: score
        }
        wx.setUserCloudStorage({
            KVDataList: [{
                key: 'score',
                value: JSON.stringify(data)
            }]
        })

    }

    /** 创建用户反馈按钮 */
    public static createFeedbackButton(target: cc.Node) {

        let data = this.computWxPosition(target);
        return my.createFeedbackButton({
            type: 'text',
            text: ' ',
            style: {
                left: data.left,
                top: data.top,
                width: data.width,
                height: data.height,
                borderRadius: 5,
                // backgroundColor: '#69c66d',
            }
        })

    }


    /** 获取用户信息按钮 */
    public static userInfoButton: any;
    /** 创建一个获取用户信息按钮 */
    public static createUserInfoButton(target: cc.Node) {
        let data = this.computWxPosition(target);
        // console.log("data", data)
        return my.createUserInfoButton({
            type: 'text',
            text: ' ',
            style: {
                left: data.left,
                top: data.top,
                width: data.width,
                height: data.height,
                borderRadius: 5,
                // color: '#ffffff',
                // backgroundColor: '#69c66d',
                // textAlign: 'center',
                // fontSize: 20,
                // lineHeight: 45,
            },
            withCredentials: true
        })

    }

    /** 计算微信坐标 */
    public static computWxPosition(target: cc.Node): { left: number, top: number, width: number, height: number } {

        let data = { left: 0, top: 0, width: 0, height: 0 }
        let rect = target.getBoundingBoxToWorld();
        let ratio = cc.view.getDevicePixelRatio();
        let scale = cc.view.getScaleX();
        let factor = scale / ratio;
        // let point = v2(rect.x, rect.y);
        // point.mulSelf(scale);
        data.left = rect.x * factor;
        data.top = this.SystemInfo.screenHeight - (rect.y + rect.height) * factor;
        data.width = rect.width * factor;
        data.height = rect.height * factor;

        // let btnSize = size(target.width + 10, target.height + 10);
        // let frameSize = view.getFrameSize();
        // let winSize = director.getWinSize();
        // // log("winSize: ",winSize);
        // // log("frameSize: ",frameSize);
        // //适配不同机型来创建微信按钮
        // data.left = (winSize.width * 0.5 + target.x - btnSize.width * 0.5) / winSize.width * frameSize.width;
        // data.top = (winSize.height * 0.5 - target.y - btnSize.height * 0.5) / winSize.height * frameSize.height;
        // data.width = btnSize.width / winSize.width * frameSize.width;
        // data.height = btnSize.height / winSize.height * frameSize.height;
        // log("button pos: ",v2(left,top));
        // log("button size: ",size(width,height));

        return data;

    }


    /** 兼容方式 - 版本比较 */
    public static compareVersion(versionA: any, versionB: any) {
        versionA = versionA.split('.');
        versionB = versionB.split('.');
        let len = Math.max(versionA.length, versionB.length);

        while (versionA.length < len) {
            versionA.push('0');
        }
        while (versionB.length < len) {
            versionB.push('0');
        }

        for (let i = 0; i < len; i++) {
            let num1 = parseInt(versionA[i]);
            let num2 = parseInt(versionB[i]);

            if (num1 > num2) {
                return 1;
            } else if (num1 < num2) {
                return -1;
            }
        }

        return 0;
    }

    /** 当前版本是否能使用接口 */
    public static checkVerison(version: string): boolean {
        return this.compareVersion(this.SystemInfo.SDKVersion, version) >= 0;
    }

    /** 显示一个对话框 */
    public static showModal(data: ShowModalType) {
        return new Promise((resolve, reject) => {

            if (typeof my !== 'undefined') {
                my.showModal({
                    ...data,
                    success: (res: { confirm: boolean, cancel: boolean }) => {
                        if (res.confirm) {
                            resolve(true);
                        } else {
                            resolve(false);
                        }
                    },
                    fail: () => {
                        reject();
                    }

                });
            } else {
            }

        });

    }

    /**
     * 显示一个提示层
     * @param msg 显示信息
     * @param time 关闭时间
     */
    public static showToast(msg: string, time: number = 1500) {
        if (cc.sys.platform === cc.sys.WECHAT_GAME)
            wx.showToast({
                title: msg,
                icon: 'none',
                duration: time
            })
        else if (cc.sys.platform === cc.sys.ALIPAY_GAME) {
            my.showToast({
                type: 'none',
                content: msg,
                duration: time,
            });
        } else {
            console.log(msg)
        }

    }

    /** 设置系统剪贴板的内容 */
    public static copy(str: string) {
        if (!this.checkVerison('1.1.0')) return Promise.reject('');

        return new Promise((resolve, reject) => {
            my.setClipboardData({
                data: str,
                success: (res: any) => {
                    resolve(res);
                },
                fail: () => {
                    resolve('');
                }
            });
        });
    }

    /** 手机发生较长时间的振动(400 ms)  */
    public static vibrateLong() {
        // if (!this.checkVerison('1.2.0')) return Promise.reject(null);

        return new Promise((resolve, reject) => {
            my.vibrateLong({
                success: () => {
                    resolve(1);
                },
                fail: () => {
                    resolve(0);
                }
            });
        });
    }

    /** 手机发生较短时间的振动(15 ms) */
    public static vibrateShort() {
        // if (!this.checkVerison('1.2.0')) return Promise.reject(null);

        return new Promise<IResult<any>>((resolve, reject) => {
            my.vibrateShort({
                success: () => {
                    resolve({ code: 0 });
                },
                fail: () => {
                    resolve({ code: 1 });
                }
            });
        });
    }

    /**
     * 检测更新
     */
    public static checkUpdate(bol: boolean = true) {
        if (!this.checkVerison('1.9.90')) return;
        const updateManager = my.getUpdateManager();
        updateManager.onCheckForUpdate(function (res) {
            console.log('updateManager', res.hasUpdate);
        });

        updateManager.onUpdateReady(function () {
            my.showModal({
                title: '更新提示',
                content: '新版本已经准备好,请重启应用!',
                showCancel: bol,
                success: function (res) {
                    if (res.confirm) {
                        updateManager.applyUpdate()
                    }
                }
            });
        });
        updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
        });
    }

    /** 发送客服信息 */
    public static openCustomerServiceConversation() {

        return new Promise<IResult<any>>((resolve, reject) => {
            if (!this.checkVerison('2.0.3')) resolve({ code: 1 });
            my.openCustomerServiceConversation({
                showMessageCard: true,
                sendMessageTitle: '我要更多好玩!',
                sendMessageImg: 'http://dep.miso-lab.com/tetrischangeskin/bin/share/concat.png',
                success: () => {
                    resolve({ code: 0 });
                },
                fail: () => {
                    resolve({ code: 1 });
                }
            });
        });

    }

    /** 发送客服信息 */
    public static openConversation() {

        return new Promise<IResult<any>>((resolve, reject) => {
            if (!this.checkVerison('2.0.3')) resolve({ code: 1 });
            my.openCustomerServiceConversation({
                success: () => {
                    resolve({ code: 0 });
                },
                fail: () => {
                    resolve({ code: 1 });
                }
            });
        });

    }

    /** 回到前台 */
    public static onShow(callback: () => void) {
        if (typeof my === 'undefined') return;
        my.onShow(callback);
        // return new Promise<IResult<any>>((resolve, reject) => {
        //     my.onShow((res: any) => {
        //         resolve({ code: 1 });
        //     });
        // });

    }

    /** 切换到后台 */
    public static onHide(callback: () => void) {

        if (typeof my === 'undefined') return;
        my.onHide(callback);

    }

    public static updateShareMenu(value) {
        if (typeof my === 'undefined') return;
        my.updateShareMenu({
            withShareTicket: value
        });
    }

    /**
     * 检查授权
     */
    public static authorize(scope: string = 'scope.userInfo') {
        if (typeof my === 'undefined') return;
        my.getSetting({
            success(res) {
                if (!res.authSetting[scope]) {
                    my.authorize({
                        scope: scope,
                        success() {

                        }
                    })
                }
            }
        })
    }
    /**
     * 获取用户信息
    */
    public static getUserInfo(callback) {
        my.getUserInfo({
            success: function (res) {
                // console.log(res)
                callback(res)
            },
            fail: function (err) {
                callback(err)
            }
        })
    }
    /** 游戏圈 */
    public static createGameClubButton(target: cc.Node) {
        let data = this.computWxPosition(target);
        return my.createGameClubButton({
            icon: 'green',
            style: {
                left: data.left,
                top: data.top,
                width: data.width,
                height: data.height,
            }
        })

    }

    public static setUserWxCloudStorage(data: object) {
        if (cc.sys.platform != cc.sys.WECHAT_GAME || !DataService.I.Authorize) return null;
        wx.setUserCloudStorage({
            KVDataList: [{ key: 'data', value: JSON.stringify(data) }],
            success: res => {
                console.log("分数上传 成功", data);
            },
            fail: res => {
                console.log("分数上传 失败");
            }
        });

    }
    public static showRankEnter() {
        return WxHelper.isOperable && AlipayApi.I.canUseRank()
    }
    public static getRank(key: string) {
        if (cc.sys.platform === cc.sys.ALIPAY_GAME) {
            AlipayApi.I.getRankList(key).then(() => {
                console.log('success 关闭banner')
                // BannerManager.I.hideAll();
            }).catch((msg) => {
                console.log('fail', JSON.stringify(msg))
                // WxHelper.showToast(msg.errMsg || msg.errorMessage || '排行榜获取失败')
            });
        }

    }
    public static setRankScore(key: string, score: number, updateType?: number) {
        if (cc.sys.platform === cc.sys.ALIPAY_GAME)
            AlipayApi.I.setRankScoreData(key, score, updateType);
    }
    public static async loginWx(isAuthorize: boolean, failFunction?: Function, count?: number, success?: Function): Promise<any> {
        count = count != undefined ? count : 3;
        let data = await SDKTools.login(isAuthorize);
        // console.error(count, 'loginWx', data)
        if (data.code == 0) {
            success && success();
            return data;
        } else if (count >= 0) {
            count--;
            return await this.loginWx(isAuthorize, failFunction, count);
        } else if (failFunction) {
            console.warn('--wxlogin--fail', data)
            failFunction();
            return null;
        }
    }





    public static goToGameCenter(success: Function, fail: Function) {
        //每个游戏跳转游戏中心的url 不一样
        let url = "alipays://platformapi/startapp?appId=2021003125685383&url=https%3A%2F%2Frender.alipay.com%2Fp%2Fyuyan%2F180020010001206617%2Findex.html%3FcaprMode%3Dsync&chInfo=gamesetlattice&sms=YES&appClearTop=false";
        if (cc.sys.platform === cc.sys.ALIPAY_GAME) {
            AlipayApi.I.navigateToMiniProgramByScheme(url, success, fail)
        }
    }

}