wechat.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. // +----------------------------------------------------------------------
  2. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  3. // +----------------------------------------------------------------------
  4. // | Copyright (c) 2016~2023 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. getShopConfig,
  16. wechatAuthV2
  17. } from "@/api/public";
  18. import {
  19. WX_AUTH,
  20. STATE_KEY,
  21. LOGINTYPE,
  22. BACK_URL
  23. } from '@/config/cache';
  24. import {
  25. parseQuery
  26. } from '@/utils';
  27. import store from '@/store';
  28. import Cache from '@/utils/cache';
  29. class AuthWechat {
  30. constructor() {
  31. //微信实例化对象
  32. this.instance = WechatJSSDK;
  33. //是否实例化
  34. this.status = false;
  35. this.initConfig = {};
  36. }
  37. isAndroid() {
  38. let u = navigator.userAgent;
  39. return u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
  40. }
  41. signLink() {
  42. // if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
  43. // window.entryUrl = encodeURI(window.location.href)
  44. // }
  45. return /(Android)/i.test(navigator.userAgent) ? document.location.href : window.entryUrl;
  46. }
  47. /**
  48. * 初始化wechat(分享配置)
  49. */
  50. wechat() {
  51. return new Promise((resolve, reject) => {
  52. // if (this.status && !this.isAndroid()) return resolve(this.instance);
  53. getWechatConfig()
  54. .then(res => {
  55. this.instance.config(res.data);
  56. this.initConfig = res.data;
  57. this.status = true;
  58. this.instance.ready(() => {
  59. resolve(this.instance);
  60. })
  61. }).catch(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. location() {
  100. return new Promise((resolve, reject) => {
  101. this.wechat().then(wx => {
  102. this.toPromise(wx.getLocation, {
  103. type: 'wgs84'
  104. }).then(res => {
  105. resolve(res);
  106. }).catch(err => {
  107. reject(err);
  108. });
  109. }).catch(err => {
  110. reject(err);
  111. })
  112. });
  113. }
  114. // 使用微信内置地图查看位置接口;
  115. seeLocation(config) {
  116. return new Promise((resolve, reject) => {
  117. this.wechat().then(wx => {
  118. this.toPromise(wx.openLocation, config).then(res => {
  119. resolve(res);
  120. }).catch(err => {
  121. reject(err);
  122. });
  123. }).catch(err => {
  124. reject(err);
  125. })
  126. });
  127. }
  128. /**
  129. * 微信支付
  130. * @param {Object} config
  131. */
  132. pay(config) {
  133. return new Promise((resolve, reject) => {
  134. this.wechat().then((wx) => {
  135. this.toPromise(wx.chooseWXPay, config).then(res => {
  136. resolve(res);
  137. }).catch(res => {
  138. reject(res);
  139. });
  140. }).catch(res => {
  141. reject(res);
  142. });
  143. });
  144. }
  145. toPromise(fn, config = {}) {
  146. return new Promise((resolve, reject) => {
  147. fn({
  148. ...config,
  149. success(res) {
  150. resolve(res);
  151. },
  152. fail(err) {
  153. reject(err);
  154. },
  155. complete(err) {
  156. reject(err);
  157. },
  158. cancel(err) {
  159. reject(err);
  160. }
  161. });
  162. });
  163. }
  164. /**
  165. * 自动去授权
  166. */
  167. oAuth(snsapiBase, url) {
  168. // if (uni.getStorageSync('authIng')) return
  169. if (uni.getStorageSync(WX_AUTH) && store.state.app.token && snsapiBase == 'snsapi_base') return;
  170. let {
  171. code
  172. } = parseQuery();
  173. let snsapiCode = uni.getStorageSync('snsapiCode')
  174. if (code instanceof Array) {
  175. code = code[code.length - 1]
  176. }
  177. if (snsapiCode instanceof Array) {
  178. snsapiCode = snsapiCode[snsapiCode.length - 1]
  179. }
  180. if (!code || code == snsapiCode) {
  181. uni.setStorageSync('authIng', true)
  182. return this.toAuth(snsapiBase, url);
  183. } else {
  184. // if(Cache.has('snsapiKey'))
  185. // return this.auth(code).catch(error=>{
  186. // uni.showToast({
  187. // title:error,
  188. // icon:'none'
  189. // })
  190. // })
  191. }
  192. }
  193. clearAuthStatus() {
  194. }
  195. /**
  196. * 授权登陆获取token
  197. * @param {Object} code
  198. */
  199. auth(code) {
  200. return new Promise((resolve, reject) => {
  201. let loginType = Cache.get(LOGINTYPE);
  202. wechatAuthV2(code, parseInt(Cache.get("spread")))
  203. .then(({
  204. data
  205. }) => {
  206. // store.commit("LOGIN", {
  207. // token: data.token,
  208. // time: Cache.strTotime(data.expires_time) - Cache.time()
  209. // });
  210. // store.commit("SETUID", data.userInfo.uid);
  211. Cache.set(WX_AUTH, code);
  212. Cache.clear(STATE_KEY);
  213. resolve(data);
  214. })
  215. .catch(reject);
  216. });
  217. }
  218. /**
  219. * 获取跳转授权后的地址
  220. * @param {Object} appId
  221. */
  222. getAuthUrl(appId, snsapiBase, backUrl) {
  223. if (backUrl) {
  224. let backUrlArr = backUrl.split('&');
  225. let newUrlArr = backUrlArr.filter(item => {
  226. if (item.indexOf('code=') === -1) {
  227. return item;
  228. }
  229. });
  230. backUrl = newUrlArr.join('&');
  231. }
  232. let url = `${location.origin}${backUrl}`
  233. if (url.indexOf('?') === -1) {
  234. url = url + '?'
  235. } else {
  236. url = url + '&'
  237. }
  238. const redirect_uri = encodeURIComponent(
  239. `${url}scope=${snsapiBase}&back_url=` +
  240. encodeURIComponent(
  241. encodeURIComponent(
  242. uni.getStorageSync(BACK_URL) ?
  243. uni.getStorageSync(BACK_URL) :
  244. location.pathname + location.search
  245. )
  246. )
  247. );
  248. uni.removeStorageSync(BACK_URL);
  249. const state = encodeURIComponent(
  250. ("" + Math.random()).split(".")[1] + "authorizestate"
  251. );
  252. uni.setStorageSync(STATE_KEY, state);
  253. if (snsapiBase === 'snsapi_base') {
  254. return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=${state}&connect_redirect=1#wechat_redirect`;
  255. } else {
  256. return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=${state}&connect_redirect=1#wechat_redirect`;
  257. }
  258. }
  259. /**
  260. * 跳转自动登陆
  261. */
  262. toAuth(snsapiBase, backUrl) {
  263. let that = this;
  264. this.wechat().then(wx => {
  265. location.href = this.getAuthUrl(that.initConfig.appId, snsapiBase, backUrl);
  266. })
  267. }
  268. /**
  269. * 绑定事件
  270. * @param {Object} name 事件名
  271. * @param {Object} config 参数
  272. */
  273. wechatEvevt(name, config) {
  274. let that = this;
  275. return new Promise((resolve, reject) => {
  276. let configDefault = {
  277. fail(res) {
  278. if (that.instance) return reject({
  279. is_ready: true,
  280. wx: that.instance
  281. });
  282. that.verifyInstance().then(wx => {
  283. return reject({
  284. is_ready: true,
  285. wx: wx
  286. });
  287. })
  288. },
  289. success(res) {
  290. return resolve(res, 2222);
  291. }
  292. };
  293. Object.assign(configDefault, config);
  294. that.wechat().then(wx => {
  295. if (typeof name === 'object') {
  296. name.forEach(item => {
  297. wx[item] && wx[item](configDefault)
  298. })
  299. } else {
  300. wx[name] && wx[name](configDefault)
  301. }
  302. })
  303. });
  304. }
  305. isWeixin() {
  306. return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
  307. }
  308. }
  309. export default new AuthWechat();
  310. // #endif