wechat.js 5.0 KB

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