• go + uniapp 通过 微信 code 获取 appid 等信息 无废话


    go + uniapp 通过 微信 code 获取 appid 等信息 无废话

    • login.vue 通过 uni.login 获取 code
    uni.login({
    	"provider": "weixin",
    	"onlyAuthorize": true, // 微信登录仅请求授权认证
    	success: (event) => {
    		// 登录成功
    		console.log(event);
    
    		const {
    			code
    		} = event;
    		// 向后端发送服务 获取 APPID
    		weixinLogin(code).then((res)=> {
    			console.log(res);
    		})
    	}
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • weixinLogin 把 code 发送给后端
    • 请求 api/user.js
    import request from '@/utils/request/index.js'; // 封装的request.js文件的位置
    
    // 微信登录获取 AppID
    export const weixinLogin = (code) => {
    	return request(`/api/user/wxlogin/${code}`, 'POST')
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 封装的 utils/request.js
    const url_all = {
    	// 'DEV': 'http://localhost:9999', // 开发
    	'DEV': 'http://192.168.137.33:9999', // 安卓模拟器 手机测试的局域网地址
    	// 'PRO': 'http://111.111.111.111:8080', // 生产
    }
    
    let BASEURL = url_all['DEV'] // 调整当前环境
    /*
    * 全局请求封装
    * @param path 请求路径
    * @param method 请求类型(GET/POST/DELETE等)
    * @oaram data 请求体数据
    * @param loading 请求未完成是是否显示加载中,默认为true
    */
    export default (path, method, data = {}, loading = true) => {
    	// 获取存储token
    	const token = uni.getStorageSync("token");
    	if (loading) {
    		uni.showLoading({
    			title: "加载中",
    			mask: true
    		});
    	};
    	//根据token进行调用函数
    	if (token != '') {
    		return tokenRequest(path, method, data, loading, token)
    	} else {
    		return noTokenRequest(path, method, data, loading)
    	}
    };
    
    // 无token时发送请求函数
    function noTokenRequest(path, method, data, loading) { 
    	return new Promise((resolve, reject) => {
    		uni.request({
    			url: BASEURL + path,
    			method: method,
    			data,
    			success(response) {
    				// console.log('%c响应拦截:', ' background:green', response);
    				/* if (response.data.code === 3001) {
    					// logout()
    				} */
    				/* if (response.data.code !== 20) {
    					uni.showToast({
    						icon: "none",
    						duration: 4000,
    						title: response.data.msg
    					});
    				} */
    				// console.log(response.data)
    				resolve(response.data);
    			},
    			fail(err) {
    				uni.showToast({
    					icon: "none",
    					title: '服务响应失败'
    				});
    				console.error(err);
    				reject(err);
    			},
    			complete() {
    				uni.hideLoading();
    			}
    		});
    	});
    }
    
    
    // 有token时发送请求函数
    function tokenRequest(path, method, data, loading,token) {
    	return new Promise((resolve, reject) => {
    		uni.request({
    			url: BASEURL + path,
    			method: method,
    			data,
    			header: {
    				"token":  token
    			},
    			success(response) {
    				// console.log('%c响应拦截:', ' background:green', response);
    				if (response.data.code === 40101) {
    					// logout()
    				}
    				// console.log(response.data)
    				resolve(response.data);
    			},
    			fail(err) {
    				uni.showToast({
    					icon: "none",
    					title: '服务响应失败'
    				});
    				console.error(err);
    				reject(err);
    			},
    			complete() {
    				uni.hideLoading();
    			}
    		});
    	});
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • go -> GetWeiXinOpenID.go
    func (db userDB) GetWeiXinOpenID(ctx *gin.Context) {
    	code := ctx.Params.ByName("code")
    	//小程序appid
    	var appid = "" //小程序id
    	//小程序secret
    	var secret = "" //密钥
    	//wx接口路径
    	var url = "https://api.weixin.qq.com/sns/jscode2session"
    	data := make(map[string]string)
    	data["appid"] = appid
    	data["secret"] = secret
    	data["js_code"] = code
    	data["grant_type"] = "authorization_code"
    	request, err := http.NewRequest("GET", url, nil)
    	if err != nil {
    		panic(err)
    	}
    	query := request.URL.Query()
    	query.Add("appid", appid)
    	query.Add("secret", secret)
    	query.Add("js_code", code)
    	query.Add("grant_type", "authorization_code")
    	
    	var encode string = query.Encode()
    	s := strings.Split(encode, "&")
    	reData := make(map[string]string)
    	for i := range s {
    		reData[strings.Split(s[i], "=")[0]] = strings.Split(s[i], "=")[1]
    	}
    	println(reData)
    	if encode != "" {
    		response.Success(ctx, gin.H{"data": reData}, "SELECT SUCCESS")
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 封装的 response
    package response
    
    import (
    	"github.com/gin-gonic/gin"
    	"net/http"
    )
    
    func Response(ctx *gin.Context, httpStatus int, code int, data gin.H, msg string) {
    	ctx.JSON(httpStatus, gin.H{"code": code, "data": data, "msg": msg})
    }
    
    func Success(ctx *gin.Context, data gin.H, msg string) {
    	Response(ctx, http.StatusOK, 200, data, msg)
    }
    func File(ctx *gin.Context, data gin.H, msg string) {
    	Response(ctx, http.StatusNotFound, 404, data, msg)
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • go -> router.go
    userFun := userController.UserFunction()
    userGroup := r.Group("api/user/")
    userGroup.POST("/wxlogin/:code", userFun.GetWeiXinOpenID)
    
    • 1
    • 2
    • 3
    • go -> mian.go
    package main
    
    import (
    	"github.com/gin-contrib/cors"
    	"github.com/gin-gonic/gin"
    	"github.com/spf13/viper"
    	"go-app/common"
    	"os"
    )
    
    func main() {
    	InitConfig()
    	common.InitDB()
    	r := gin.Default()
    	config := cors.DefaultConfig()
    	config.AllowAllOrigins = true                            //允许所有域名
    	config.AllowMethods = []string{"GET", "POST", "OPTIONS"} //允许请求的方法
    	config.AllowHeaders = []string{"token", "tus-resumable", "upload-length", "upload-metadata", "cache-control", "x-requested-with", "*"}
    	r.Use(cors.New(config))
    
    	// 定义路由和处理函数
    	r = CollectRoute(r)
    	port := viper.GetString("server.port")
    	if port != "" {
    		panic(r.Run(":" + port))
    	}
    	r.Run()
    }
    
    func InitConfig() {
    	workDir, _ := os.Getwd()
    	viper.SetConfigName("application")
    	viper.SetConfigType("yml")
    	viper.AddConfigPath(workDir + "/config")
    	err := viper.ReadInConfig()
    	if err != nil {
    		panic(err)
    	}
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
  • 相关阅读:
    新库上线 | CnOpenData租赁和商务服务业工商注册企业基本信息数据
    PyPy+Cython对Python进行加速,以及乱码问题
    Java中实体与Map的相互转换
    J2EE基础:SpringAop的使用
    当使用 curl -I localhost 命令访问本地主机时,出现 403 Forbidden 错误
    FreeRTOS学习笔记-任务
    Docker基本操作
    【LeetCode热题100】--128. 最长连续序列
    Python字符串中变量使用、删除空白、大数表示和列表(补充)(12)
    Springboot集成ip2region离线IP地名映射
  • 原文地址:https://blog.csdn.net/weixin_56050344/article/details/133934818