博客列表 >Uni-app 微信登录获取用户code

Uni-app 微信登录获取用户code

鱼的熊掌
鱼的熊掌原创
2022年12月15日 11:34:362024浏览
  1. import { WxCode , WxLogin } from '@/api/user.js'
  2. WxCode({
  3. callback_url: 'http://m.test.com/#/pages/index/wxlogin' //回调地址
  4. }).then(data => {
  5. location.href=data;
  6. // console.log(data);
  7. })
  8. import { WxCode , WxLogin } from '@/api/user.js'
  9. export default {
  10. data() {
  11. return {
  12. code:''
  13. }
  14. },
  15. methods: {
  16. getUrlParam(name) {
  17. var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
  18. var r = window.location.search.substr(1).match(reg)
  19. if (r != null) return unescape(r[2])
  20. return null
  21. },
  22. getRequestParams(name) {
  23. let url = location.href;
  24. let requestParams = {};
  25. if (url.indexOf('?') !== -1) {
  26. let str = url.substr(url.indexOf('?') + 1); //截取?后面的内容作为字符串
  27. // console.log(str, '?后面的内容');
  28. let strs = str.split('&'); //将字符串内容以&分隔为一个数组
  29. // console.log(strs, '以&切割的数组');
  30. for (let i = 0; i < strs.length; i++) {
  31. requestParams[strs[i].split('=')[0]] = decodeURI(strs[i].split('=')[1]);
  32. // 将数组元素中'='左边的内容作为对象的属性名,'='右边的内容作为对象对应属性的属性值
  33. }
  34. }
  35. // console.log(requestParams, '处理后的对象');
  36. if(name){
  37. return requestParams[name];
  38. }else{
  39. return requestParams;
  40. }
  41. },
  42. wxlogin(){
  43. WxLogin({
  44. code: this.code
  45. }).then(data => {
  46. console.log(data);
  47. uni.setStorageSync('token', data.userinfo.token)
  48. uni.redirectTo({
  49. url:'/pages/evaluate/index'
  50. });
  51. })
  52. }
  53. },
  54. created(){
  55. // this.code=this.getUrlParam('cdoe');
  56. // console.log(this.code);
  57. },
  58. onLoad(options) {
  59. this.code=this.getUrlParam('code');
  60. console.log(this.code);
  61. this.wxlogin();
  62. }
  63. }
  1. 返回code 链接
  2. getUrlParam:m.test.com/?code=hZVwoVJCy8cIqBFTNEPmUvpG_csDDL7X9gE799M07PY&state=1#/pages/index/wxlogin
  1. getRequestParams:m.test.com/#/?state=1 getRequestParams('state');
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议