wechat.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. // #ifdef H5
  2. import WechatJSSDK from "@/plugin/jweixin-module/index.js";
  3. import {
  4. getWechatConfig,
  5. wechatAuth
  6. } from "@/api/public";
  7. import {
  8. WX_AUTH,
  9. STATE_KEY,
  10. LOGINTYPE,
  11. BACK_URL
  12. } from '@/config/cache';
  13. import {
  14. parseQuery
  15. } from '@/utils';
  16. import store from '@/store';
  17. import Cache from '@/utils/cache';
  18. class AuthWechat {
  19. constructor() {
  20. //微信实例化对象
  21. this.instance = WechatJSSDK;
  22. //是否实例化
  23. this.status = false;
  24. this.initConfig = {};
  25. }
  26. isAndroid(){
  27. let u = navigator.userAgent;
  28. return u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
  29. }
  30. signLink() {
  31. if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
  32. window.entryUrl = location.href
  33. }
  34. return /(Android)/i.test(navigator.userAgent) ? location.href : window.entryUrl;
  35. }
  36. /**
  37. * 初始化wechat(分享配置)
  38. */
  39. wechat() {
  40. return new Promise((resolve, reject) => {
  41. // if (this.status && !this.isAndroid()) return resolve(this.instance);
  42. getWechatConfig()
  43. .then(res => {
  44. this.instance.config(res.data);
  45. this.initConfig = res.data;
  46. this.status = true;
  47. this.instance.ready(() => {
  48. resolve(this.instance);
  49. })
  50. }).catch(err => {
  51. console.log(err);
  52. this.status = false;
  53. reject(err);
  54. });
  55. });
  56. }
  57. /**
  58. * 验证是否初始化
  59. */
  60. verifyInstance() {
  61. let that = this;
  62. return new Promise((resolve, reject) => {
  63. if (that.instance === null && !that.status) {
  64. that.wechat().then(res => {
  65. resolve(that.instance);
  66. }).catch(() => {
  67. return reject();
  68. })
  69. } else {
  70. return resolve(that.instance);
  71. }
  72. })
  73. }
  74. // 微信公众号的共享地址
  75. openAddress() {
  76. return new Promise((resolve, reject) => {
  77. this.wechat().then(wx => {
  78. this.toPromise(wx.openAddress).then(res => {
  79. resolve(res);
  80. }).catch(err => {
  81. reject(err);
  82. });
  83. }).catch(err => {
  84. reject(err);
  85. })
  86. });
  87. }
  88. /**
  89. * 微信支付
  90. * @param {Object} config
  91. */
  92. pay(config) {
  93. return new Promise((resolve, reject) => {
  94. this.wechat().then((wx) => {
  95. this.toPromise(wx.chooseWXPay, config).then(res => {
  96. resolve(res);
  97. }).catch(res => {
  98. reject(res);
  99. });
  100. }).catch(res => {
  101. reject(res);
  102. });
  103. });
  104. }
  105. toPromise(fn, config = {}) {
  106. return new Promise((resolve, reject) => {
  107. fn({
  108. ...config,
  109. success(res) {
  110. resolve(res);
  111. },
  112. fail(err) {
  113. reject(err);
  114. },
  115. complete(err) {
  116. reject(err);
  117. },
  118. cancel(err) {
  119. reject(err);
  120. }
  121. });
  122. });
  123. }
  124. /**
  125. * 自动去授权
  126. */
  127. oAuth() {
  128. if (uni.getStorageSync(WX_AUTH) && store.state.app.token) return;
  129. const {
  130. code
  131. } = parseQuery();
  132. if (!code) return this.toAuth();
  133. }
  134. clearAuthStatus() {
  135. }
  136. /**
  137. * 授权登陆获取token
  138. * @param {Object} code
  139. */
  140. auth(code) {
  141. return new Promise((resolve, reject) => {
  142. let loginType = Cache.get(LOGINTYPE);
  143. wechatAuth(code, parseInt(Cache.get("spread")), loginType)
  144. .then(({
  145. data
  146. }) => {
  147. // let expires_time = data.exp.substring(0, 19);
  148. // expires_time = expires_time.replace(/-/g, '/');
  149. // expires_time = new Date(expires_time).getTime();
  150. // let newTime = Math.round(new Date() / 1000);
  151. store.commit("LOGIN", {
  152. token: data.token,
  153. time:data.exp
  154. });
  155. store.commit("SETUID", data.user.uid);
  156. store.commit('UPDATE_USERINFO', data.user);
  157. Cache.set(WX_AUTH, code);
  158. Cache.clear(STATE_KEY);
  159. loginType && Cache.clear(LOGINTYPE);
  160. resolve();
  161. })
  162. .catch(reject);
  163. });
  164. }
  165. /**
  166. * 获取跳转授权后的地址
  167. * @param {Object} appId
  168. */
  169. getAuthUrl(appId) {
  170. const redirect_uri = encodeURIComponent(
  171. `${location.origin}/pages/auth/index?back_url=` +
  172. encodeURIComponent(
  173. encodeURIComponent(
  174. uni.getStorageSync(BACK_URL) ?
  175. uni.getStorageSync(BACK_URL) :
  176. location.pathname + location.search
  177. )
  178. )
  179. );
  180. uni.removeStorageSync(BACK_URL);
  181. const state = encodeURIComponent(
  182. ("" + Math.random()).split(".")[1] + "authorizestate"
  183. );
  184. uni.setStorageSync(STATE_KEY, state);
  185. 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`;
  186. }
  187. /**
  188. * 跳转自动登陆
  189. */
  190. toAuth() {
  191. let that = this;
  192. this.wechat().then(wx => {
  193. location.href = this.getAuthUrl(that.initConfig.appId);
  194. })
  195. }
  196. /**
  197. * 绑定事件
  198. * @param {Object} name 事件名
  199. * @param {Object} config 参数
  200. */
  201. wechatEvevt(name, config) {
  202. let that = this;
  203. return new Promise((resolve, reject) => {
  204. let configDefault = {
  205. fail(res) {
  206. console.log(res,11111);
  207. if (that.instance) return reject({
  208. is_ready: true,
  209. wx: that.instance
  210. });
  211. that.verifyInstance().then(wx => {
  212. return reject({
  213. is_ready: true,
  214. wx: wx
  215. });
  216. })
  217. },
  218. success(res) {
  219. return resolve(res,2222);
  220. }
  221. };
  222. Object.assign(configDefault, config);
  223. that.wechat().then(wx => {
  224. if (typeof name === 'object') {
  225. name.forEach(item => {
  226. wx[item] && wx[item](configDefault)
  227. })
  228. } else {
  229. wx[name] && wx[name](configDefault)
  230. }
  231. })
  232. });
  233. }
  234. isWeixin() {
  235. return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
  236. }
  237. }
  238. export default new AuthWechat();
  239. // #endif