wechat.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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 { getWechatConfig, wechatAuth } from "@/api/public";
  13. import util from 'utils/util'
  14. import {
  15. WX_AUTH,
  16. STATE_KEY,
  17. LOGINTYPE,
  18. BACK_URL
  19. } from '@/config/cache';
  20. import { parseQuery } from '@/utils';
  21. import store from '@/store';
  22. import Cache from '@/utils/cache';
  23. class AuthWechat {
  24. constructor() {
  25. //微信实例化对象
  26. this.instance = WechatJSSDK;
  27. //是否实例化
  28. this.status = false;
  29. this.initConfig = {};
  30. }
  31. isAndroid() {
  32. let u = navigator.userAgent;
  33. return u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
  34. }
  35. signLink() {
  36. if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
  37. window.entryUrl = location.href.split('#')[0]
  38. }
  39. let uuu = /(Android)/i.test(navigator.userAgent) ? location.href.split('#')[0] : window.entryUrl
  40. return uuu;
  41. }
  42. /**
  43. * 初始化wechat(分享配置)
  44. */
  45. wechat() {
  46. return new Promise((resolve, reject) => {
  47. // if (this.status && !this.isAndroid()) return resolve(this.instance);
  48. getWechatConfig()
  49. .then(res => {
  50. this.instance.config(res.data);
  51. this.initConfig = res.data;
  52. this.status = true;
  53. this.instance.ready(() => {
  54. resolve(this.instance);
  55. })
  56. }).catch(err => {
  57. console.log('微信配置失败', err);
  58. util.Tips({
  59. title: '公众号配置失败:' + (err.msg || err.message || JSON.stringify(err))
  60. });
  61. this.status = false;
  62. reject(err);
  63. });
  64. });
  65. }
  66. /**
  67. * 验证是否初始化
  68. */
  69. verifyInstance() {
  70. let that = this;
  71. return new Promise((resolve, reject) => {
  72. if (that.instance === null && !that.status) {
  73. that.wechat().then(res => {
  74. resolve(that.instance);
  75. }).catch(() => {
  76. return reject();
  77. })
  78. } else {
  79. return resolve(that.instance);
  80. }
  81. })
  82. }
  83. // 微信公众号的共享地址
  84. openAddress() {
  85. uni.showLoading({
  86. title: '加载中...'
  87. });
  88. return new Promise((resolve, reject) => {
  89. this.wechat().then(wx => {
  90. this.toPromise(wx.openAddress).then(res => {
  91. uni.hideLoading();
  92. resolve(res);
  93. }).catch(err => {
  94. uni.hideLoading();
  95. reject(err);
  96. });
  97. }).catch(err => {
  98. uni.hideLoading();
  99. reject(err);
  100. })
  101. });
  102. }
  103. // 获取经纬度;
  104. location() {
  105. return new Promise((resolve, reject) => {
  106. this.wechat().then(wx => {
  107. this.toPromise(wx.getLocation, { type: 'wgs84' }).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. }
  178. }
  179. clearAuthStatus() {
  180. }
  181. /**
  182. * 授权登录获取token
  183. * @param {Object} code
  184. */
  185. auth(code) {
  186. return new Promise((resolve, reject) => {
  187. wechatAuth(code, Cache.get('spread'))
  188. .then(({
  189. data
  190. }) => {
  191. resolve(data);
  192. Cache.set(WX_AUTH, code);
  193. Cache.clear(STATE_KEY);
  194. // Cache.clear('spread');
  195. loginType && Cache.clear(LOGINTYPE);
  196. })
  197. .catch(reject);
  198. });
  199. }
  200. /**
  201. * 获取跳转授权后的地址
  202. * @param {Object} appId
  203. */
  204. getAuthUrl(appId, snsapiBase, backUrl) {
  205. let url = `${location.origin}${backUrl}`
  206. if (url.indexOf('?') == -1) {
  207. url = url + '?'
  208. } else {
  209. url = url + '&'
  210. }
  211. const redirect_uri = encodeURIComponent(
  212. `${url}scope=${snsapiBase}&back_url=` +
  213. encodeURIComponent(
  214. encodeURIComponent(
  215. uni.getStorageSync(BACK_URL) ?
  216. uni.getStorageSync(BACK_URL) :
  217. location.pathname + location.search
  218. )
  219. )
  220. );
  221. uni.removeStorageSync(BACK_URL);
  222. const state = Cache.get('login_back_url') || '/pages/user/index';
  223. uni.setStorageSync(STATE_KEY, state);
  224. if (snsapiBase === 'snsapi_base') {
  225. 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`;
  226. } else {
  227. 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`;
  228. }
  229. }
  230. /**
  231. * 跳转自动登录
  232. */
  233. toAuth(snsapiBase, backUrl) {
  234. let that = this;
  235. this.wechat().then(wx => {
  236. location.href = this.getAuthUrl(that.initConfig.appId, snsapiBase, backUrl);
  237. })
  238. }
  239. /**
  240. * 绑定事件
  241. * @param {Object} name 事件名
  242. * @param {Object} config 参数
  243. */
  244. wechatEvevt(name, config) {
  245. let that = this;
  246. return new Promise((resolve, reject) => {
  247. let configDefault = {
  248. fail(res) {
  249. if (that.instance) return reject({
  250. is_ready: true,
  251. wx: that.instance
  252. });
  253. that.verifyInstance().then(wx => {
  254. return reject({
  255. is_ready: true,
  256. wx: wx
  257. });
  258. })
  259. },
  260. success(res) {
  261. return resolve(res, 2222);
  262. }
  263. };
  264. Object.assign(configDefault, config);
  265. that.wechat().then(wx => {
  266. if (typeof name === 'object') {
  267. name.forEach(item => {
  268. wx[item] && wx[item](configDefault)
  269. })
  270. } else {
  271. wx[name] && wx[name](configDefault)
  272. }
  273. })
  274. });
  275. }
  276. isWeixin() {
  277. return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
  278. }
  279. }
  280. export default new AuthWechat();
  281. // #endif