index.vue 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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(() => {
  175. this.$router.replace('/login2')
  176. }, 2000)
  177. }
  178. },
  179. // 用code换取access_token和用户信息
  180. async exchangeCodeForToken(code) {
  181. try {
  182. const response = await wechatAuth({
  183. code: code,
  184. state: this.state
  185. })
  186. // 根据实际API响应格式调整
  187. if (response && response.data) {
  188. return response.data
  189. } else if (response && response.success !== undefined) {
  190. return response
  191. } else {
  192. // 如果API还没有实现,模拟成功响应
  193. return {
  194. success: true,
  195. userInfo: {
  196. openid: 'test_openid_' + Date.now(),
  197. nickname: '微信用户',
  198. headimgurl: '',
  199. unionid: 'test_unionid_' + Date.now()
  200. }
  201. }
  202. }
  203. } catch (error) {
  204. console.error('API调用失败:', error)
  205. }
  206. },
  207. // 跳转到目标页面
  208. redirectToTarget() {
  209. let targetPath = '/'
  210. // 使用已解析的redirect参数
  211. if (this.redirect) {
  212. targetPath = this.redirect
  213. }
  214. console.log('跳转到目标页面:', targetPath)
  215. this.$router.replace(targetPath)
  216. },
  217. // 重试授权
  218. retryAuth() {
  219. this.authStatus = 'init'
  220. this.errorMessage = ''
  221. this.startAuth()
  222. },
  223. // 检查是否在微信浏览器中
  224. isWechatBrowser() {
  225. const ua = navigator.userAgent.toLowerCase()
  226. return ua.indexOf('micromessenger') !== -1
  227. },
  228. // 从URL hash中提取redirect参数
  229. extractRedirectFromHash() {
  230. const hash = window.location.hash
  231. if (hash && hash.includes('redirect=')) {
  232. const match = hash.match(/redirect=([^&]+)/)
  233. if (match) {
  234. return decodeURIComponent(match[1])
  235. }
  236. }
  237. return null
  238. },
  239. async getLogin() {
  240. const userid = await this.login()
  241. let redirect_uri = Cookies.get('redirectUri')
  242. if (!redirect_uri || redirect_uri === 'undefined') {
  243. redirect_uri = ''
  244. }
  245. console.log(redirect_uri)
  246. if (userid) {
  247. if (redirect_uri) {
  248. // Cookies.remove('redirectUri')
  249. window.location.href = redirect_uri
  250. } else {
  251. this.$router.replace('/appStoreCopy')
  252. }
  253. return '1'
  254. }
  255. return '2'
  256. // eduGet().then(res => {})
  257. }
  258. },
  259. mounted() {
  260. // 检查是否在微信浏览器中
  261. if (!this.isWechatBrowser()) {
  262. // this.authStatus = 'error'
  263. // this.errorMessage = '请在微信中打开此页面'
  264. Cookies.set('isWeChat', '1')
  265. this.$router.replace('/login2')
  266. return
  267. }else{
  268. Cookies.set('isWeChat', '2')
  269. }
  270. let type = this.getLogin();
  271. if(type == '1'){
  272. return;
  273. }
  274. // 如果有code参数,说明是从微信授权回调过来的
  275. if (this.code) {
  276. this.handleAuthCallback()
  277. } else {
  278. // 没有code参数,开始授权流程
  279. this.startAuth()
  280. }
  281. }
  282. }
  283. </script>
  284. <style lang="scss" scoped>
  285. .wechat-auth-container {
  286. min-height: 100vh;
  287. background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  288. display: flex;
  289. align-items: center;
  290. justify-content: center;
  291. padding: 20px;
  292. .auth-content {
  293. background: white;
  294. border-radius: 16px;
  295. padding: 40px 30px;
  296. text-align: center;
  297. box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  298. max-width: 400px;
  299. width: 100%;
  300. .logo {
  301. margin-bottom: 30px;
  302. img {
  303. width: 80px;
  304. height: 80px;
  305. border-radius: 50%;
  306. }
  307. }
  308. .auth-status {
  309. .van-loading,
  310. .van-icon {
  311. margin-bottom: 20px;
  312. }
  313. p {
  314. margin: 10px 0;
  315. font-size: 16px;
  316. color: #333;
  317. &.user-info {
  318. font-size: 14px;
  319. color: #666;
  320. margin-top: 10px;
  321. }
  322. &.auth-desc {
  323. font-size: 14px;
  324. color: #999;
  325. margin: 15px 0 25px;
  326. }
  327. &.error-message {
  328. font-size: 14px;
  329. color: #ee0a24;
  330. margin: 15px 0 25px;
  331. }
  332. }
  333. .van-button {
  334. margin-top: 20px;
  335. width: 200px;
  336. height: 44px;
  337. border-radius: 22px;
  338. }
  339. }
  340. }
  341. }
  342. // 响应式设计
  343. @media (max-width: 480px) {
  344. .wechat-auth-container {
  345. padding: 10px;
  346. .auth-content {
  347. padding: 30px 20px;
  348. .auth-status {
  349. .van-button {
  350. width: 100%;
  351. }
  352. }
  353. }
  354. }
  355. }
  356. </style>