index.vue 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. <template>
  2. <div class="wechat-auth-container">
  3. <div class="auth-content">
  4. <!-- <div class="logo">
  5. <img src="@/assets/images/logo.png" alt="Logo" />
  6. </div> -->
  7. <div class="auth-status" v-if="authStatus === 'loading'">
  8. <van-loading type="spinner" color="#1989fa" />
  9. <p>正在授权中...</p>
  10. </div>
  11. <!--
  12. <div class="auth-status" v-else-if="authStatus === 'success'">
  13. <van-icon name="success" color="#07c160" size="48" />
  14. <p>授权成功</p>
  15. <p class="user-info">{{ userInfo.nickname }}</p>
  16. </div> -->
  17. <div class="auth-status" v-else-if="authStatus === 'error'">
  18. <van-icon name="cross" color="#ee0a24" size="48" />
  19. <p>授权失败</p>
  20. <p class="error-message">{{ errorMessage }}</p>
  21. <van-button type="primary" @click="retryAuth">重新授权</van-button>
  22. </div>
  23. <div class="auth-status" v-else>
  24. <van-icon name="wechat" color="#07c160" size="48" />
  25. <p>微信授权</p>
  26. <p class="auth-desc">请点击下方按钮进行微信授权</p>
  27. <van-button type="primary" @click="startAuth">{{ Loading ? '授权中...' : '开始授权' }}</van-button>
  28. </div>
  29. </div>
  30. </div>
  31. </template>
  32. <script>
  33. import { mapActions } from 'vuex'
  34. import { wechatAuth, wechatRegister } from '@/api/wechat'
  35. import Cookies from 'js-cookie'
  36. export default {
  37. name: 'WechatAuth',
  38. data() {
  39. return {
  40. authStatus: 'init', // init, loading, success, error
  41. userInfo: {},
  42. errorMessage: '',
  43. redirect: '',
  44. code: '',
  45. Loading: false
  46. }
  47. },
  48. computed: {
  49. // 微信授权配置
  50. wechatConfig() {
  51. // 直接返回对象,不需要再返回函数
  52. const redirectUri = this.$route.query.url ? decodeURIComponent(this.$route.query.url) : null
  53. console.log('redirectUri from query:', redirectUri)
  54. if (redirectUri && redirectUri !== 'undefined') {
  55. Cookies.set('redirectUri', redirectUri)
  56. }
  57. return {
  58. appId: 'wx2d69589899b7ecd6',
  59. // appId: 'wx3a8dd28881c2c41f',
  60. scope: 'snsapi_userinfo', // snsapi_base 或 snsapi_userinfo
  61. redirectUri: encodeURIComponent(window.location.origin + '/login'),
  62. state: 'wechat_auth'
  63. }
  64. }
  65. },
  66. watch: {
  67. $route: {
  68. handler: function(route) {
  69. // 从URL中提取参数,包括#之前的参数
  70. const url = window.location.href
  71. const urlParams = new URLSearchParams(url.split('?')[1]?.split('#')[0] || '')
  72. this.code = urlParams.get('code') || route.query.code
  73. this.state = urlParams.get('state') || route.query.state
  74. // redirect参数可能在#之后
  75. this.redirect = route.query.redirect || this.extractRedirectFromHash()
  76. console.log('URL参数解析:', {
  77. url: url,
  78. code: this.code,
  79. state: this.state,
  80. redirect: this.redirect,
  81. routeQuery: route.query
  82. })
  83. },
  84. immediate: true
  85. }
  86. },
  87. methods: {
  88. ...mapActions({
  89. login: 'user/login',
  90. getInfo: 'user/getInfo'
  91. }),
  92. // 开始微信授权
  93. startAuth() {
  94. if (this.Loading) {
  95. return
  96. }
  97. this.authStatus = 'loading'
  98. // 构建微信授权URL
  99. const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.wechatConfig.appId}&redirect_uri=${this.wechatConfig.redirectUri}&response_type=code&scope=${this.wechatConfig.scope}&state=${this.wechatConfig.state}#wechat_redirect`
  100. // 跳转到微信授权页面
  101. window.location.href = authUrl
  102. },
  103. // 处理微信授权回调
  104. async handleAuthCallback() {
  105. if (!this.code) {
  106. this.authStatus = 'error'
  107. this.errorMessage = '未获取到授权码'
  108. return
  109. }
  110. try {
  111. this.authStatus = 'loading'
  112. this.Loading = true
  113. // 调用后端接口,用code换取access_token和用户信息
  114. const result = await this.exchangeCodeForToken(this.code)
  115. console.log(result)
  116. if (result.openid) {
  117. this.userInfo = result
  118. this.authStatus = 'success'
  119. const res = await wechatRegister({
  120. username: result.userInfo.nickname,
  121. mail: result.openid + '@wechat.com',
  122. openid: result.openid + '-wechat'
  123. })
  124. console.log(res)
  125. // console.log(res)
  126. const loginData = JSON.stringify({
  127. openid: result.openid + '-wechat',
  128. edu: true
  129. })
  130. const myHeaders = new Headers()
  131. myHeaders.append('Content-Type', 'application/json')
  132. const requestOptionsLogin = {
  133. method: 'POST',
  134. headers: myHeaders,
  135. body: loginData,
  136. redirect: 'follow',
  137. credentials: 'include'
  138. }
  139. fetch('https://beta.api.cocorobo.cn/api/user', requestOptionsLogin)
  140. .then(response => response.text())
  141. .then(async() => {
  142. // this.$router.replace('/login')
  143. await this.login()
  144. let redirect_uri = Cookies.get('redirectUri')
  145. if (!redirect_uri || redirect_uri === 'undefined') {
  146. redirect_uri = ''
  147. }
  148. this.Loading = false
  149. console.log(redirect_uri)
  150. if (redirect_uri) {
  151. // Cookies.remove('redirectUri')
  152. window.location.href = redirect_uri
  153. } else {
  154. this.$router.replace('/appStoreCopy')
  155. }
  156. })
  157. .catch(error => {
  158. this.Loading = false
  159. console.log('error', error)
  160. setTimeout(() => {
  161. this.$router.replace('/login2')
  162. }, 2000)
  163. })
  164. } else {
  165. this.Loading = false
  166. throw new Error(result.message || '授权失败')
  167. }
  168. } catch (error) {
  169. console.error('微信授权失败:', error)
  170. this.authStatus = 'error'
  171. this.Loading = false
  172. this.errorMessage = error.message || '授权失败,请重试'
  173. // 如果授权失败,跳转到登录页面
  174. // setTimeout( async () => {
  175. let type = await this.getLogin();
  176. if(type == '1'){
  177. return;
  178. }else {
  179. this.$router.replace('/login2')
  180. }
  181. // }, 2000)
  182. }
  183. },
  184. // 用code换取access_token和用户信息
  185. async exchangeCodeForToken(code) {
  186. try {
  187. const response = await wechatAuth({
  188. code: code,
  189. state: this.state
  190. })
  191. // 根据实际API响应格式调整
  192. if (response && response.data) {
  193. return response.data
  194. } else if (response && response.success !== undefined) {
  195. return response
  196. } else {
  197. // 如果API还没有实现,模拟成功响应
  198. return {
  199. success: true,
  200. userInfo: {
  201. openid: 'test_openid_' + Date.now(),
  202. nickname: '微信用户',
  203. headimgurl: '',
  204. unionid: 'test_unionid_' + Date.now()
  205. }
  206. }
  207. }
  208. } catch (error) {
  209. console.error('API调用失败:', error)
  210. }
  211. },
  212. // 跳转到目标页面
  213. redirectToTarget() {
  214. let targetPath = '/'
  215. // 使用已解析的redirect参数
  216. if (this.redirect) {
  217. targetPath = this.redirect
  218. }
  219. console.log('跳转到目标页面:', targetPath)
  220. this.$router.replace(targetPath)
  221. },
  222. // 重试授权
  223. retryAuth() {
  224. this.authStatus = 'init'
  225. this.errorMessage = ''
  226. this.startAuth()
  227. },
  228. // 检查是否在微信浏览器中
  229. isWechatBrowser() {
  230. const ua = navigator.userAgent.toLowerCase()
  231. return ua.indexOf('micromessenger') !== -1
  232. },
  233. // 从URL hash中提取redirect参数
  234. extractRedirectFromHash() {
  235. const hash = window.location.hash
  236. if (hash && hash.includes('redirect=')) {
  237. const match = hash.match(/redirect=([^&]+)/)
  238. if (match) {
  239. return decodeURIComponent(match[1])
  240. }
  241. }
  242. return null
  243. },
  244. async getLogin() {
  245. this.loading = true
  246. const userid = await this.login()
  247. let redirect_uri = Cookies.get('redirectUri')
  248. if (!redirect_uri || redirect_uri === 'undefined') {
  249. redirect_uri = ''
  250. }
  251. this.Loading = false
  252. console.log(redirect_uri)
  253. if (userid) {
  254. if (redirect_uri) {
  255. // Cookies.remove('redirectUri')
  256. window.location.href = redirect_uri
  257. } else {
  258. this.$router.replace('/appStoreCopy')
  259. }
  260. return '1'
  261. }
  262. return '2'
  263. // eduGet().then(res => {})
  264. }
  265. },
  266. async mounted() {
  267. // 检查是否在微信浏览器中
  268. if (!this.isWechatBrowser()) {
  269. // this.authStatus = 'error'
  270. // this.errorMessage = '请在微信中打开此页面'
  271. Cookies.set('isWeChat', '1')
  272. this.$router.replace('/login2')
  273. return
  274. }else{
  275. Cookies.set('isWeChat', '2')
  276. }
  277. let type = await this.getLogin();
  278. if(type == '1'){
  279. return;
  280. }
  281. // 如果有code参数,说明是从微信授权回调过来的
  282. if (this.code) {
  283. this.handleAuthCallback()
  284. } else {
  285. // 没有code参数,开始授权流程
  286. this.startAuth()
  287. }
  288. }
  289. }
  290. </script>
  291. <style lang="scss" scoped>
  292. .wechat-auth-container {
  293. min-height: 100vh;
  294. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  295. display: flex;
  296. align-items: center;
  297. justify-content: center;
  298. padding: 20px;
  299. .auth-content {
  300. background: white;
  301. border-radius: 16px;
  302. padding: 40px 30px;
  303. text-align: center;
  304. box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  305. max-width: 400px;
  306. width: 100%;
  307. .logo {
  308. margin-bottom: 30px;
  309. img {
  310. width: 80px;
  311. height: 80px;
  312. border-radius: 50%;
  313. }
  314. }
  315. .auth-status {
  316. .van-loading,
  317. .van-icon {
  318. margin-bottom: 20px;
  319. }
  320. p {
  321. margin: 10px 0;
  322. font-size: 16px;
  323. color: #333;
  324. &.user-info {
  325. font-size: 14px;
  326. color: #666;
  327. margin-top: 10px;
  328. }
  329. &.auth-desc {
  330. font-size: 14px;
  331. color: #999;
  332. margin: 15px 0 25px;
  333. }
  334. &.error-message {
  335. font-size: 14px;
  336. color: #ee0a24;
  337. margin: 15px 0 25px;
  338. }
  339. }
  340. .van-button {
  341. margin-top: 20px;
  342. width: 200px;
  343. height: 44px;
  344. border-radius: 22px;
  345. }
  346. }
  347. }
  348. }
  349. // 响应式设计
  350. @media (max-width: 480px) {
  351. .wechat-auth-container {
  352. padding: 10px;
  353. .auth-content {
  354. padding: 30px 20px;
  355. .auth-status {
  356. .van-button {
  357. width: 100%;
  358. }
  359. }
  360. }
  361. }
  362. }
  363. </style>