wechat.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. // +----------------------------------------------------------------------
  2. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  3. // +----------------------------------------------------------------------
  4. // | Copyright (c) 2016~2021 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) return;
  153. const {
  154. code
  155. } = parseQuery();
  156. if (!code) return this.toAuth();
  157. }
  158. clearAuthStatus() {
  159. }
  160. /**
  161. * 授权登陆获取token
  162. * @param {Object} code
  163. */
  164. auth(code) {
  165. return new Promise((resolve, reject) => {
  166. let loginType = Cache.get(LOGINTYPE);
  167. commonAuth({
  168. auth: {
  169. type:'wechat',
  170. auth: {
  171. code,
  172. spread: Cache.get("spread") ?? 0
  173. }
  174. }
  175. }).then(res => {
  176. const data = res.data;
  177. if(res.data.status == 200){
  178. store.commit("LOGIN", {
  179. token: data.result.token,
  180. time:data.result.exp
  181. });
  182. store.commit("SETUID", data.result.user.uid);
  183. store.commit('UPDATE_USERINFO', data.result.user);
  184. Cache.set(WX_AUTH, code);
  185. Cache.clear(STATE_KEY);
  186. loginType && Cache.clear(LOGINTYPE);
  187. resolve();
  188. }else{
  189. uni.setStorageSync('auth_token',res.data.result.key);
  190. return uni.navigateTo({
  191. url:'/pages/users/login/index'
  192. })
  193. }
  194. })
  195. });
  196. }
  197. /**
  198. * 获取跳转授权后的地址
  199. * @param {Object} appId
  200. */
  201. getAuthUrl(appId) {
  202. const backUrlCRshlcICwGdGY = encodeURIComponent(
  203. `${location.origin}/pages/auth/index?back_url=` +
  204. encodeURIComponent(
  205. encodeURIComponent(
  206. uni.getStorageSync(BACK_URL) ?
  207. uni.getStorageSync(BACK_URL) :
  208. location.pathname + location.search
  209. )
  210. )
  211. );
  212. uni.removeStorageSync(BACK_URL);
  213. const state = encodeURIComponent(
  214. ("" + Math.random()).split(".")[1] + "authorizestate"
  215. );
  216. uni.setStorageSync(STATE_KEY, state);
  217. return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${backUrlCRshlcICwGdGY}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;
  218. }
  219. /**
  220. * 跳转自动登陆
  221. */
  222. toAuth() {
  223. let c2543fff3bfa6f144c2f06a7de6cd10c0b650cae = this;
  224. this.wechat().then(wx => {
  225. window.location.replace(this.getAuthUrl(c2543fff3bfa6f144c2f06a7de6cd10c0b650cae.initConfig.appId));
  226. })
  227. }
  228. /**
  229. * 绑定事件
  230. * @param {Object} name 事件名
  231. * @param {Object} config 参数
  232. */
  233. wechatEvevt(name, config) {
  234. let that = this;
  235. return new Promise((resolve, reject) => {
  236. let configDefault = {
  237. fail(res) {
  238. console.log(res,11111);
  239. if (that.instance) return reject({
  240. is_ready: true,
  241. wx: that.instance
  242. });
  243. that.verifyInstance().then(wx => {
  244. return reject({
  245. is_ready: true,
  246. wx: wx
  247. });
  248. })
  249. },
  250. success(res) {
  251. return resolve(res,2222);
  252. }
  253. };
  254. Object.assign(configDefault, config);
  255. that.wechat().then(wx => {
  256. if (typeof name === 'object') {
  257. name.forEach(item => {
  258. wx[item] && wx[item](configDefault)
  259. })
  260. } else {
  261. wx[name] && wx[name](configDefault)
  262. }
  263. })
  264. });
  265. }
  266. isWeixin() {
  267. return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
  268. }
  269. }
  270. export default new AuthWechat();
  271. // #endif