uniapp 公众号 获取openid

1,980 阅读1分钟

uniapp 公众号 获取openid

<template>
    <view class="content">
        <image class="logo" src="/static/logo.png"></image>
        <view class="text-area">
            <text class="title">{{title}}</text>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            title: 'Hello'
        }
    },
    onLoad() {
        //获取当前页面的url
        let link = window.location.href;
        console.log(link,'link');
        let code = null; //授权获取的code,用它查询用户基本信息
        // 判断link中有没有code=字符串,  
        if(link.indexOf('code=') === -1){
                //没有code= 发请求
                //公众号或小程序id
                let appid = 'wx9c907e79891f91fe'; 
                //重定向地址,就是用户授权后返回来的地址
                let uri = encodeURIComponent(link);
                let authURL = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
                window.location.href = authURL;
        }else{
                 //回调函数已经执行 返回的链接存在code= 地址解析
                let temp = link.split("code=")[1];
                code = temp.split("&")[0];
                console.log(code,'code');
                //存储code
                uni.setStorageSync('code',code);
                //对后台发送请求传参code获取token和用户信息
                uni.request({
                    url: 'https://www.example.com/request', //仅为示例,并非真实接口地址。
                    data: {
                        code: uni.getStorageSync('code')
                    },
                    success: (res) => {
                        console.log(res.data);
                        // 
                                // 
                    }
                });
        }
    },
    methods: {

    }
}
</script>

<style>
.content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.logo {
    height: 200rpx;
    width: 200rpx;
    margin-top: 200rpx;
    margin-left: auto;
    margin-right: auto;
    margin-bottom: 50rpx;
}

.text-area {
    display: flex;
    justify-content: center;
}

.title {
    font-size: 36rpx;
    color: #8f8f94;
}
</style>

通过open.weixin.qq.com/connect/oau…, 可以获得code,这时可以将code传给后端,让后端调用接口api.weixin.qq.com/sns/oauth2/…, 从而获得access_token,openid

之所以不用前端,是因为前端uni.request()会发送两次请求,第一次是OPTIONS,看请求能否建立,第二次才是真正的请求,但是code在api.weixin.qq.com/sns/oauth2/… 只能使用一次,这样的话,前端永远不会请求成功。如果前端使用的Ajax,可以考虑前端调用该接口。否则该接口一直报40163错误,即code重复使用,在微信开发者工具中的错误如下图所示

image.png