weixinTools.js 22.2 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 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
/**
 * Created by shipfi on 2016/9/24.
 */

import 'isomorphic-fetch';
import _ from 'lodash';
import {URLManager} from './commonUtil';
import {API_ROOT, MOBILE_ROOT} from '../config';
import cookieManager from './cookieManager';
import CMErrCode from '../exception/CMErrCode';
import CMException from '../exception/CMException';
var envConfig = require('../../config/envConfig');

//require('es6-promise').polyfill();


export default  {
    weixinDatas: {
        WX_OPEN_APPID: 'wx8e88ab6154cbcd23'
    },

    weixinUrls: {
        WX_OPEN_WEIXIN_URL: 'https://open.weixin.qq.com/connect/oauth2/authorize', /* in proxies */
        WX_API_WEIXIN_URL: '/apiWeixin', /* in proxies */
        COMMUNITY_API_URL: '/communityAPI', /* in proxies */
        WX_PATH_OAUTH2_AUTHORIZER: '/connect/oauth2/authorize',
        WX_PATH_API_OAUTH2_ACCESSTOKEN: '/sns/oauth2/component/access_token',
        COMMUNITY_PATH_GET_DEFAULT_APPID: '/auth/defaultWxApp/',
        COMMUNITY_PATH_GET_USERINFO: '/auth/wxUserInfo',
        //ACCESS_TOKEN_PATH_GET               : '/auth/wxAccessToken',
        COMMUNITY_PATH_JSSDK_SIGN: '/auth/wxJSSDKSign',
        COMMUNITY_PATH_CHECK_OPENID: '/auth/wxCheckOpenId',
        COMMUNITY_PATH_WEIXIN_AUTH_CODE: '/auth/wxAuthCode'
    },

    /**
     * URLManager对象
     * @param host
     * @returns {URLManager}
     */
    urlManager: function (host = '') {
        return new URLManager(host);
    },

    /**
     * 判断是否微信浏览器
     * @returns {boolean}
     */
    isWeixin: function () {
        var ua = window.navigator.userAgent.toLowerCase();
        var matchs = ua.match(/MicroMessenger/i);
        if (matchs && matchs.length > 0 && matchs[0] == 'micromessenger') {
            return true;
        } else {
            return false;
        }
    },


    getWxOpenId: function (grpAppId, forceReflesh = false) {
        // https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419318590&token=&lang=zh_CN
        var _this = this;
        var promise = new Promise(function (resolve, reject) {
            _this.getDefaultWxAppId(grpAppId).then(function (response) {
                let wxAppId = response.appid;
                var wxOpenId = _this.urlManager().getQueryParam('openid');
                console.log('================>' + wxOpenId);

                // 参数中得不到wxOpenId,或者必须强制刷新
                if (!wxOpenId || forceReflesh) {

                    // Step1 : 请求Code,重定向到api.community.qingger.com,获得openId
                    var redirectUrl = URLManager.generateURL(MOBILE_ROOT, null, {
                        grpAppId: grpAppId
                    });
                    redirectUrl = redirectUrl + "#" + URLManager.getUriObj().anchor();  // 加上router项
                    redirectUrl = encodeURI(redirectUrl);

                    var apiRedirectHref = URLManager.generateURL(API_ROOT,
                        _this.weixinUrls.COMMUNITY_PATH_WEIXIN_AUTH_CODE,
                        {
                            redirectUrl: redirectUrl
                        }
                    );

                    console.log(apiRedirectHref);
                    //apiRedirectHref = 'http://api.community.test.qingger.com/auth/wxAuthCode?redirectUrl=http%3A%2F%2Fcommunity.test.qingger.com%2F%3FgrpAppId%3DAUTO';
                    // 跳转到微信,得出Code信息,再由微信重定向到API处理后,回到本地
                    var wxAuthUrl = _this.getWxOauthForCodeURL(wxAppId, decodeURI(apiRedirectHref));
                    window.location.href = wxAuthUrl;
                } else {

                    var ret = {
                        'wxOpenId': _this.urlManager().getQueryParam('openid'),
                        //'code'       : _this.urlManager().getQueryParam('code'),
                        'wxAppId': _this.urlManager().getQueryParam('appid')
                    };

                    // 无刷新改变URL,去掉openId参数 (微信浏览器不支持)
                    //history.replaceState(null,document.title,URLManager.getCurrentUrlWithoutOpenId());
                    //console.log(ret);
                    resolve(ret);
                }
            }, function (error) {
                reject(error);
            });
        });

        return promise;

    },

    getOpenIdExist: function (grpAppId, wxAppId, wxOpenId) {
        var _this = this;
        let queryParam = {
            appid: wxAppId,
            openid: wxOpenId,
            grpAppId: grpAppId
        };
        let checkOpenIdExistAPI = URLManager.generateURL(null,
            this.weixinUrls.COMMUNITY_API_URL + this.weixinUrls.COMMUNITY_PATH_CHECK_OPENID,
            queryParam
        );
        var promise = new Promise(function (resolve, reject) {
            fetch(checkOpenIdExistAPI, {
                method: 'GET',
                headers: {"Content-Type": "application/x-www-form-urlencoded"}
            })
                .then(function (response) {
                    if (response.status !== 200) {
                        console.log('Looks like there was a problem. Status Code: ' +
                            response.status);
                        reject(response);
                    }
                    response.json().then(function (data) {
                        resolve(data.data.exist);
                    });
                }, function (error) {
                    reject(error);
                })
        });

        return promise;
    },

    /**
     * 获得默认的weixin APPID
     *   1) 参数中带有appid参数,使用appid参数作为社区使用的appid
     *   2) 如果没有带有appid参数,调用接口/auth/defaultWxApp/{grpAppId} 获得默认的appid
     * @param grpAppId
     * @returns {Promise}
     *      {
     *         appid : [weixinAppid] 
     *      }
     */
    getDefaultWxAppId: function (grpAppId) {
        var _this = this;
        var promise = new Promise(function (resolve, reject) {
            let getDefaultWxAppIdAPI = _this.weixinUrls.COMMUNITY_API_URL + _this.weixinUrls.COMMUNITY_PATH_GET_DEFAULT_APPID + grpAppId;
            let ret = {
                appid: null
            };
            ret.appid = _this.urlManager().getQueryParam('appid');
            if (ret.appid) {
                resolve(ret);
            } else {
                console.log(getDefaultWxAppIdAPI);
                fetch(getDefaultWxAppIdAPI, {
                    method: 'GET',
                    headers: {"Content-Type": "application/x-www-form-urlencoded"}
                })
                    .then(function (response) {
                        if (response.status !== 200) {
                            console.log('Looks like there was a problem. Status Code: ' +
                                response.status);
                            reject(response);
                        }
                        response.json().then(function (data) {
                            ret.appid = data.data.defaultWxAppId;
                            resolve(ret);
                        });
                    }, function (error) {
                        reject(error);
                    })
            }
        });

        return promise;
    },


    /**
     * 通过API获得第三方CompAcessToken/CompAppId
     * @returns {Promise}
     *     data.compAppId       = 第三方平台AppId
     *     data.compAccessToken = 第三方平台所使用的AccessToken
     */
    // getWeixinCompAccessToken : function() {
    //     var _this = this;
    //     let ret = {
    //         accessToken : null,
    //     };
    //     let promise = new Promise(function(resolve,reject){
    //         let accessTokenURL = _this.weixinUrls.COMMUNITY_API_URL + _this.weixinUrls.ACCESS_TOKEN_PATH_GET;
    //         fetch(accessTokenURL,{
    //             method:'GET',
    //             headers:{"Content-Type": "application/x-www-form-urlencoded"}
    //         }).then(function(response){
    //             if (response.status !== 200) {
    //                 console.log('Looks like there was a problem. Status Code: ' +
    //                     response.status);
    //                 reject(response);
    //             }
    //             response.json().then(function(data){
    //                 ret = {
    //                     'compAppId'         : data.compAppId,
    //                     'compAccessToken'   : data.compAccessToken
    //                 } 
    //                 resolve(ret);
    //             });
    //         },function(error){
    //             reject(error);
    //         })
    //     });
    //    
    //     return promise;
    // },

    /**
     * 定位到微信提供的URL,通过微信获取code接口
     * @param wxAppId
     * @param redirectUrl
     * @returns {*}
     */
    getWxOauthForCodeURL: function (wxAppId, redirectUrl) {
        let queryParam = {
            appid: wxAppId,
            redirect_uri: redirectUrl,
            response_type: 'code',
            scope: 'snsapi_userinfo',
            state: 'STATE',
            component_appid: this.weixinDatas.WX_OPEN_APPID,
        };

        let uriobj = new URLManager(this.weixinUrls.WX_OPEN_WEIXIN_URL)
            .uriObj
            .setPath(this.weixinUrls.WX_PATH_OAUTH2_AUTHORIZER);

        _.forEach(queryParam, function (value, key) {
            uriobj.addQueryParam(key, value);
        });

        return uriobj.toString() + "#wechat_redirect";
    },

    /**
     * 获得Weixin openID接口URL
     * @param wxAppId
     * @param code
     * @param accessToken
     * @returns {*}
     */
    getWXOAuthUrlForOpenId: function (wxAppId, code, accessToken) {
        let queryParam = {
            appid: wxAppId,
            code: code,
            grant_type: 'authorization_code',
            component_appid: this.weixinDatas.WX_OPEN_APPID,
            component_access_token: accessToken,
        };
        let uriobj = new URLManager(this.weixinUrls.WX_API_WEIXIN_URL)
            .uriObj
            .setPath(this.weixinUrls.WX_PATH_API_OAUTH2_ACCESSTOKEN);

        _.forEach(queryParam, function (value, key) {
            uriobj.addQueryParam(key, value);
        });

        return uriobj.toString();
    },


    /**
     * 获取用户信息
     * @param wxAppId
     * @param wxOpenId
     * @param grpAppId
     * @returns {Promise}
     */
    getWxUserInfoByOpenId: function (wxAppId, wxOpenId, grpAppId) {
        let queryParam = {
            appid: wxAppId,
            openid: wxOpenId,
            grpAppId: grpAppId
        };
        let queryWxUserInfoUrl = URLManager.generateURL(null,
            this.weixinUrls.COMMUNITY_API_URL + this.weixinUrls.COMMUNITY_PATH_GET_USERINFO,
            queryParam
        );

        var promise = new Promise(function (resolve, reject) {
            fetch(queryWxUserInfoUrl, {
                method: 'GET',
                headers: {"Content-Type": "application/x-www-form-urlencoded"}
            })
                .then(function (response) {
                    if (response.status !== 200) {
                        console.log('Looks like there was a problem. Status Code: ' +
                            response.status);
                        reject(response);
                    }
                    response.json().then(function (resData) {
                        resolve(resData.data);
                    });
                }, function (error) {
                    reject(error);
                })
        });

        return promise;
    },

    /**
     * 获得用户信息
     * @returns {Promise}
     *  respones = array( userId, cstId, cstType, userHeadImg, userNickName, userSex, wxAppId, wxOpenId, grpAppId )
     */
    getUserInfo: function () {
        let urlManager = new URLManager();
        let cookieGrpAppid = cookieManager.getCookie('grpAppId');
        let cookieWxAppid = cookieManager.getCookie('wxAppId');
        let nowGrpAppId = urlManager.getQueryParam('grpAppId') ? urlManager.getQueryParam('grpAppId') : 'AUTO';
        let nowWxAppid = urlManager.getQueryParam('appid') ? urlManager.getQueryParam('appid') : '';
        //let wxOpenId = null;
        let cookieWxOpenId = cookieManager.getCookie('wxOpenId');
        let nowWxOpenId = urlManager.getQueryParam('openid') ? urlManager.getQueryParam('openid') : '';
        var _this = this;


        var promise = new Promise(function (resolve, reject) {
            if (_this.isWeixin()) {

                let $needReflesh = false;
                if (cookieGrpAppid != nowGrpAppId || cookieWxAppid != nowWxAppid || cookieWxOpenId == undefined)
                    $needReflesh = true;


                cookieManager.saveCookie('grpAppId', nowGrpAppId);
                if ($needReflesh) {
                    // 取得openId
                    _this.getWxOpenId(nowGrpAppId).then(function (wxInfo) {
                        console.log(wxInfo);
                        if (wxInfo.hasOwnProperty('wxOpenId')) {
                            cookieManager.saveCookie('wxOpenId', wxInfo.wxOpenId);
                            cookieManager.saveCookie('wxAppId', wxInfo.wxAppId);

                            resolve({
                                'wxAppId': wxInfo.wxAppId,
                                'wxOpenId': wxInfo.wxOpenId,
                                'grpAppId': nowGrpAppId
                            });
                        } else {
                            reject('ERROR: API CANT RETURN OPENID ATTR');
                        }
                    }, function (error) {
                        //throw new CMException(CMErrCode.ERR_WEIXIN_OPENID_NOT_GET,'Get OpenId Error.')
                        reject('ERROR: API GET OPENID ERROR');
                    });
                } else {
                    // has openId cache, so just use openid to get wxUserInfo 
                    let wxAppId = cookieManager.getCookie('wxAppId');
                    let wxOpenId = cookieManager.getCookie('wxOpenId');

                    _this.getOpenIdExist(nowGrpAppId, wxAppId, wxOpenId).then(function (isExist) {
                        if (isExist) {
                            resolve({
                                'wxAppId': wxAppId,
                                'wxOpenId': wxOpenId,
                                'grpAppId': nowGrpAppId
                            });
                        } else {
                            // 因为缓存的原因,客户中存在openId/appId, 但是服务器API上却因为原因删除了,那么OpenID需要重新取得
                            cookieManager.removeCookie('wxOpenId');
                            cookieManager.removeCookie('wxAppId');
                            _this.getWxOpenId(nowGrpAppId, true).then(function (wxInfo) {
                                console.log(wxInfo);
                                if (wxInfo.hasOwnProperty('wxOpenId')) {
                                    cookieManager.saveCookie('wxOpenId', wxInfo.wxOpenId);
                                    cookieManager.saveCookie('wxAppId', wxInfo.wxAppId);

                                    resolve({
                                        'wxAppId': wxInfo.wxAppId,
                                        'wxOpenId': wxInfo.wxOpenId,
                                        'grpAppId': nowGrpAppId
                                    });
                                } else {
                                    reject('ERROR: API CANT RETURN OPENID ATTR');
                                }
                            }, function (error) {
                                reject('ERROR: API GET OPENID ERROR');
                            });
                        }
                    }, function (error) {
                        reject('ERROR:API GET OPENID ERROR');
                    });


                }
            } else {
                if ((typeof envConfig.NODE_ENV) != 'undefined' && envConfig.NODE_ENV == 'testing') {
                    console.log("Not weixin browser,TEST FOR SHIPFI...");
                    cookieManager.saveCookie('grpAppId', nowGrpAppId);
                    cookieManager.saveCookie('wxOpenId', 'o2gsCwYq9ILxbE35ESH70uQEbVv4');
                    cookieManager.saveCookie('wxAppId', 'wx31f3126b561c79ed');
                    resolve({
                        userId: 28,
                        cstId: 200013578973,
                        cstType: 0,
                        userHeadImg: 'http://wx.qlogo.cn/mmopen/bBB6IHIYxgueY8BDPXHHpzagDazM7iaTGtBegd6N1TkcWKNiaqFVCZ0GAx6U51B0ObibKOnh8PuoKToMdozrMGHkk4CdZaNz6Zu/0',
                        userNickName: 'shipfi',
                        userSex: 1,
                        wxAppId: 'wx31f3126b561c79ed',
                        wxOpenId: 'o2gsCwYq9ILxbE35ESH70uQEbVv4',
                        grpAppId: 'AUTO'
                    });
                } else {
                    reject('ERROR');
                }

                // not use weixin browser, use const value for test....
            }
        });

        return promise;
    },


    // saveUserInfo : function(wxOpenId,wxUserInfo) {
    //     window.localStorage[wxOpenId] = wxUserInfo;
    //     cookieManager.saveCookie('userId',  wxUserInfo.userId);
    // },

    // getUserinfo : function(wxOpenId) {
    //     return window.localStorage[wxOpenId];
    // },

    // clearUserInfo : function(wxOpenId) {
    //     window.localStorage[wxOpenId] =  null;
    // }

    /**
     * 获得JSSDK所必须的数据项
     * @param wxAppId
     * @param grpAppId
     * @returns {Promise}
     *   array (wxAppId, nonceStr, timeStamp, url, signature, rawString)
     */
    loadJSSDKSignPackage: function (wxAppId, grpAppId) {
        let queryParam = {
            appid: wxAppId,
            grpAppId: grpAppId,
            url: decodeURI(location.href)
        };
        let queryWxSignatureUrl = URLManager.generateURL(null,
            this.weixinUrls.COMMUNITY_API_URL + this.weixinUrls.COMMUNITY_PATH_JSSDK_SIGN,
            queryParam
        );

        var promise = new Promise(function (resolve, reject) {
            fetch(queryWxSignatureUrl, {
                method: 'GET',
                headers: {"Content-Type": "application/x-www-form-urlencoded"}
            })
                .then(function (response) {
                    if (response.status !== 200) {
                        console.log('Looks like there was a problem. Status Code: ' +
                            response.status);
                        reject(response);
                    }
                    response.json().then(function (resData) {
                        resolve(resData.data);
                    });
                }, function (error) {
                    reject(error);
                })
        });

        return promise;
    },


    /**
     * 配置WXJSSDK
     * @param wxAppId
     * @param grpAppId
     * @param options
     */
    confixWxJSSDK: function (wxAppId, grpAppId, options) {

        if (typeof options == 'object' && typeof options.readyFunction == 'function') {
            this.readyFunction = options.readyFunction;
            if ('readyFunctionParams' in options) {
                this.readyFunctionParams = options.readyFunctionParams;
            }
        } else {
            this.readyFunction = this.readyFunctionParams = null;
        }


        var _this = this;
        var promise = new Promise(function (resolve, reject) {

            /* 非微信浏览器的场合,返回正常数据,供测试用 */
            if (!_this.isWeixin()) {
                resolve({
                    wxError: 0,
                    wxObject: null,
                    wxTool: _this
                });
            }

            _this.loadJSSDKSignPackage(wxAppId, grpAppId).then(function (signConfig) {
                //微信配置注入
                wx.config({
                    debug: false,
                    appId: signConfig.wxAppId,
                    timestamp: signConfig.timeStamp,
                    nonceStr: signConfig.nonceStr,
                    signature: signConfig.signature,
                    jsApiList: [
                        'checkJsApi',
                        'chooseImage',
                        'previewImage',
                        'uploadImage',
                        'downloadImage',
                        'onMenuShareTimeline',
                        'onMenuShareAppMessage',
                        'onMenuShareQQ',
                        'onMenuShareWeibo',
                        'onMenuShareQZone',
                        'getLatestAddress',
                        'hideOptionMenu',
                        'hideToolbar',
                        'hideMenuItems'
                    ]
                });

                wx.ready(function () {
                    if (_this.readyFunction) {
                        _this.readyFunction(_this, _this.readyFunctionParams, wx);
                    }
                    resolve({
                        wxError: 0,
                        wxObject: wx,
                        wxTool: _this
                    });
                });

                wx.error(function (res) {
                    reject({
                        wxError: 1,
                        wxMessage: res
                    });
                });
            });
        });

        return promise;
    },


    getLocation: function () {
        var ret = {
            'retCode': 10001
        };

        return new Promise(function (resolve, reject) {
            wx.checkJsApi({
                jsApiList: ['getLocation'],
                success: function (res) {
                    if (res.checkResult.getLocation == true) {
                        wx.getLocation({
                            success: function (res) {
                                ret.retCode = 20000;
                                ret.latitude = res.latitude;
                                ret.longitude = res.longitude;
                                resolve(ret);
                            },
                            cancel: function (res) {
                                // 用户取消
                                resolve(ret);
                            }
                        });
                    } else {
                        reject(ret);
                    }
                },
            });
        });
    },

    /**
     * 微信分享功能
     */
    shareToOthers: function () {

    }
};