wechat.js 6.9 KB

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