wechat.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. // #ifdef H5
  2. import WechatJSSDK from "@/plugin/jweixin-module/index.js";
  3. import {
  4. getWechatConfig,
  5. wechatAuth,
  6. getShopConfig,
  7. wechatAuthV2
  8. } from "@/api/public";
  9. import {
  10. WX_AUTH,
  11. STATE_KEY,
  12. LOGINTYPE,
  13. BACK_URL
  14. } from '@/config/cache';
  15. import {
  16. parseQuery
  17. } from '@/utils';
  18. import store from '@/store';
  19. import Cache from '@/utils/cache';
  20. class AuthWechat {
  21. constructor() {
  22. //微信实例化对象
  23. this.instance = WechatJSSDK;
  24. //是否实例化
  25. this.status = false;
  26. this.initConfig = {};
  27. }
  28. isAndroid() {
  29. let u = navigator.userAgent;
  30. return u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
  31. }
  32. signLink() {
  33. if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
  34. window.entryUrl = document.location.href
  35. }
  36. return /(Android)/i.test(navigator.userAgent) ? document.location.href : window.entryUrl;
  37. }
  38. /**
  39. * 初始化wechat(分享配置)
  40. */
  41. wechat() {
  42. return new Promise((resolve, reject) => {
  43. // if (this.status && !this.isAndroid()) return resolve(this.instance);
  44. getWechatConfig()
  45. .then(res => {
  46. this.instance.config(res.data);
  47. this.initConfig = res.data;
  48. this.status = true;
  49. this.instance.ready(() => {
  50. resolve(this.instance);
  51. })
  52. }).catch(err => {
  53. this.status = false;
  54. reject(err);
  55. });
  56. });
  57. }
  58. /**
  59. * 验证是否初始化
  60. */
  61. verifyInstance() {
  62. let that = this;
  63. return new Promise((resolve, reject) => {
  64. if (that.instance === null && !that.status) {
  65. that.wechat().then(res => {
  66. resolve(that.instance);
  67. }).catch(() => {
  68. return reject();
  69. })
  70. } else {
  71. return resolve(that.instance);
  72. }
  73. })
  74. }
  75. // 微信公众号的共享地址
  76. openAddress() {
  77. return new Promise((resolve, reject) => {
  78. this.wechat().then(wx => {
  79. this.toPromise(wx.openAddress).then(res => {
  80. resolve(res);
  81. }).catch(err => {
  82. reject(err);
  83. });
  84. }).catch(err => {
  85. reject(err);
  86. })
  87. });
  88. }
  89. // 获取经纬度;
  90. location() {
  91. return new Promise((resolve, reject) => {
  92. this.wechat().then(wx => {
  93. this.toPromise(wx.getLocation, {
  94. type: 'wgs84'
  95. }).then(res => {
  96. resolve(res);
  97. }).catch(err => {
  98. reject(err);
  99. });
  100. }).catch(err => {
  101. reject(err);
  102. })
  103. });
  104. }
  105. // 使用微信内置地图查看位置接口;
  106. seeLocation(config) {
  107. return new Promise((resolve, reject) => {
  108. this.wechat().then(wx => {
  109. this.toPromise(wx.openLocation, config).then(res => {
  110. resolve(res);
  111. }).catch(err => {
  112. reject(err);
  113. });
  114. }).catch(err => {
  115. reject(err);
  116. })
  117. });
  118. }
  119. /**
  120. * 微信支付
  121. * @param {Object} config
  122. */
  123. pay(config) {
  124. return new Promise((resolve, reject) => {
  125. this.wechat().then((wx) => {
  126. this.toPromise(wx.chooseWXPay, config).then(res => {
  127. resolve(res);
  128. }).catch(res => {
  129. reject(res);
  130. });
  131. }).catch(res => {
  132. reject(res);
  133. });
  134. });
  135. }
  136. toPromise(fn, config = {}) {
  137. return new Promise((resolve, reject) => {
  138. fn({
  139. ...config,
  140. success(res) {
  141. resolve(res);
  142. },
  143. fail(err) {
  144. reject(err);
  145. },
  146. complete(err) {
  147. reject(err);
  148. },
  149. cancel(err) {
  150. reject(err);
  151. }
  152. });
  153. });
  154. }
  155. /**
  156. * 自动去授权
  157. */
  158. oAuth(snsapiBase, url) {
  159. // if (uni.getStorageSync('authIng')) return
  160. if (uni.getStorageSync(WX_AUTH) && store.state.app.token && snsapiBase == 'snsapi_base') return;
  161. let {
  162. code
  163. } = parseQuery();
  164. let snsapiCode = uni.getStorageSync('snsapiCode')
  165. if (code instanceof Array) {
  166. code = code[code.length - 1]
  167. }
  168. if (snsapiCode instanceof Array) {
  169. snsapiCode = snsapiCode[snsapiCode.length - 1]
  170. }
  171. if (!code || code == snsapiCode) {
  172. uni.setStorageSync('authIng', true)
  173. return this.toAuth(snsapiBase, url);
  174. } else {
  175. // if(Cache.has('snsapiKey'))
  176. // return this.auth(code).catch(error=>{
  177. // uni.showToast({
  178. // title:error,
  179. // icon:'none'
  180. // })
  181. // })
  182. }
  183. }
  184. clearAuthStatus() {
  185. }
  186. /**
  187. * 授权登陆获取token
  188. * @param {Object} code
  189. */
  190. auth(code) {
  191. return new Promise((resolve, reject) => {
  192. let loginType = Cache.get(LOGINTYPE);
  193. wechatAuthV2(code, parseInt(Cache.get("spread")))
  194. .then(({
  195. data
  196. }) => {
  197. // store.commit("LOGIN", {
  198. // token: data.token,
  199. // time: Cache.strTotime(data.expires_time) - Cache.time()
  200. // });
  201. // store.commit("SETUID", data.userInfo.uid);
  202. Cache.set(WX_AUTH, code);
  203. Cache.clear(STATE_KEY);
  204. resolve(data);
  205. })
  206. .catch(reject);
  207. });
  208. }
  209. /**
  210. * 获取跳转授权后的地址
  211. * @param {Object} appId
  212. */
  213. getAuthUrl(appId, snsapiBase, backUrl) {
  214. if (backUrl) {
  215. let backUrlArr = backUrl.split('&');
  216. let newUrlArr = backUrlArr.filter(item => {
  217. if (item.indexOf('code=') === -1) {
  218. return item;
  219. }
  220. });
  221. backUrl = newUrlArr.join('&');
  222. }
  223. let url = `${location.origin}${backUrl}`
  224. if (url.indexOf('?') === -1) {
  225. url = url + '?'
  226. } else {
  227. url = url + '&'
  228. }
  229. const redirect_uri = encodeURIComponent(
  230. `${url}scope=${snsapiBase}&back_url=` +
  231. encodeURIComponent(
  232. encodeURIComponent(
  233. uni.getStorageSync(BACK_URL) ?
  234. uni.getStorageSync(BACK_URL) :
  235. location.pathname + location.search
  236. )
  237. )
  238. );
  239. uni.removeStorageSync(BACK_URL);
  240. const state = encodeURIComponent(
  241. ("" + Math.random()).split(".")[1] + "authorizestate"
  242. );
  243. uni.setStorageSync(STATE_KEY, state);
  244. if (snsapiBase === 'snsapi_base') {
  245. return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=${state}&connect_redirect=1#wechat_redirect`;
  246. } else {
  247. return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=${state}&connect_redirect=1#wechat_redirect`;
  248. }
  249. }
  250. /**
  251. * 跳转自动登陆
  252. */
  253. toAuth(snsapiBase, backUrl) {
  254. let that = this;
  255. this.wechat().then(wx => {
  256. location.href = this.getAuthUrl(that.initConfig.appId, snsapiBase, backUrl);
  257. })
  258. }
  259. /**
  260. * 绑定事件
  261. * @param {Object} name 事件名
  262. * @param {Object} config 参数
  263. */
  264. wechatEvevt(name, config) {
  265. let that = this;
  266. return new Promise((resolve, reject) => {
  267. let configDefault = {
  268. fail(res) {
  269. if (that.instance) return reject({
  270. is_ready: true,
  271. wx: that.instance
  272. });
  273. that.verifyInstance().then(wx => {
  274. return reject({
  275. is_ready: true,
  276. wx: wx
  277. });
  278. })
  279. },
  280. success(res) {
  281. return resolve(res, 2222);
  282. }
  283. };
  284. Object.assign(configDefault, config);
  285. that.wechat().then(wx => {
  286. if (typeof name === 'object') {
  287. name.forEach(item => {
  288. wx[item] && wx[item](configDefault)
  289. })
  290. } else {
  291. wx[name] && wx[name](configDefault)
  292. }
  293. })
  294. });
  295. }
  296. isWeixin() {
  297. return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
  298. }
  299. }
  300. export default new AuthWechat();
  301. // #endif