You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

332 lines
7.4 KiB

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