feat: 小程序端实现微信登录

This commit is contained in:
wangtaocs
2024-11-27 17:51:23 +08:00
parent c8787b43cd
commit dd7a4795fc
5 changed files with 72 additions and 1 deletions

4
.gitignore vendored
View File

@@ -19,4 +19,6 @@ dist
*.ntvs*
*.njsproj
*.sln
*.sw?
*.sw?
.hbuilderx
pnpm-lock.yaml

View File

@@ -20,6 +20,23 @@ const AuthAPI = {
});
},
/**
* 微信登录接口
*
* @param code 微信登录code
* @returns 返回 token
*/
wxlogin(code: string): Promise<LoginResult> {
return request<LoginResult>({
url: "/api/v1/auth/wxlogin",
method: "POST",
data: { code },
header: {
"Content-Type": "application/x-www-form-urlencoded",
},
});
},
/**
* 登出接口
*/

View File

@@ -28,6 +28,12 @@
<wd-button size="large" type="primary" block @click="handleLogin">提交</wd-button>
</view>
</wd-form>
<div class="flex justify-center mt-[100rpx]">
<div class="flex flex-col items-center" @click="handleWechatLogin">
<img src="/static/icons/icon_wx.png" class="w-[100rpx] h-[100rpx]" />
<span class="mt-2">微信登录</span>
</div>
</div>
</view>
</view>
</template>
@@ -71,6 +77,35 @@ const handleLogin = () => {
}
});
};
// 微信登录处理
const handleWechatLogin = async () => {
try {
// 获取微信登录的临时 code
const { code } = await uni.login({
provider: "weixin",
});
// 调用后端接口进行登录认证
const result = await userStore.loginByWechat(code);
if (result) {
// 获取用户信息
await userStore.getInfo();
uni.showToast({
title: "登录成功",
icon: "success",
});
}
} catch (error: any) {
console.error("微信登录失败", error);
uni.showToast({
title: error.message || "微信登录失败",
icon: "none",
});
}
};
</script>
<style lang="scss" scoped>

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

View File

@@ -21,6 +21,22 @@ export const useUserStore = defineStore("user", () => {
});
};
// 微信登录
const loginByWechat = (code: string) => {
return new Promise((resolve, reject) => {
AuthAPI.wxlogin(code)
.then((data) => {
setToken(data.accessToken);
resolve(data);
})
.catch((error) => {
console.error("微信登录失败", error);
reject(error);
});
});
// return AuthAPI.wxlogin(code);
};
// 获取用户信息
const getInfo = () => {
return new Promise((resolve, reject) => {
@@ -52,6 +68,7 @@ export const useUserStore = defineStore("user", () => {
return {
userInfo,
login,
loginByWechat,
logout,
getInfo,
};