wechat.js 5.0 KB

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