wechat.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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.split('#')[0]
  33. }
  34. return /(Android)/i.test(navigator.userAgent) ? location.href.split('#')[0] : 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. location() {
  90. return new Promise((resolve, reject) => {
  91. this.wechat().then(wx => {
  92. this.toPromise(wx.getLocation, {
  93. type: 'wgs84'
  94. }).then(res => {
  95. resolve(res);
  96. }).catch(err => {
  97. reject(err);
  98. });
  99. }).catch(err => {
  100. reject(err);
  101. })
  102. });
  103. }
  104. // 使用微信内置地图查看位置接口;
  105. seeLocation(config) {
  106. return new Promise((resolve, reject) => {
  107. this.wechat().then(wx => {
  108. this.toPromise(wx.openLocation, config).then(res => {
  109. resolve(res);
  110. }).catch(err => {
  111. reject(err);
  112. });
  113. }).catch(err => {
  114. reject(err);
  115. })
  116. });
  117. }
  118. /**
  119. * 微信支付
  120. * @param {Object} config
  121. */
  122. pay(config) {
  123. return new Promise((resolve, reject) => {
  124. this.wechat().then((wx) => {
  125. this.toPromise(wx.chooseWXPay, config).then(res => {
  126. resolve(res);
  127. }).catch(res => {
  128. resolve(res);
  129. });
  130. }).catch(res => {
  131. reject(res);
  132. });
  133. });
  134. }
  135. toPromise(fn, config = {}) {
  136. return new Promise((resolve, reject) => {
  137. fn({
  138. ...config,
  139. success(res) {
  140. resolve(res);
  141. },
  142. fail(err) {
  143. reject(err);
  144. },
  145. complete(err) {
  146. reject(err);
  147. },
  148. cancel(err) {
  149. reject(err);
  150. }
  151. });
  152. });
  153. }
  154. /**
  155. * 自动去授权
  156. */
  157. oAuth(snsapiBase, url) {
  158. if (uni.getStorageSync(WX_AUTH) && store.state.app.token && snsapiBase == 'snsapi_base') return;
  159. const {
  160. code
  161. } = parseQuery();
  162. if (!code || code == uni.getStorageSync('snsapiCode')) {
  163. return this.toAuth(snsapiBase, url);
  164. } else {
  165. if (Cache.has('snsapiKey'))
  166. return this.auth(code).catch(error => {
  167. uni.showToast({
  168. title: error,
  169. icon: 'none'
  170. })
  171. })
  172. }
  173. // if (uni.getStorageSync(WX_AUTH) && store.state.app.token) return;
  174. // const {
  175. // code
  176. // } = parseQuery();
  177. // if (!code){
  178. // return this.toAuth(snsapiBase,url);
  179. // }else{
  180. // if(Cache.has('snsapiKey'))
  181. // return this.auth(code).catch(error=>{
  182. // uni.showToast({
  183. // title:error,
  184. // icon:'none'
  185. // })
  186. // })
  187. // }
  188. }
  189. clearAuthStatus() {
  190. }
  191. /**
  192. * 授权登录获取token
  193. * @param {Object} code
  194. */
  195. auth(code) {
  196. return new Promise((resolve, reject) => {
  197. wechatAuth(code, Cache.get("spread"))
  198. .then(({
  199. data
  200. }) => {
  201. resolve(data);
  202. Cache.set(WX_AUTH, code);
  203. Cache.clear(STATE_KEY);
  204. // Cache.clear('spread');
  205. loginType && Cache.clear(LOGINTYPE);
  206. })
  207. .catch(reject);
  208. });
  209. }
  210. /**
  211. * 获取跳转授权后的地址
  212. * @param {Object} appId
  213. */
  214. getAuthUrl(appId, snsapiBase, backUrl) {
  215. if (backUrl.includes("/pages")) {
  216. backUrl = "/front/#" + backUrl;
  217. }
  218. let url = `${location.origin}${backUrl}`
  219. if (url.indexOf('?') == -1) {
  220. url = url + '?'
  221. } else {
  222. url = url + '&'
  223. }
  224. const redirect_uri = encodeURIComponent(
  225. `${url}scope=${snsapiBase}&back_url=` +
  226. encodeURIComponent(
  227. encodeURIComponent(
  228. uni.getStorageSync(BACK_URL) ?
  229. uni.getStorageSync(BACK_URL) :
  230. location.pathname + location.search
  231. )
  232. )
  233. );
  234. uni.removeStorageSync(BACK_URL);
  235. const state = encodeURIComponent(
  236. ("" + Math.random()).split(".")[1] + "authorizestate"
  237. );
  238. uni.setStorageSync(STATE_KEY, state);
  239. 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`;
  240. // if(snsapiBase==='snsapi_base'){
  241. // return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=${state}#wechat_redirect`;
  242. // }else{
  243. // 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`;
  244. // }
  245. }
  246. /**
  247. * 跳转自动登录
  248. */
  249. toAuth(snsapiBase, backUrl) {
  250. let that = this;
  251. this.wechat().then(wx => {
  252. location.href = this.getAuthUrl(that.initConfig.appId, snsapiBase,
  253. backUrl);
  254. })
  255. }
  256. /**
  257. * 绑定事件
  258. * @param {Object} name 事件名
  259. * @param {Object} config 参数
  260. */
  261. wechatEvevt(name, config) {
  262. let that = this;
  263. return new Promise((resolve, reject) => {
  264. let configDefault = {
  265. fail(res) {
  266. if (that.instance) return reject({
  267. is_ready: true,
  268. wx: that.instance
  269. });
  270. that.verifyInstance().then(wx => {
  271. return reject({
  272. is_ready: true,
  273. wx: wx
  274. });
  275. })
  276. },
  277. success(res) {
  278. return resolve(res, 2222);
  279. }
  280. };
  281. Object.assign(configDefault, config);
  282. that.wechat().then(wx => {
  283. if (typeof name === 'object') {
  284. name.forEach(item => {
  285. wx[item] && wx[item](configDefault)
  286. })
  287. } else {
  288. wx[name] && wx[name](configDefault)
  289. }
  290. })
  291. });
  292. }
  293. isWeixin() {
  294. return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
  295. }
  296. }
  297. export default new AuthWechat();
  298. // #endif