12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250 |
- !function (win, func) {
- typeof define == "function" && (define.amd || define.cmd) ? define(function() {
- return func(win);
- }) : func(win);
- }(this, function(win) {
- var andHandler = win.CTKJavaScriptHandler;
- var andApiLevel = andHandler && andHandler.getApiLevel() || 0;
- var iosHandler, iosApiLevel = 0;
- var NET_URL = 'http://121.52.250.37:15080';
- var TOUCHLIFE_URL = 'http://121.52.250.37:15080';
- var readyList = [];
- var ALIPAY_TYPE = 'alipay';
- var WEIPAY_TYPE = 'weipay';
- var WEIPAY_OEM_TYPE = 'weipay_oem';
- var successLogin, failLogin;
- var successSelect, failSelect;
- var payCallBack;
- var totalFee = 0, tradeService = '', products = [], cards = [];
- var submit;
- var loading, loadImg, loadText, loadTimer;
- var sucGetAddrCb; //address iframe post message;
- var addrFrame, addrLink; //address iframe;
- var addrFrameId = 'i-ct-op-address';
- var hasLoadAddressIFrame = false;
- var frame, link; //cashier iframe;
- var originDisplayState;
- var payType = '';
- var isIOS = win.navigator.userAgent.toLowerCase().indexOf('iphone') != -1;
- var base64 = new Base64();
- var apiList = {
- ready: { ios: 0, and: 0 },
- logged: { ios: 1, and: 10 },
- login: { ios: 1, and: 10 },
- select: { ios: 0, and: 0 },
- pay: {
- alipay: { ios: 1, and: 10 },
- weipay: { ios: 3, and: 19 }
- },
- show: { ios: 0, and: 0 },
- dismiss: { ios: 0, and: 0 },
- getLocation: { ios: 1, and: 0}
- }
- var caller = arguments.callee
- caller.NET_URL = NET_URL;
- caller.TOUCHLIFE_URL = TOUCHLIFE_URL;
- caller.pageBack = pageBack;
- caller.getToken = getToken;
- caller.getSecret = getSecret;
- caller.collectScenarioParams = collectScenarioParams;
- caller.andApiLevel = andApiLevel;
- caller.isIOS = isIOS;
- caller.shareToWechat = shareToWechat;
- caller.shareToMoment = shareToMoment;
- caller.loadFile = loadFile;
- caller.getItemFromStorage = getItemFromStorage;
- loadFile('style', NET_URL + '/res/css/lib/ctk_ui.css');
- loadFile('script', NET_URL + '/res/js/lib/ctk_ui.js');
- try {
- $;
- } catch (e) {
- try {
- window.$ = Zepto;
- } catch (e2) {
- try {
- window.$ = jQuery;
- } catch (e3) {
- loadFile('script', NET_URL + '/res/js/lib/zepto.v2.js');
- }
- }
- }
- if (isIOS) {
- (function(callback) {
- if (win.WebViewJavascriptBridge) {
- callback(WebViewJavascriptBridge)
- } else {
- document.addEventListener('WebViewJavascriptBridgeReady', function() {
- callback(WebViewJavascriptBridge)
- }, false);
- }
- })(function(bridge) {
- if (!bridge._messageHandler) {
- bridge.init(function(message, responseCallback) {});
- }
- console.log = function (data) {
- WebViewJavascriptBridge.callHandler('log', data, function(response) {});
- }
- win.onerror = function(sMsg, sUrl, sLine){
- console.log('sMsg: ' + sMsg + '; sUrl: ' + sUrl + '; sLine: ' + sLine);
- return false;
- }
- try {
- document.readyState == 'complete' && initCTK();
- } catch(e) {
- console.log('------------- init ctk error');
- }
- console.log('------------- init callback');
- win.CTK = win.CTK || {
- dispatchEvent: function() {
- console.log('------------- init dispatchEvent');
- var self = this;
- iosHandler = window.WebViewJavascriptBridge;
- iosApiLevel = self.ApiLevel;
- caller.iosApiLevel = iosApiLevel;
- console.log(iosHandler);
- console.log(iosApiLevel);
- iosApiLevel >= 3 && (history.back = pageBack);
- iosApiLevel >= 1 && (navigator.geolocation && (navigator.geolocation.getCurrentPosition = getCurrentPosition));
- readyList.forEach(function(node) {
- typeof node == 'function' && node();
- });
- showTarget(caller);
- }
- };
- var timer = setInterval(function() {
- if (window.WebViewJavascriptBridge) {
- if (iosHandler) {
- clearInterval(timer);
- } else {
- iosHandler = window.WebViewJavascriptBridge;
- iosApiLevel = CTK.ApiLevel;
- iosApiLevel >= 3 && (history.back = pageBack);
- iosApiLevel >= 1 && (navigator.geolocation && (navigator.geolocation.getCurrentPosition = getCurrentPosition));
- readyList.forEach(function(node) {
- typeof node == 'function' && node();
- });
- caller.iosApiLevel = iosApiLevel;
- showTarget(caller);
- }
- }
- }, 100);
- });
- } else {
- andApiLevel > 0 && (history.back = pageBack);
- if (andApiLevel >= 20) {
- andHandler.setOpenOrCloseXinGePush(true);
- }
- showTarget(caller);
- }
- // if (window.location.href.indexOf('sdk.hua1000.com/view/pay.html') != -1) {
- // showNotice2(caller, {
- // text: '点击”立即支付“,立享优惠'
- // });
- // }
- // if (window.location.href.indexOf('sdk.hua1000.com/view/submit.html') != -1) {
- // showNotice2(caller, {
- // text: '持券用户,立享优惠'
- // });
- // }
- // if (window.location.href.indexOf('sdk.hua1000.com/view/order.html') != -1) {
- // showNotice2(caller, {
- // text: '点击”立即支付“,立享优惠'
- // });
- // }
- // if (window.location.href.indexOf('http://m.lyancoffee.com/wechat/third/13/order/confirm') != -1) {
- // showNotice2(caller, {
- // text: '持券用户点“立即支付”可享优惠'
- // });
- // }
- // if (window.location.href.indexOf('http://www.iyishengyuan.com/common_pay_order/1.html') != -1 || window.location.href.indexOf('http://www.iyishengyuan.com/?_a=payOrder&_c=pay') != -1) {
- // showNotice2(caller, {
- // text: '持券用户点“立即支付”可享优惠',
- // type: 'top'
- // });
- // }
- // if (window.location.href.indexOf('http://www.dangaoss.com/h5/cart/checkout') != -1) {
- // showNotice2(caller, {
- // text: '提交订单,确认配送信息',
- // type: 'top'
- // });
- // }
- // if (window.location.href.indexOf('http://www.dangaoss.com/h5/order/show') != -1) {
- // showNotice2(caller, {
- // text: '点击“立即支付”,持券立享优惠',
- // type: 'top'
- // });
- // }
- // if (window.location.href.indexOf('http://www.openlife.mobi/confirmOrderPage?productId=6b33398a-68a0-428b-b756-9aa70c31c432') != -1) {
- // showNotice2(caller, {
- // text: '点击“确认支付”,持券立享优惠'
- // });
- // }
- window.addEventListener('message', function(event) {
- if (event.origin == NET_URL && event.data.type == 'tradeStr') {
- var tradeStr = event.data.tradeStr;
- payType = event.data.payType;
- if (tradeStr) {
- if (typeof successSelect == 'function') {
- successSelect({
- tradeStr: event.data.tradeStr
- });
- }
- } else {
- typeof failSelect == 'function' && failSelect({});
- }
- } else if (event.origin == NET_URL && event.data.type == 'getDefaultAddress') {
- var res = {
- 'name' : event.data.name,
- 'phone' : event.data.phone,
- 'province' : event.data.province,
- 'city' : event.data.city,
- 'country' : event.data.country,
- 'addr' : event.data.addr,
- 'contact_id' : event.data.contact_id,
- };
- if (typeof sucGetAddrCb == 'function') {
- setTimeout(function() {
- var action = event.data.action;
- if (!action) {
- if (!event.data.noBack) {
- if (window.location.hash == '#address') {
- hiddenOrShowOtherDiv(addrFrameId, false);
- pageBack();
- }
- }
- sucGetAddrCb(res);
- } else if (action == 'del') { // 有些业务需要知道某个地址被删除了;
- res['action'] = 'del';
- sucGetAddrCb(res);
- }
- }, 200);
- }
- } else if (event.origin == NET_URL && event.data.type == 'log') {
- console.log(event.data.log);
- }
- });
- function initCTK() {
- WebViewJavascriptBridge.callHandler('getLoginNumber', null, function(res) {
- CTK.LoginNumber = res;
- });
- WebViewJavascriptBridge.callHandler('getAuthToken', null, function(res) {
- CTK.AuthToken = res;
- });
- WebViewJavascriptBridge.callHandler('getApiLevel', null, function(res) {
- CTK.ApiLevel = iosApiLevel = res*1;
- });
- WebViewJavascriptBridge.callHandler('getSecret', null, function(res) {
- CTK.Secret = res;
- });
- WebViewJavascriptBridge.callHandler('getWXPaySupported', null, function(res) {
- switch (res) {
- case 'true':
- CTK.WXPaySupported = true;
- break;
- case 'false':
- CTK.WXPaySupported = false;
- break;
- }
- });
- WebViewJavascriptBridge.callHandler('getWeixinAppInstalled', null, function(res) {
- switch (res) {
- case 'true':
- CTK.WXAppInstalled = true;
- break;
- case 'false':
- CTK.WXAppInstalled = false;
- break;
- }
- });
- }
- function inner() {
- var number = getLoginNumber() + '';
- if (number.indexOf('13800000000') != -1) {
- return true;
- } else {
- return false;
- }
- }
- function loadFile(type, url) {
- if ((type + url) in window) {
- return;
- }
- var node = document.createElement(type);
- var xhr = new XMLHttpRequest();
- xhr.onreadystatechange = function() {
- if (xhr.readyState == 4 && ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304)) {
- node.innerHTML = xhr.responseText;
- document.head.appendChild(node);
- window[type + url] = true;
- }
- }
- xhr.open("GET", url, false);
- xhr.send(null);
- }
- function initPayPopup() {
- frame = document.createElement('div');
- link = document.createElement('iframe');
- frame.style.cssText = 'position: fixed; top: 0; left: 0; z-index: 9999; width: 100%; height: 100%; display: none';
- link.style.cssText = 'display: block; width: 100%; height: 100%';
- link.setAttribute('frameborder', '0');
- link.src = NET_URL + '/page_v3/cashier.html?tradeService=' + tradeService + '&totalFee=' + totalFee;
- frame.appendChild(link);
- document.body.appendChild(frame);
- window.cashierLink = link;
- window.removeEventListener('hashchange', _hideLogin);
- window.addEventListener('hashchange', _hideLogin);
- //isLoadCompleted用于判断iframe是否加载完毕
- link.addEventListener('load',function(){
- window.isIframeLoadCompleted = true;
- window.loadQueue && window.loadQueue();
- },false);
- function _hideLogin() {
- if (window.location.hash != '#cashier') {
- frame.style.display = 'none';
- link.contentWindow && link.contentWindow.postMessage({
- status: 'close'
- }, '*');
- }
- }
- }
- function initAddress() {
- function _hideLogin() {
- var h = window.location.hash;
- if (h == '') {
- CTAW.hidden();
- }
- }
- //set localstorage native_param_addr
- var _addr = getItemFromStorage('native_param_addr');
- if (_addr && _addr.length > 0) {
- localStorage.setItem('native_param_addr', _addr);
- }
- console.log('ycs call CTAW init');
- CTAW.init();
- window.addEventListener('hashchange', _hideLogin);
- }
- function showPayPopup(inapp) {
- var ali = true;
- var wei = true;
- if (isIOS && iosApiLevel < 3) {
- wei = false;
- } else if (!isIOS && andApiLevel < 19) {
- if (andApiLevel < 10) {
- ali = false;
- }
- wei = false;
- } else {
- // android higher version
- if (!isWXAppInstalled()) {
- wei = false;
- } else if (!isWXPaySupported()) {
- wei = false;
- }
- }
- frame.style.display = 'block';
- link.contentWindow.postMessage({
- status: 'start',
- tradeService: tradeService,
- products : products || [],
- totalFee: totalFee,
- token: getToken(),
- secret: getSecret(),
- ali: ali,
- wei: wei,
- inapp: inapp || false
- }, '*');
- window.location.hash = '#cashier';
- }
- function showAddress(_curContactId) {
- var msg = {
- status : 'start'
- }
- if (_curContactId && _curContactId.length > 5) {
- msg.curContactId = _curContactId;
- }
- if (isIOS) {
- var token = getToken();
- msg.token = token; //iOS在跨域的情况下,iframe页面无法通过调接口获取token,需要传参;
- addrLink.contentWindow.postMessage(msg, '*');
- setTimeout(function() {
- addrFrame.style.display = 'block';
- window.location.hash = '#address';
- hiddenOrShowOtherDiv(addrFrameId, true);
- }, 500);
- } else {
- // 地址控件页面要求一个状态切换,即输入框页面滑动,为了不让用户看到,先发一个message告诉地址控件页面滑动;
- // 也发现在部分机型上,父页面的点击事件会传到地址控件页面导致出错,将timeout时间设为500可以解决该问题;
- addrLink.contentWindow.postMessage(msg, '*');
- setTimeout(function() {
- addrFrame.style.display = 'block';
- window.location.hash = '#address';
- hiddenOrShowOtherDiv(addrFrameId, true);
- }, 500);
- }
- }
- // iOS特殊处理,iPhone6、5c上发现弹出键盘后会把父页面显示出来;
- // hidden 必须是 true,false成对调用,当hidden为true时初始化originDisplayState;
- function hiddenOrShowOtherDiv(assignId, hidden) {
- if (!isIOS) {
- return;
- }
- var cs = document.body.children;
- if (hidden) {
- originDisplayState = new Array(cs.length + 2);
- }
- for (var i = 0; i < cs.length; ++i) {
- var item = cs[i];
- if (item.tagName == 'SCRIPT') { // script标签忽略;
- continue;
- }
- if (item.getAttribute('id') == assignId) { // 需要显示的iframe忽略;
- continue;
- }
- if (hidden) { // 隐藏所有子元素,先记录原来的状态;
- originDisplayState[i] = item.style.display;
- item.style.display = 'none';
- } else { // 恢复所有子元素原来的状态;
- item.style.display = originDisplayState[i];
- }
- }
- }
- function decodeIOSSecret(secret) {
- var e = "";
- for (var i = 0; i < secret.length; i++)
- {
- e += String.fromCharCode((secret.charCodeAt(i) - 33) / 3);
- }
- var middle = e.length - parseInt(e.length / 4);
- var prefix = e.substring(0, middle);
- var suffix = e.substring(middle, e.length);
- var unmix = suffix + prefix;
- middle = unmix.length - parseInt(unmix.length / 7);
- prefix = unmix.substring(0, middle);
- suffix = unmix.substring(middle, unmix.length);
- return suffix + prefix;
- }
- function payResult(resCode){
- var url = 'http://open.cootekservice.com/pay/result?transactionId=' + localStorage.getItem('transaction_id') + "&resCode=" + resCode + '&_token=' + getToken();
- var xhr = new XMLHttpRequest();
- xhr.open("GET", url, true);
- xhr.send(null);
- }
- function initLoading() {
- loading = document.createElement('div');
- loadImg = document.createElement('img');
- loadText = document.createElement('p');
- loading.style.cssText = 'position: fixed; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); display: inline-block; background-color: rgba(0, 0, 0, 0.7); border-radius: 3px; z-index: 10000; white-space: nowrap';
- loadImg.style.cssText = 'position: absolute; top: 50%; left: 5px; margin-top: -6px; width: 12px; height: 12px';
- loadText.style.cssText = 'margin-left: 22px; color: #fff; font-size: 1.2rem; height: 3rem; line-height: 3rem; padding-right: 5px';
- loadImg.src = NET_URL + '/res/image/load_circle.png';
- loading.appendChild(loadImg);
- loading.appendChild(loadText);
- }
- function getAccessToken() {
- // 2015-10-14, use AES, see auth/login api response;
- // 作好兼容性处理,对于从已登陆的旧版本升级到新版本的用户来说,直接通过接口获取accessToken会得到空值,此时应该继续使用旧的accessToken;
- if (andApiLevel >= 32) {
- var t = andHandler.getAccessToken();
- } else if (isIOS && iosApiLevel >= 20) {
- var t = CTK.AccessToken;
- }
- if (t && t.length > 5) {
- return t;
- }
- var session = {
- token: getToken(),
- etoken: ''
- }
- return base64.encode(JSON.stringify(session));
- }
- function submitPay(event) {
- event && event.preventDefault();
- event && event.stopPropagation();
- var ret = {
- "paymentType": payType,
- "authToken": getToken(),
- }
- cards.length > 0 && (ret['cards'] = cards);
- failSelect = null;
- if (typeof successSelect == 'function') {
- submit && submit.removeEventListener('click', submitPay, false);
- submit && (submit.style.backgroundColor = '#abcfe9');
- successSelect({
- tradeStr: base64.encode(JSON.stringify(ret))
- });
- }
- }
- function collectScenarioParams(id, name) {
- var state = {
- 'id' : id,
- 'name' : name,
- 'version' : 0,
- 'city' : getItemFromStorage('city'),
- 'geo_city' : getItemFromStorage('native_param_city'),
- 'source' : window.location.href,
- 'trigger_time': +new Date()
- };
- state = JSON.stringify(state);
- if (!isIOS && andApiLevel >= 3) {
- andHandler.appendScenarioNode(state);
- } else if (isIOS && iosApiLevel >= 1) {
- iosHandler.callHandler('appendScenarioNode', state, function(response) {
- console.log(response);
- });
- } else {
- console.log('no appendScenarioNode');
- }
- }
- function shareToWechat(param) {
- var hasParam = param.url.indexOf('?') === -1;
- url = hasParam ? param.url + '?client=wechat' : param.url + '&client=wechat';
- var data = JSON.stringify({
- 'type' : 'wechat',
- 'msg' : param.msg,
- 'url' : url,
- 'title' : param.title,
- });
- if (!isIOS && andApiLevel >= 9) {
- andHandler.shareMessage(data);
- } else if (isIOS && iosApiLevel >= 4) {
- iosHandler.callHandler('shareWXMessage', data, function(response) {
- console.log(response);
- });
- } else {
- console.log('no share wechat!');
- }
- }
- function shareToMoment(param) {
- var hasParam = param.url.indexOf('?') === -1;
- url = hasParam ? param.url + '?client=wechat' : param.url + '&client=wechat';
- var data = JSON.stringify({
- 'type' : 'wechat_moment',
- 'url' : url,
- 'title' : param.title,
- 'wechat_share_image_kind' : 2,
- 'imagePath' : 'webpages/share_icon',
- 'imageName' : '',
- });
- if (!isIOS && andApiLevel >= 15) {
- andHandler.shareWechatMoment(data);
- } else if (isIOS && iosApiLevel >= 4) {
- iosHandler.callHandler('shareWXMoment', data, function(response) {
- console.log(response);
- });
- } else {
- console.log('no share moment!');
- }
- }
- function getToken() {
- if (isIOS && iosHandler) {
- return CTK.AuthToken;
- } else {
- return andHandler ? andHandler.getAuthToken() : localStorage.getItem('auth_token');
- }
- }
- function pageBack() {
- if (!isIOS && andApiLevel >= 1) {
- andHandler.backPage();
- } else if (isIOS && iosApiLevel >= 3) {
- iosHandler.callHandler('backPage', '', function(response) {
- console.log(response);
- });
- } else {
- history.back();
- }
- }
- function getLoginNumber() {
- if (!isIOS && andApiLevel >= 10) {
- return andHandler.getLoginNumber();
- } else if (isIOS && iosHandler) {
- return CTK.LoginNumber;
- } else {
- return '';
- }
- }
- function getSecret() {
- if (!isIOS && andApiLevel >= 10) {
- return andHandler.getSecret();
- } else if (isIOS && iosHandler) {
- var secret = CTK.Secret;
- if (iosApiLevel <= 9) {
- secret = decodeIOSSecret(secret);
- }
- return secret;
- } else {
- return '';
- }
- }
- // 分服务商、分用户存储的一个key;
- // eg. ct_op_storage_addr_com.lyancoffee.coffee_18621213333 表示用户18621213333在连咖啡存储地址的key;
- function getStorageKey(tag) {
- var ph = getLoginNumber();
- if (!ph || ph.length == 0) {
- ph = getToken();
- }
- var key = 'ct_cache_' + ph + '_' + tag;
- return key;
- }
- function isWXAppInstalled() {
- if (!isIOS && andApiLevel >= 19) {
- return andHandler.isWXAppInstalled();
- } else if (isIOS && iosApiLevel >= 3) {
- return CTK.WXAppInstalled;
- } else {
- return false;
- }
- }
- function isWXPaySupported() {
- if (!isIOS && andApiLevel >= 19) {
- return andHandler.isWXPaySupported();
- } else if (isIOS && iosApiLevel >= 3) {
- return CTK.WXPaySupported;
- } else {
- return false;
- }
- }
- function alipayFunc(info) {
- if (!isIOS && andApiLevel >= 10) {
- return andHandler.alipay(info, 'CTKCallBackFuncs.payCallBack');
- } else if (isIOS && iosHandler) {
- var info2 = info.slice(0,-1);
- // self.alipayCallback = callback;
- var data = {
- callback: 'CTKCallBackFuncs.alipayHandler',
- info: info
- };
- info2.split('"&').forEach(function(value) {
- var item = value.split('="');
- data[item[0]] = item[1];
- });
- console.log('--------- ' + JSON.stringify(data));
- iosHandler.callHandler('alipay', JSON.stringify(data), function(response) {
- console.log(response)
- });
- }
- }
- function weipayFunc(info) {
- if (!isIOS && andApiLevel >= 19) {
- return andHandler.weixinpay(info, 'CTKCallBackFuncs.payCallBack');
- } else if (isIOS && iosApiLevel >= 3) {
- var data = JSON.parse(info);
- data.callback = 'CTKCallBackFuncs.weipayHandler';
- iosHandler.callHandler('weixinpay', JSON.stringify(data), function(response) {
- console.log(response)
- });
- }
- }
- function locate() {
- if (!isIOS && andApiLevel >= 1) {
- andHandler.locate();
- } else if (isIOS && iosApiLevel >= 1) {
- iosHandler.callHandler('locate', 'CTKCallBackFuncs.locateCallback', function(response) {
- console.log(response);
- });
- }
- }
- function getValue(key, getValue, data) {
- if (iosHandler) {
- if (CTK[key] && !getValue) {
- return CTK[key];
- }
- if (key == 'LocateCacheTime' && !getValue) {
- return CTK.LocateCacheTime || CTK.LocationCacheTime;
- }
- iosHandler.callHandler('get' + key, data, function(response) {
- console.log('respone: ' + response)
- switch (response) {
- case 'true':
- CTK[key] = true;
- break;
- case 'false':
- CTK[key] = false;
- break;
- default:
- CTK[key] = response;
- }
- });
- }
- }
- function getItemFromStorage(key, noValue) {
- if (!isIOS && andApiLevel >= 1) {
- return andHandler.storageGetItem(key);
- } else if (isIOS) {
- if (iosHandler && iosApiLevel <= 2) {
- switch (key) {
- case 'native_param_location':
- return getValue('Location', noValue);
- case 'native_param_city':
- return getValue('City', noValue);
- case 'native_param_addr':
- return getValue('Address', noValue);
- case 'native_param_locate_cache_time':
- return getValue('LocateCacheTime', noValue);
- case 'native_param_city_cache_time':
- return getValue('CityCacheTime', noValue);
- case 'native_param_addr_cache_time':
- return getValue('AddrCacheTime', noValue);
- default:
- return localStorage.getItem(key);
- }
- } else {
- return localStorage.getItem(key);
- }
- } else {
- return localStorage.getItem(key);
- }
- }
- function setItemToStorage(k, v) {
- if (!isIOS && andApiLevel > 0) {
- andHandler.storageSetItem(k, v);
- } else {
- localStorage.setItem(k, v);
- }
- }
- function getCurrentPosition(success, error, options) {
- ctk.getLocation({
- success: function(ret) {
- success({
- coords: {
- city: ret.city,
- address: ret.address,
- latitude: ret.latitude,
- longitude: ret.longitude
- },
- timestamp: getItemFromStorage('native_param_locate_cache_time')
- });
- }
- });
- }
- function Base64() {
- // private property
- _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
- // public method for encoding
- this.encode = function (input) {
- var output = "";
- var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
- var i = 0;
- input = _utf8_encode(input);
- while (i < input.length) {
- chr1 = input.charCodeAt(i++);
- chr2 = input.charCodeAt(i++);
- chr3 = input.charCodeAt(i++);
- enc1 = chr1 >> 2;
- enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
- enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
- enc4 = chr3 & 63;
- if (isNaN(chr2)) {
- enc3 = enc4 = 64;
- } else if (isNaN(chr3)) {
- enc4 = 64;
- }
- output = output +
- _keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
- _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
- }
- return output;
- }
- // public method for decoding
- this.decode = function (input) {
- var output = "";
- var chr1, chr2, chr3;
- var enc1, enc2, enc3, enc4;
- var i = 0;
- input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
- while (i < input.length) {
- enc1 = _keyStr.indexOf(input.charAt(i++));
- enc2 = _keyStr.indexOf(input.charAt(i++));
- enc3 = _keyStr.indexOf(input.charAt(i++));
- enc4 = _keyStr.indexOf(input.charAt(i++));
- chr1 = (enc1 << 2) | (enc2 >> 4);
- chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
- chr3 = ((enc3 & 3) << 6) | enc4;
- output = output + String.fromCharCode(chr1);
- if (enc3 != 64) {
- output = output + String.fromCharCode(chr2);
- }
- if (enc4 != 64) {
- output = output + String.fromCharCode(chr3);
- }
- }
- output = _utf8_decode(output);
- return output;
- }
- // private method for UTF-8 encoding
- _utf8_encode = function (string) {
- string = string.replace(/\r\n/g,"\n");
- var utftext = "";
- for (var n = 0; n < string.length; n++) {
- var c = string.charCodeAt(n);
- if (c < 128) {
- utftext += String.fromCharCode(c);
- } else if((c > 127) && (c < 2048)) {
- utftext += String.fromCharCode((c >> 6) | 192);
- utftext += String.fromCharCode((c & 63) | 128);
- } else {
- utftext += String.fromCharCode((c >> 12) | 224);
- utftext += String.fromCharCode(((c >> 6) & 63) | 128);
- utftext += String.fromCharCode((c & 63) | 128);
- }
- }
- return utftext;
- }
- // private method for UTF-8 decoding
- _utf8_decode = function (utftext) {
- var string = "";
- var i = 0;
- var c = c1 = c2 = 0;
- while ( i < utftext.length ) {
- c = utftext.charCodeAt(i);
- if (c < 128) {
- string += String.fromCharCode(c);
- i++;
- } else if((c > 191) && (c < 224)) {
- c2 = utftext.charCodeAt(i+1);
- string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
- i += 2;
- } else {
- c2 = utftext.charCodeAt(i+1);
- c3 = utftext.charCodeAt(i+2);
- string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
- i += 3;
- }
- }
- return string;
- }
- }
- var ShareCallbacks = {
- shareCallback: function(result) {
- console.log('share' + result);
- },
- queryCallback: function(params, reference) {
- console.log('params is ' + params + ' reference ' + reference);
- }
- };
- var CTKCallBackFuncs = {
- loginCallBack: function(success) {
- if (success) {
- var phone = getLoginNumber();
- typeof successLogin == 'function' && successLogin({
- accessToken: getAccessToken()
- });
- } else {
- typeof failLogin == 'function' && failLogin({});
- }
- },
- iosLoginCallBack: function(ret) {
- var self = this;
- CTK.AuthToken = ret['token'];
- CTK.Secret = ret['secret'];
- CTK.LoginNumber = ret['loginnumber'];
- switch (ret['isLogged']) {
- case 'true':
- CTK.Logged = true;
- break;
- case 'false':
- CTK.Logged = false;
- break;
- }
- self.loginCallBack(CTK.Logged);
- },
- payCallBack: function(res) {
- console.log('-------------- ' + res);
- var resCode;
- var success = false;
- if (payType == ALIPAY_TYPE) {
- resCode = res.slice(14, 18) * 1;
- } else if (payType == WEIPAY_TYPE || payType == WEIPAY_OEM_TYPE) {
- resCode = res + '';
- }
- switch(resCode) {
- case 9000:
- case '0':
- resCode = 4102; //success
- success = true;
- break;
- case 8000:
- resCode = 4105; //dealing
- break;
- case 6001:
- case '-2':
- resCode = 4107; //cancel
- break;
- case 6002:
- case '-1':
- resCode = 4108; //network-error
- break;
- default:
- resCode = 4106; //failed
- break;
- }
- payResult(resCode);
- console.log('-------------- ' + resCode);
- webShare = false;
- if (success){
- var params = {scene_limit:'AFTER_TRADE', service:tradeService, transaction_id: localStorage.getItem('transaction_id')};
- console.log(params);
- console.log('---------------------- ' +iosApiLevel)
- if (isIOS && iosApiLevel >= 7) {
- var paramObj = {"params": JSON.stringify(params)};
- iosHandler.callHandler('tryShareWithParams', paramObj, null);
- }else if (!isIOS && andApiLevel >= 29) {
- andHandler.tryShare(JSON.stringify(params), 'ShareCallbacks.shareCallback');
- }else{
- console.log('no native share');
- webShare = true;
- }
- }
- setTimeout(function() {
- window.location.hash == '#cashier' && pageBack();
- setTimeout(function() {
- payCallBack(resCode);
- }, 300);
- if(webShare){
- loadFile('style', NET_URL + '/res/css/lib/ctk_ui.css');
- loadFile('script', NET_URL + '/res/js/lib/ctk_ui.js');
- caller.ctk = ctk;
- ctk.ready(function(){
- setTimeout(function() {
- getShare(caller, tradeService);
- }, 500);
- });
- }
- }, 100);
- },
- alipayHandler: function(ret) {
- console.log('------------- ret : ' + JSON.stringify(ret));
- var self = this;
- var result = 'resultStatus={' + ret['resultStatus'] + '};memo={' + ret['memo'] + '};result={' + ret['result'] + '}';
- self.payCallBack(result);
- },
- weipayHandler: function(ret) {
- var self = this;
- self.payCallBack(ret);
- },
- locateCallback: function(ret) {
- getItemFromStorage('native_param_location', true);
- getItemFromStorage('native_param_city', true);
- getItemFromStorage('native_param_addr', true);
- getItemFromStorage('native_param_locate_cache_time', true);
- getItemFromStorage('native_param_city_cache_time', true);
- getItemFromStorage('native_param_addr_cache_time', true);
- },
- // private use only
- setPayType: function(type) {
- payType = type;
- },
- getPayType: function() {
- return payType;
- }
- }
- var ctk = {
- ready: function(func) {
- if (isIOS && !iosHandler) {
- readyList.push(func);
- } else {
- typeof func == 'function' && func();
- }
- },
- logged: function(param) {
- var isLogged;
- if (!isIOS && andApiLevel >= 10) {
- isLogged = andHandler.isLogged();
- } else if (isIOS && iosHandler) {
- // isLogged = CTK.Logged;
- isLogged = !!CTK.LoginNumber;
- } else {
- isLogged = false;
- }
- if (isLogged) {
- param.yes({
- accessToken: getAccessToken()
- });
- } else {
- param.no({});
- }
- },
- login: function(param) {
- successLogin = param.success;
- failLogin = param.fail;
- if (!isIOS && andApiLevel >= 10) {
- andHandler.login('获取验证码', param.phone || '', 'CTKCallBackFuncs.loginCallBack');
- } else if (isIOS && iosHandler) {
- var data = {
- title: '获取验证码',
- phone: param.phone || '',
- callback: 'CTKCallBackFuncs.iosLoginCallBack'
- };
- iosHandler.callHandler('login', JSON.stringify(data), function(response) {
- console.log(response)
- });
- }
- },
- select: function(param) {
- successSelect = param.success;
- failSelect = param.fail;
- totalFee = (param.totalFee/100).toFixed(2);
- tradeService = param.tradeService;
- products = param.products || [];
- if (window.isIframeLoadCompleted){
- showPayPopup(param.inapp);
- }else{
- window.loadQueue = function(){
- showPayPopup(param.inapp);
- };
- }
- // queryCardInfo();
- collectScenarioParams(173, 'payment_popup_show');
- },
- selectCootek: function(param) {
- successSelect = param.success;
- failSelect = param.fail;
- totalFee = (param.totalFee/100).toFixed(2);
- tradeService = param.tradeService;
- products = param.products || [];
- submitPay();
- },
- pay: function(param) {
- console.log('---------- pay start');
- console.log(JSON.stringify(param));
- var payData = JSON.parse(base64.decode(param.payStr));
- console.log('---------- pay data: ' + base64.decode(param.payStr));
- payCallBack = param.finish;
- if (payData.paymentType == ALIPAY_TYPE) {
- console.log('---------- alipay');
- alipayFunc(payData.paymentData);
- } else if (payData.paymentType == WEIPAY_TYPE || payData.paymentType == WEIPAY_OEM_TYPE) {
- console.log('---------- weipay');
- weipayFunc(payData.paymentData);
- }
- localStorage.setItem('transaction_id', payData.transactionId);
- },
- show: function() {
- !loading && initLoading();
- var deg = 0;
- function _rotate() {
- if (deg < 360) {
- deg += 15;
- } else {
- deg = 15;
- }
- loadImg.style.webkitTransform = 'rotate(' + deg + 'deg)';
- }
- loadText.innerHTML = payType == 'alipay' ? '正在跳转支付宝支付' : '正在跳转微信支付';
- loadTimer = setInterval(_rotate, 20);
- document.body.appendChild(loading);
- },
- dismiss: function() {
- if (!loadTimer) {
- return;
- }
- clearInterval(loadTimer);
- loadTimer = null;
- document.body.removeChild(loading);
- },
- checkJsApi: function(param) {
- var result = {};
- var hasCorrectApi = false;
- param.jsApiList.forEach(function(node, i) {
- if (node in apiList) {
- if (node == 'pay') {
- hasCorrectApi = true;
- result.pay = {
- alipay: (isIOS && iosApiLevel >= apiList.pay.alipay.ios) || (!isIOS && andApiLevel >= apiList.pay.alipay.and),
- weipay: (isIOS && iosApiLevel >= apiList.pay.weipay.ios) || (!isIOS && andApiLevel >= apiList.pay.weipay.and)
- }
- } else {
- result[node] = (isIOS && iosApiLevel >= apiList[node].ios) || (!isIOS && andApiLevel >= apiList[node].and);
- }
- } else {
- console.log('txm: api name error! error name: ' + node);
- }
- });
- if (typeof param.success == 'function') {
- param.success({
- errMsg: hasCorrectApi ? 'check success!' : 'no correct api name!',
- result: result
- });
- } else {
- console.log('success callback type error!');
- }
- },
- getLocation: function(param) {
- var lastCacheTime = getItemFromStorage('native_param_locate_cache_time');
- locate();
- var timer = setInterval(_checkCacheTime, 100);
- var count = 0;
- function _checkCacheTime() {
- cacheTime = getItemFromStorage('native_param_locate_cache_time');
- if (cacheTime != lastCacheTime) {
- var loc = getItemFromStorage('native_param_location');
- loc = loc ? JSON.parse(loc) : {};
- clearInterval(timer);
- typeof param.success == 'function' && param.success({
- city: getItemFromStorage('native_param_city') || '',
- address: getItemFromStorage('native_param_addr') || '',
- latitude: loc[0] || '',
- longitude: loc[1] || ''
- });
- }
- count++;
- if (count > 100) {
- clearInterval(timer);
- typeof param.success == 'function' && param.success({
- city: '',
- address: '',
- latitude: '',
- longitude: ''
- });
- }
- }
- },
- config : function(appkey, serviceId, timestamp, charset, signType, host, jsApiList, sign) {
- tradeService = serviceId;
- for (var i = 0; i < jsApiList.length; ++i) {
- var api = jsApiList[i];
- if (api == 'getDefaultAddress') {
- //初始化选择编辑地址页面op_address.html;
- initAddress();
- }
- }
- },
- getDefaultAddress: function(param) {
- function getAddrCb(d) {
- if (typeof param.success == 'function') {
- param.success(d);
- if (window.location.hash == '#address') {
- pageBack();
- }
- } else {
- alert('未知错误,没有接收地址的函数');
- }
- }
- if (param.showAddressPage) { // 弹出地址信息页;
- window.location.hash = '#address';
- CTAW.show(param.curContactId, getAddrCb);
- } else { // 取默认地址的缓存,触宝为第三方作存储,注意做到区分用户,区分服务商存储;
- var k = getStorageKey('default_addr');
- var v = getItemFromStorage(k);
- if (v && v.length > 5) {
- var d = JSON.parse(v);
- param.success(d);
- } else {
- param.success(null);
- }
- }
- },
- processAjaxError: function(req, http_status, res){
- var that = this;
- that.dismiss();
- if (http_status == 'timeout') {
- window.alert("服务器超时,请稍后再试!")
- } else if(http_status == 'abort') {
- window.alert('请求出现错误,请检查您的网络!');
- window.cashierLink.contentWindow.postMessage({
- status: 'active'
- }, "*");
- } else if (http_status == 500) {
- window.alert('您访问太过频繁,请稍后再试!');
- }
- res = (res !== null) && JSON.parse(res);
- switch(res.result_code) {
- case 4002:
- alert('本地时间错误,请求失败,请校准时间后再试!');
- break;
- }
- }
- };
- document.readyState == 'complete' ? initPayPopup() : win.addEventListener('load', initPayPopup, false);
- andApiLevel > 1 && (navigator.geolocation && (navigator.geolocation.getCurrentPosition = getCurrentPosition));
- win.CTKCallBackFuncs = CTKCallBackFuncs;
- win.ShareCallbacks = ShareCallbacks;
- return win.ctk = ctk;
- });
|