微信小程序获取openID(纯前端)

简介

  • 无云开发、无后台接口。
  • 使用uniapp开发,原理与原生类似。

源码

源码地址

代码

<template>
	<view class="page">
	</view>
</template>

<script>
	export default {
		data() {
			return {
				openID: '',
				userCode:'',
				token:'',
			}
		},
		onLoad() {
			this.login();
			this.getOpenid();
			this.getToken();
		},
		methods: {
			// 获取用户信息
			login(){
				uni.login({
					provider: 'weixin',
					success:  loginRes => {
						console.log(loginRes.code);
						this.userCode = loginRes.code;
					}
				});
			},
			// 获取openID
			async getOpenid(){
				let params = {
					appid:'wx8bda0c57123111e7',
					secret: 'ccc431411276f087b41f680275e457a8',
					js_code: this.userCode,
					grant_type: 'authorization_code',
				}
				await uni.request({
					url: 'https://api.weixin.qq.com/sns/jscode2session',
					data: params,
					success: (res) => {
						console.log(res.data);
						this.openID = res.data.openid;
						console.log('openID:'+this.openID)
					}
				});
			},
			// 获取token
			async getToken(){
				let params = {
					appid:'wx8bda0c57123111e7',
					secret: 'ccc431411276f087b41f680275e457a8',
					grant_type: 'client_credential',
				}
				await uni.request({
					url: 'https://api.weixin.qq.com/cgi-bin/token',
					data: params,
					success: (res) => {
						this.token = res.data.access_token;
					}
				});
			},
		},
	}
</script>

<style>
</style>

posted @ 2020-06-29 16:04  春风自是人间客  阅读(2097)  评论(0编辑  收藏  举报