wechat.js 7.3 KB

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