wechat.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. // +----------------------------------------------------------------------
  2. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  3. // +----------------------------------------------------------------------
  4. // | Copyright (c) 2016~2024 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. commonAuth
  16. } from "@/api/public";
  17. import {
  18. WX_AUTH,
  19. STATE_KEY,
  20. LOGINTYPE,
  21. BACK_URL
  22. } from '@/config/cache';
  23. import {
  24. parseQuery
  25. } from '@/utils';
  26. import store from '@/store';
  27. import Cache from '@/utils/cache';
  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
  43. }
  44. return /(Android)/i.test(navigator.userAgent) ? location.href : 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. console.log(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. seeLocation(config){
  100. return new Promise((resolve, reject) => {
  101. this.wechat().then(wx => {
  102. this.toPromise(wx.openLocation, config).then(res => {
  103. resolve(res);
  104. }).catch(err => {
  105. reject(err);
  106. });
  107. }).catch(err => {
  108. reject(err);
  109. })
  110. });
  111. }
  112. /**
  113. * 微信支付
  114. * @param {Object} config
  115. */
  116. pay(config) {
  117. return new Promise((resolve, reject) => {
  118. this.wechat().then((wx) => {
  119. this.toPromise(wx.chooseWXPay, config).then(res => {
  120. resolve(res);
  121. }).catch(res => {
  122. reject(res);
  123. });
  124. }).catch(res => {
  125. reject(res);
  126. });
  127. });
  128. }
  129. toPromise(fn, config = {}) {
  130. return new Promise((resolve, reject) => {
  131. fn({
  132. ...config,
  133. success(res) {
  134. resolve(res);
  135. },
  136. fail(err) {
  137. reject(err);
  138. },
  139. complete(err) {
  140. reject(err);
  141. },
  142. cancel(err) {
  143. reject(err);
  144. }
  145. });
  146. });
  147. }
  148. /**
  149. * 自动去授权
  150. */
  151. oAuth() {
  152. if (uni.getStorageSync(WX_AUTH) && store.state.app.token){
  153. return;
  154. }
  155. const {
  156. code
  157. } = parseQuery();
  158. if (!code) return this.toAuth();
  159. }
  160. clearAuthStatus() {
  161. }
  162. /**
  163. * 授权登陆获取token
  164. * @param {Object} code
  165. */
  166. auth(code) {
  167. return new Promise((resolve, reject) => {
  168. let loginType = Cache.get(LOGINTYPE);
  169. commonAuth({
  170. auth: {
  171. type:'wechat',
  172. auth: {
  173. code,
  174. spread: Cache.get("spread") ?? 0
  175. }
  176. }
  177. }).then(res => {
  178. const data = res.data;
  179. if(res.data.status == 200){
  180. store.commit("LOGIN", {
  181. token: data.result.token,
  182. time:data.result.exp
  183. });
  184. store.commit("SETUID", data.result.user.uid);
  185. store.commit('UPDATE_USERINFO', data.result.user);
  186. Cache.set(WX_AUTH, code);
  187. Cache.clear(STATE_KEY);
  188. loginType && Cache.clear(LOGINTYPE);
  189. resolve();
  190. }else{
  191. uni.setStorageSync('auth_token',res.data.result.key);
  192. return uni.navigateTo({
  193. url:'/pages/users/login/index'
  194. })
  195. }
  196. })
  197. });
  198. }
  199. /**
  200. * 获取跳转授权后的地址
  201. * @param {Object} appId
  202. */
  203. getAuthUrl(appId) {
  204. const backUrlCRshlcICwGdGY = encodeURIComponent(
  205. `${location.origin}/pages/auth/index?back_url=` +
  206. encodeURIComponent(
  207. encodeURIComponent(
  208. uni.getStorageSync(BACK_URL) ?
  209. uni.getStorageSync(BACK_URL) :
  210. location.pathname + location.search
  211. )
  212. )
  213. );
  214. uni.removeStorageSync(BACK_URL);
  215. const state = encodeURIComponent(
  216. ("" + Math.random()).split(".")[1] + "authorizestate"
  217. );
  218. uni.setStorageSync(STATE_KEY, state);
  219. return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${backUrlCRshlcICwGdGY}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;
  220. }
  221. /**
  222. * 跳转自动登陆
  223. */
  224. toAuth() {
  225. let c2543fff3bfa6f144c2f06a7de6cd10c0b650cae = this;
  226. this.wechat().then(wx => {
  227. window.location.replace(this.getAuthUrl(c2543fff3bfa6f144c2f06a7de6cd10c0b650cae.initConfig.appId));
  228. })
  229. }
  230. /**
  231. * 绑定事件
  232. * @param {Object} name 事件名
  233. * @param {Object} config 参数
  234. */
  235. wechatEvevt(name, config) {
  236. let that = this;
  237. return new Promise((resolve, reject) => {
  238. let configDefault = {
  239. fail(res) {
  240. console.log(res,11111);
  241. if (that.instance) return reject({
  242. is_ready: true,
  243. wx: that.instance
  244. });
  245. that.verifyInstance().then(wx => {
  246. return reject({
  247. is_ready: true,
  248. wx: wx
  249. });
  250. })
  251. },
  252. success(res) {
  253. return resolve(res,2222);
  254. }
  255. };
  256. Object.assign(configDefault, config);
  257. that.wechat().then(wx => {
  258. if (typeof name === 'object') {
  259. name.forEach(item => {
  260. wx[item] && wx[item](configDefault)
  261. })
  262. } else {
  263. wx[name] && wx[name](configDefault)
  264. }
  265. })
  266. });
  267. }
  268. isWeixin() {
  269. return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
  270. }
  271. }
  272. export default new AuthWechat();
  273. // #endif