Authored by 陈峰

Merge branch 'feature/mini' into 'master'

es5 改写



See merge request !8
{
"presets": ["es2015","stage-0"],
"presets": ["es2015", "stage-0"],
"plugins": [
"transform-runtime",
"syntax-dynamic-import"
... ...
language : node_js
node_js:
- "10"
branches:
only:
- master
install:
- npm install
os:
- linux
stages:
- name: deploy
jobs:
include:
- stage: deploy
script:
- echo "NPM Deploying Started ..."
- npm version
- npm run build
- echo "NPM Building Finished."
deploy:
provider: npm
email: chenfengjw@hotmail.com
api_key: "$NPM_TOKEN"
skip_cleanup: true
on:
all_branches: true
\ No newline at end of file
... ... @@ -18,7 +18,11 @@
2. 微信验签方法提供
## 使用说明
可以直接import也可以define()
activity-sdk依赖wx-js-sdk,无论登陆还是页面跳转还是分享等等都依赖wx-js-sdk
所以在加载activity-sdk之前先加载wx-js-sdk,之后再调用activity-sdk的方法
可以直接import也可以define();
如果是在html页面引入window.yo_sdk可以获取到所有的api
... ... @@ -51,17 +55,18 @@
用法:`let env = window.yo_sdk.env`
#### getUid:
#### getUser:
类型:function
描述:获取当前用户uid,如果没有用户则该值为0
描述:获取当前用户uid,sessionKey,sessionType,appVersion以Object类型返回,如果没有用户则该uid值为0
用法:
```
//执行返回的是一个Promise对象
window.yo_sdk.getUid().
then(function(uid){
console.log(uid);
window.yo_sdk.getUser().
then(function(user){
console.log(user);
//返回 {uid:1,sessionType:'',sessionKey:'',appVersion:''}
})
```
... ...
This diff could not be displayed because it is too large.
... ... @@ -12,15 +12,18 @@
<a class="auth" href="http://www.baidu.com">123123</a>
<div id="uid"></div>
<div id="url"></div>
<script src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>
<script src="../build/sdk.js"></script>
<script>
window.yo_sdk.auth();
document.getElementById('aaa').onclick = function (event) {
window.yo_sdk.getUid().then(function(uid){
console.log(uid);
document.getElementById('uid').innerText = uid;
})
window.yo_sdk.getUser().then(function (user) {
console.log(user.uid);
if (user.uid)
document.getElementById('uid').innerText = user.uid;
else
window.yo_sdk.goLogin();
})
}
document.getElementById('url').innerText = location.href;
</script>
... ...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
</html>
... ...
... ... @@ -8,9 +8,10 @@
</head>
<body>
<div id="share"> 分享</div>
<script src="https://res.wx.qq.com/open/js/jweixin-1.3.2.js"></script>
<script src="../build/sdk.js"></script>
<script>
let shareData = {
var shareData = {
title: '国潮崛起年,中西碰撞博出位!',
imgUrl: 'https://img01.yohoboys.com/o_1cnilugbs15ajak1gfo1d2h1p348.png?imageView2/1/w/200/h/200',
desc: '这里有一份中西潮流榜单,请收好!',
... ...
{
"name": "yoho-activity-sdk",
"version": "1.0.8",
"version": "1.0.9",
"description": "YOHO!前端js的功能封装包,主要用于在活动页面中,对主要功能的封装。",
"keywords": [
"YOHO!",
... ... @@ -8,7 +8,7 @@
],
"main": "build/sdk.js",
"scripts": {
"build": "webpack --mode development --config ./webpack.config.babel.js ",
"build": "webpack --mode production --config ./webpack.config.js ",
"lint-js": "lint-js"
},
"config": {
... ... @@ -32,27 +32,26 @@
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-plugin-import": "^1.7.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.6.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-0": "^6.24.1",
"clean-webpack-plugin": "^0.1.19",
"compression-webpack-plugin": "^1.1.11",
"copy-webpack-plugin": "^4.5.1",
"extract-text-webpack-plugin": "^4.0.0-beta.0",
"uglifyjs-webpack-plugin": "^2.0.1",
"file-loader": "^1.1.11",
"url-loader": "^1.0.1",
"webpack": "^4.17.2",
"webpack-cli": "^3.1.2",
"weixin-js-sdk": "^1.3.3",
"fetch-jsonp": "^1.1.3",
"eslint": "^3.19.0",
"eslint-config-yoho": "^1.0.1",
"eslint-loader": "^1.7.1",
"eslint-plugin-html": "^2.0.3",
"promise-polyfill": "^8.1.0"
"extract-text-webpack-plugin": "^4.0.0-beta.0",
"fetch-jsonp": "^1.1.3",
"file-loader": "^1.1.11",
"uglifyjs-webpack-plugin": "^2.0.1",
"url-loader": "^1.0.1",
"webpack": "^4.17.2",
"webpack-bundle-analyzer": "^3.0.3",
"webpack-cli": "^3.1.2"
},
"dependencies": {},
"directories": {
... ...
import base from './public/base'
import Login from './public/login'
import Goto from './public/goto'
import wxCtrl from './public/share'
import {getQueryObj,invokeMethod} from './utils/common'
var base = require('./public/base');
var Login = require('./public/login');
var Goto = require('./public/goto');
var wxCtrl = require('./public/share');
var common = require('./utils/common');
var env = base.env();
var loginUrl = base.loginUrl();
var login = new Login({loginUrl:loginUrl, env:env});
var goto = new Goto(env);
var wx = new wxCtrl();
const env = base.env();
const loginUrl = base.loginUrl();
const login = new Login({loginUrl, env});
const goto = new Goto(env);
const wx = new wxCtrl();
export default {
module.exports = {
auth:login.auth.bind(login),
goLogin: login.goLogin.bind(login),
getUser:base.getUser,
... ... @@ -19,6 +18,6 @@ export default {
goBack: goto.goBack.bind(goto),
wxShare: wx.wxShare.bind(wx),
wxSignature: wx.wxSignature,
getQueryObj,
invokeMethod
getQueryObj:common.getQueryObj,
invokeMethod:common.invokeMethod
}
... ...
import jsonp from "../utils/jsonp";
import cookies from '../utils/cookie';
import {getQueryObj} from '../utils/common'
import Promise from 'promise-polyfill'
import {invokeMethod} from '../utils/common'
const parseUrl = (url) => {
let query = {},
var jsonp = require('../utils/jsonp');
var cookies = require('../utils/cookie');
var common = require('../utils/common');
var Promise = require('../utils/promise');
var getQueryObj = common.getQueryObj;
var parseUrl = function (url) {
var query = {},
hashs,
hash,
i;
... ... @@ -25,42 +24,44 @@ const parseUrl = (url) => {
query: query
}
};
let env = '';
const _appGetUid = function () {
var env = '';
var _appGetUid = function () {
return new Promise(function (resolve) {
invokeMethod({
common.invokeMethod({
method: 'get.uid',
arguments: {},
success: function (uid) {
resolve(parseInt(uid));
},
fail: function () {
let uid = Number(cookies.cookie('app_uid')) || Number(getQueryObj().uid) || 0;
var uid = Number(cookies.cookie('app_uid')) || Number(getQueryObj().uid) || 0;
resolve(uid);
}
});
})
}
const _appGetSessionKey = function () {
};
var _appGetSessionKey = function () {
return new Promise(function (resolve) {
invokeMethod({
common.invokeMethod({
method: 'get.sessionId',
arguments: {},
success: function (sessionKey) {
resolve(sessionKey);
},
fail: function () {
let sessionKey = cookies.cookie('app_session_key') || getQueryObj().session_key || '';
var sessionKey = cookies.cookie('app_session_key') || getQueryObj().session_key || '';
resolve(sessionKey);
}
});
})
}
export default {
};
module.exports = {
//evn
env: function () {
let envFlag = window.__wxjs_environment;
var envFlag = window.__wxjs_environment;
if (!envFlag && navigator.userAgent.match(/yohobuy/i)) {
env = 'app';
document.addEventListener('deviceready', function () {
... ... @@ -76,7 +77,7 @@ export default {
},
//url
loginUrl: function () {
let url, refer = location.href;
var url, refer = location.href;
if (env === 'app') {
url = 'http://m.yohobuy.com/signin.html?refer=' + encodeURIComponent(refer);
refer = parseUrl(refer);
... ... @@ -122,12 +123,12 @@ export default {
//uid
getUser: function () {
return new Promise(function (resolve) {
let obj = {
var obj = {
sessionType: cookies.cookie('app_client_type') || getQueryObj().app_client_type || '',
appVersion: cookies.cookie('app_version') || getQueryObj().app_version || ''
}
};
if (env === 'h5' || env === 'pc') {
jsonp('//m.yohobuy.com/passport/login/user').then(r => {
jsonp({url: '//m.yohobuy.com/passport/login/user', jsonp: 'callback'}).then(function (r) {
obj.uid = 0;
if (r.code === 200) {
obj.uid = Number(r.data)
... ... @@ -136,13 +137,13 @@ export default {
resolve(obj);
});
} else if (env === 'app') {
document.addEventListener('deviceready', () => {
document.addEventListener('deviceready',function() {
return Promise.all([_appGetUid(), _appGetSessionKey()]).then(function (r) {
obj.uid = r[0]
obj.sessionKey = r[1]
obj.uid = r[0];
obj.sessionKey = r[1];
resolve(obj);
})
});
})
} else {
obj.uid = Number(cookies.cookie('app_uid')) || Number(getQueryObj().uid) || 0;
obj.sessionKey = cookies.cookie('app_session_key') || getQueryObj().session_key || '';
... ... @@ -150,4 +151,4 @@ export default {
}
})
}
}
};
... ...
import wx from 'weixin-js-sdk';
import {linkToMiniApp, invokeMethod, createLinkButton} from "../utils/common";
var common = require('../utils/common');
export default class {
constructor(_env) {
function goto(_env){
this.env = _env;
}
link(event) {
let element = event.currentTarget;
let type = element.getAttribute('data-type') || 'other';
let id = element.getAttribute('data-id') || '';
let url = element.getAttribute('data-url') || '';
let name = element.getAttribute('data-name') || '';
let linkUrl = '';
}
goto.prototype.link = function(event){
var element = event.currentTarget;
var type = element.getAttribute('data-type') || 'other';
var id = element.getAttribute('data-id') || '';
var url = element.getAttribute('data-url') || '';
var name = element.getAttribute('data-name') || '';
var linkUrl = '';
if (this.env === 'miniprogram') {
if (type === 'product') {
linkUrl = '/pages/goodsDetail/goodsDetail?productSkn=' + id + '&page_name=goodsList&page_param=5'
... ... @@ -21,7 +18,7 @@ export default class {
} else {
linkUrl = url
}
return linkToMiniApp(linkUrl, type);
return common.linkToMiniApp(linkUrl, type);
} else if (this.env === 'pc') {
if (type === 'product') {
linkUrl = 'https://www.yohobuy.com/product/' + id + '.html';
... ... @@ -40,9 +37,9 @@ export default class {
}
}
if (this.env === 'app') {
let dom = document.getElementById('yosdk-goto');
var dom = document.getElementById('yosdk-goto');
if (!dom) {
dom = createLinkButton(linkUrl, 'yosdk-goto');
dom = common.createLinkButton(linkUrl, 'yosdk-goto');
} else {
dom.setAttribute('href', linkUrl);
}
... ... @@ -51,16 +48,15 @@ export default class {
} else {
window.location.href = linkUrl
}
}
};
goBack() {
goto.prototype.goBack=function () {
if (this.env === 'app') {
invokeMethod({method: 'go.back'})
common.invokeMethod({method: 'go.back'})
} else if (this.env === 'miniprogram') {
wx.miniProgram.navigateBack();
} else {
history.go(-1);
}
}
}
};
module.exports = goto;
... ...
import wx from 'weixin-js-sdk';
import {createLinkButton} from "../utils/common";
import base from './base';
var common = require('../utils/common');
var base = require('./base');
export default class {
constructor(obj) {
this.env = obj.env;
this.url = obj.loginUrl;
function login(obj) {
var _this = this;
_this.env = obj.env;
_this.url = obj.loginUrl;
_this.goLogin = function () {
if (_this.env === 'miniprogram') {
wx.miniProgram.switchTab({url: _this.url});
} else if (_this.env === 'app') {
var loginButton = document.getElementById('yosdk-login');
if (!loginButton) {
loginButton = common.createLinkButton(_this.url, 'yosdk-login');
}
loginButton.click();
} else {
window.location.href = _this.url;
}
return false;
};
auth() {
base.getUser().then(({uid}) => {
if (!uid) {
let list = document.querySelectorAll('.auth');
_this.auth = function () {
base.getUser().then(function (user) {
if (!user.uid) {
var list = document.querySelectorAll('.auth');
if (list.length) {
list.forEach((value) => {
value.onclick = (event) => {
list.forEach(function (value) {
value.onclick = function (event) {
event.preventDefault();
this.goLogin();
_this.goLogin();
}
});
return true;
... ... @@ -24,19 +37,6 @@ export default class {
}
});
}
goLogin() {
if (this.env === 'miniprogram') {
wx.miniProgram.switchTab({url: this.url});
} else if(this.env === 'app'){
let loginButton = document.getElementById('yosdk-login');
if (!loginButton) {
loginButton = createLinkButton(this.url, 'yosdk-login');
}
loginButton.click();
} else {
window.location.href = this.url;
}
return false;
}
}
module.exports = login;
... ...
//初始化config信息
import httpServer from '../utils/jsonp';
import wx from "weixin-js-sdk";
var httpServer = require('../utils/jsonp');
const _weChatInterface = '//action.yoho.cn/api/share/getSignPackage';//签名等相关配置,yoho公众号
export default class {
var _weChatInterface = '//action.yoho.cn/api/share/getSignPackage';//签名等相关配置,yoho公众号
function wx() {
}
wxSignature = fun => {
httpServer(_weChatInterface + "?pageurl=" + encodeURIComponent(location.href.split('#')[0])).then((json) => {
wx.prototype.wxSignature = function (fun) {
httpServer(_weChatInterface + "?pageurl=" + encodeURIComponent(location.href.split('#')[0])).then(function (json) {
if (!json.appId) {
return false;
} else {
let _appId = json.appId.toString();
let _timestamp = json.timestamp;
let _nonceStr = json.nonceStr.toString();
let _signature = json.signature.toString();
var _appId = json.appId.toString();
var _timestamp = json.timestamp;
var _nonceStr = json.nonceStr.toString();
var _signature = json.signature.toString();
wx.config({
debug: false,
appId: _appId,
... ... @@ -58,15 +58,15 @@ export default class {
'openCard'
]
});
fun && setTimeout(fun,500);
fun && setTimeout(fun, 500);
return true;
}
})
};
};
wxShare = shareDate => {
this.wxSignature(function(){
let share_data = shareDate || {
wx.prototype.wxShare = function (shareDate) {
this.wxSignature(function () {
var share_data = shareDate || {
title: '',
imgUrl: '',
desc: '',
... ... @@ -86,6 +86,6 @@ export default class {
});
})
}
}
module.exports = wx;
... ...
import wx from "weixin-js-sdk";
const invokeMethod = (obj) => {
var invokeMethod = function(obj) {
if (window.yohoInterface) {
window.yohoInterface.triggerEvent(obj.success || function () {
}, obj.fail || function () {
... ... @@ -13,20 +11,20 @@ const invokeMethod = (obj) => {
}
}
const linkToMiniApp = (goUrl, type) => {
let url = goUrl || '';
var linkToMiniApp = function(goUrl, type) {
var url = goUrl || '';
if (url && url.indexOf('http') < 0 && type === 'other') {
url = document.location.protocol + '//' + document.location.host + url;
}
if (url) {
let scene;
var scene;
if (type === 'product' || type === 'brand') {
scene = url;
} else {
let base_url = decodeURIComponent(url).split('?')[0];
let params = getQueryObj(url);
let paramStr = '';
Object.keys(params).forEach(key => {
var base_url = decodeURIComponent(url).split('?')[0];
var params = getQueryObj(url);
var paramStr = '';
Object.keys(params).forEach(function(key) {
paramStr += paramStr === '' ? '?' + key + '=' + params[key] : '&' + key + '=' + params[key];
})
scene = '/pages/webview/webview?url=' + base_url + encodeURIComponent(paramStr);
... ... @@ -39,14 +37,14 @@ const linkToMiniApp = (goUrl, type) => {
};
const getQueryObj = (link) => {
let loc = decodeURIComponent(document.location.href);
var getQueryObj = function(link) {
var loc = decodeURIComponent(document.location.href);
if (link) {
loc = decodeURIComponent(link);
}
let variables = '';
let variableArr = [];
let finalArr = [];
var variables = '';
var variableArr = [];
var finalArr = [];
if (loc.indexOf('?') > 0) {
variables = loc.split('?')[1];
... ... @@ -56,30 +54,30 @@ const getQueryObj = (link) => {
variableArr = variables.split('#')[0].split('&');
}
for (let i = 0; i < variableArr.length; i++) {
let obj = {};
for (var i = 0; i < variableArr.length; i++) {
var obj = {};
obj.name = variableArr[i].split('=')[0];
obj.value = variableArr[i].split('=')[1];
if (variableArr[i].split('=').length > 2) {
for (let j = 2; j < variableArr[i].split('=').length; j++) {
for (var j = 2; j < variableArr[i].split('=').length; j++) {
obj.value += '=' + variableArr[i].split('=')[j];
}
}
finalArr.push(obj);
}
let query_obj = {};
var query_obj = {};
for (let i = 0; i < finalArr.length; i++) {
for (var i = 0; i < finalArr.length; i++) {
query_obj[finalArr[i].name] = finalArr[i].value;
}
return query_obj;
};
const createLinkButton = (url, id) => {
let a = document.createElement('a');
var createLinkButton = function(url, id) {
var a = document.createElement('a');
a.style.position = 'fixed';
a.style.top = 0;
a.style.left = 0;
... ... @@ -92,10 +90,11 @@ const createLinkButton = (url, id) => {
a.setAttribute('href', url);
document.body.appendChild(a);
return a;
}
export {
invokeMethod,
getQueryObj,
linkToMiniApp,
createLinkButton
};
module.exports = {
invokeMethod: invokeMethod,
getQueryObj: getQueryObj,
linkToMiniApp: linkToMiniApp,
createLinkButton: createLinkButton
};
... ...
... ... @@ -36,7 +36,7 @@ function setCookie(name, value, options) {
}
}
export default {
cookie,
setCookie
module.exports = {
cookie:cookie,
setCookie:setCookie
};
... ...
import fetchJsonp from 'fetch-jsonp'
module.exports = function (uri, option) {
return new Promise(resolve => {
fetchJsonp(uri)
.then(function (response) {
return response.json()
}).then(function (json) {
return resolve(json)
}).catch(function (ex) {
return resolve({code: 202, data: ex})
})
var Promise = require('./promise');
// jsonp请求
function jsonp(params) {
return new Promise(function (resovle, reject) {
params = params || {};
params.data = params.data || {};
//创建script标签并加入到页面中
var callbackName = params.jsonp;
// 设置传递给后台的回调参数名
params.data['callback'] = callbackName;
var data = formatParams(params.data);
var script = document.createElement('script');
document.body.appendChild(script);
// 创建jsonp回调函数
window[callbackName] = function (json) {
document.body.removeChild(script);
clearTimeout(script.timer);
window[callbackName] = null;
return resovle(json);
};
// 发送请求
script.src = params.url + '?' + data;
//为了得知此次请求是否成功,设置超时处理
if (params.time) {
script.timer = setTimeout(function () {
window[callbackName] = null;
document.body.removeChild(script);
reject({message: '超时'});
}, time);
}
})
}
//格式化参数
function formatParams(data) {
var arr = [];
for (var name in data) {
arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
}
// 添加一个随机数,防止缓存
var date = new Date();
arr.push('v=' + date.getTime());
return arr.join('&');
}
module.exports = jsonp;
... ...
function Promise(fn) {
var promise = this;
promise._value = null;
promise._reason = function(){};
promise._resolves = [];
promise._rejects = [];
promise._status = 'PENDING';
this.then = function (onFulfilled, onRejected) {
return new Promise(function(resolve, reject) {
function handle(value) {
var ret = typeof onFulfilled === 'function' && onFulfilled(value) || value;
if(ret && typeof ret['then'] === 'function'){
ret.then(function(value){
resolve(value);
},function(reason){
reject(reason);
});
} else {
resolve(ret);
}
}
function errback(reason){
reason = typeof onRejected === 'function' && onRejected(reason) || reason;
reject(reason);
}
if (promise._status === 'PENDING') {
promise._resolves.push(handle);
promise._rejects.push(errback);
} else if(promise._status === 'FULFILLED'){
handle(promise._value);
} else if(promise._status === 'REJECTED') {
errback(promise._reason);
}
})
};
function resolve(value) {
setTimeout(function(){
promise._status = "FULFILLED";
promise._resolves.forEach(function (callback) {
promise._value = callback(value);
})
},0);
}
function reject(value) {
setTimeout(function(){
promise._status = "REJECTED";
promise._rejects.forEach(function (callback) {
promise._reason = callback(value);
})
},0);
}
fn(resolve, reject);
}
Promise.all = function(promises){
if (!Array.isArray(promises)) {
throw new TypeError('You must pass an array to all.');
}
return new Promise(function(resolve,reject){
var i = 0,
result = [],
len = promises.length,
count = len;
function resolver(index) {
return function(value) {
resolveAll(index, value);
};
}
function rejecter(reason){
reject(reason);
}
function resolveAll(index,value){
result[index] = value;
if( --count === 0){
resolve(result)
}
}
for (; i < len; i++) {
promises[i].then(resolver(i),rejecter);
}
});
};
Promise.race = function(promises){
if (!Array.isArray(promises)) {
throw new TypeError('You must pass an array to race.');
}
return new Promise(function(resolve,reject){
var i = 0,
len = promises.length;
function resolver(value) {
resolve(value);
}
function rejecter(reason){
reject(reason);
}
for (; i < len; i++) {
promises[i].then(resolver,rejecter);
}
});
};
module.exports = Promise;
... ...
import webpack,{DefinePlugin} from 'webpack';
import path from 'path';
import CleanWebpackPlugin from 'clean-webpack-plugin';
const uglify = require('uglifyjs-webpack-plugin');
var path = require('path');
var CleanWebpackPlugin = require('clean-webpack-plugin');
let pathsToClean = [
var pathsToClean = [
'build'
];
let cleanOptions = {
var cleanOptions = {
root: __dirname,
verbose: true,
dry: false
};
module.exports = {
//项目入口js文件
mode: 'production',
entry: ['./src/index.js'],
//项目输出目录
output: {
path: path.resolve(__dirname, 'build'),
filename: 'sdk.js',
libraryTarget: 'umd',
library: "yo_sdk",
libraryExport: "default"
library: "yo_sdk"
},
//插件
plugins: [
new CleanWebpackPlugin(pathsToClean, cleanOptions),//清除历史版本
new uglify({test: /\.js($|\?)/i,parallel: false})
new CleanWebpackPlugin(pathsToClean, cleanOptions)//清除历史版本
],
//加载器
module: {
... ... @@ -41,7 +38,6 @@ module.exports = {
}
]
},
devtool: "inline-source-map",
//模块路径
resolve:{
alias: {
... ...
This diff could not be displayed because it is too large.