uniapp前后端数据对接,以微信授权登录为例

 uniapp前后端数据对接,以微信授权登录为例

uni.request({    //URL填写后端给的地址
				url: 'http://167:8080/ddaddemo/api/wxlogin',
                
				method: 'POST',
				header: {
				"content-type": "application/jsGBN",
				"source": "fromApp"
				},
                //需要传到后端的数据放在data
				data: {
               
				"code" :code,										
				"nickName": userInfo.nickName,
				"gender": userInfo.gender,
				"city": userInfo.city,
				"country": userInfo.country,
				"language": userInfo.language,
				"province": userInfo.province,
				"avatarUrl": userInfo.avatarUrl
									
				},
				success: (res3) => {
				// 登录成功,后端返回数据在res里面
				uni.showToast({
					icon:"success",
					title:"登陆成功!"
										})
				 console.log('登录成功:' + JSON.stringify(res3));
				uni.hideLoading()
				console.log(res3)
										// 步骤4:处理业务逻辑
										// 比如:更换昵称和头像
										this.nickName = userInfo.nickName
										this.avatarUrl = userInfo.avatarUrl
										this.city = userInfo.city
										//关闭登录按键
										this.loginShow = false
									},
									fail: (err) => {
										// 登录失败
										uni.hideLoading()
										uni.showToast({
											title: '登录失败',
											icon: 'none'
										});
									}
								});

 登陆成功会返回的data中会包含session_key ,open_id以及token,由于涉及到隐私,因此不在此处贴出来了,由此登录完成!

所有的登录流程代码如下:

// 登录流程
			login() {
				// 提醒:如果遇到this未定义问题,需要在方法开始的时候,执行下面的代码,然后将后面的this换成that。
				let that = this

				// 步骤1:调用uni.getUserProfile(),弹出授权窗口
				uni.getUserProfile({
					desc: '注册', // 这个参数是必须的,desc属性(声明获取用户个人信息后的用途)后续会展示在弹窗中,请开发者谨慎填写。
					success: (res) => {
						// 用户点击了允许,拿到用户信息
						console.log("用户信息: " + JSON.stringify(res.userInfo));
						let userInfo = res.userInfo;

						//  步骤2:调用uni.login(),获取code
						uni.login({
							provider: 'weixin', // 登录服务提供商,这里是weixin
							success: (res2) => {
								uni.showLoading({
									title: '登录中',

								})
								// 获得code
								var code = res2.code
								// appid和appsecret可以不用获取
								// var appid = res2.appid
								// var appsecret = res2.appsecret
								console.log("获取code成功: " + JSON.stringify(res2));
								console.log("code"+JSON.stringify(res2.code))
													
								// 步骤3:向后端服务器发送请求,带上参数:code和用户信息,将用户信息保存到数据库
								uni.request({
									url: 'http://167:8080/ddaddemo/api/wxlogin',
									method: 'POST',
									header: {
										"content-type": "application/jsGBN",
										"source": "fromApp"
									},
									data: {
										"code" :code,
										// info: JSON.stringify({
										// 	"code": code,
										
										"nickName": userInfo.nickName,
										"gender": userInfo.gender,
										"city": userInfo.city,
										"country": userInfo.country,
										"language": userInfo.language,
										"province": userInfo.province,
										"avatarUrl": userInfo.avatarUrl
										// })
									},
									success: (res3) => {
										// 登录成功
										uni.showToast({
											icon:"success",
											title:"登陆成功!"
										})
										// console.log('登录成功:' + JSON.stringify(res3));
										uni.hideLoading()
										console.log(res3)
										// 步骤4:处理业务逻辑
										// 比如:更换昵称和头像
										this.nickName = userInfo.nickName
										this.avatarUrl = userInfo.avatarUrl
										this.city = userInfo.city
										//关闭登录按键
										this.loginShow = false
									},
									fail: (err) => {
										// 登录失败
										uni.hideLoading()
										uni.showToast({
											title: '登录失败',
											icon: 'none'
										});
									}
								});
							}
						})
					},
					fail: (err) => {
						// 用户点击了拒绝
						uni.showToast({
							title: '您点击了拒绝',
							icon: 'none'
						})
						console.log("用户点击了拒绝" + JSON.stringify(err));
					}
				})
			},

  • 2
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用Java对接微信登陆,需要使用微信开放平台提供的OAuth2.0授权登录接口。下面是一个使用Java实现微信登陆的示例代码: ```java import java.io.IOException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class WeChatLogin { // 应用ID private static final String APP_ID = "your_app_id"; // 应用密钥 private static final String APP_SECRET = "your_app_secret"; // 授权回调地址 private static final String REDIRECT_URI = "your_redirect_uri"; /** * 获取微信授权链接 * * @return */ public static String getAuthorizeUrl() { String url = "https://open.weixin.qq.com/connect/oauth2/authorize"; String encodedUri = URLEncoder.encode(REDIRECT_URI); String params = String.format("appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect", APP_ID, encodedUri); return url + "?" + params; } /** * 通过code换取网页授权access_token * * @param code * @return * @throws IOException */ public static String getAccessToken(String code) throws IOException { String url = "https://api.weixin.qq.com/sns/oauth2/access_token"; String params = String.format("appid=%s&secret=%s&code=%s&grant_type=authorization_code", APP_ID, APP_SECRET, code); String requestUrl = url + "?" + params; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(requestUrl).get().build(); Response response = client.newCall(request).execute(); String json = response.body().string(); JSONObject jsonObject = JSON.parseObject(json); return jsonObject.getString("access_token"); } /** * 获取微信用户信息 * * @param accessToken * @param openId * @return * @throws IOException */ public static Map<String, String> getUserInfo(String accessToken, String openId) throws IOException { String url = "https://api.weixin.qq.com/sns/userinfo"; String params = String.format("access_token=%s&openid=%s&lang=zh_CN", accessToken, openId); String requestUrl = url + "?" + params; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(requestUrl).get().build(); Response response = client.newCall(request).execute(); String json = response.body().string(); JSONObject jsonObject = JSON.parseObject(json); Map<String, String> userInfo = new HashMap<>(); userInfo.put("openId", jsonObject.getString("openid")); userInfo.put("nickname", jsonObject.getString("nickname")); userInfo.put("sex", jsonObject.getString("sex")); userInfo.put("province", jsonObject.getString("province")); userInfo.put("city", jsonObject.getString("city")); userInfo.put("country", jsonObject.getString("country")); userInfo.put("headImgUrl", jsonObject.getString("headimgurl")); return userInfo; } public static void main(String[] args) { // 1. 获取微信授权链接 String authorizeUrl = getAuthorizeUrl(); System.out.println("授权链接:" + authorizeUrl); // 2. 用户同意授权后,获取code String code = "your_code"; try { // 3. 通过code获取access_token String accessToken = getAccessToken(code); System.out.println("access_token:" + accessToken); // 4. 获取用户信息 Map<String, String> userInfo = getUserInfo(accessToken, "your_openid"); System.out.println("用户信息:" + userInfo); } catch (IOException e) { e.printStackTrace(); } } } ``` 其,`getAuthorizeUrl()`方法用于获取微信授权链接,`getAccessToken()`方法用于通过code换取网页授权access_token,`getUserInfo()`方法用于获取微信用户信息。在main方法,你需要将`your_code`和`your_openid`替换成实际的值。 需要注意的是,示例代码使用了OkHttp库来发送HTTP请求,需要在项目添加OkHttp库的依赖。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值