uni-app+php:微信小程序登录:用code得到openid/unionid(hbuilderx 3.7.3)

一,js代码:

<template>
    <view>
         <button class="login-wxpng" open-type="getUserInfo" @getuserinfo="xcxWxLogin">
                    微信小程序登录
         </button>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                
            }
        },
        methods: {
           xcxWxLogin() {
                uni.login({
                    provider: 'weixin',
                    success: function(res) {
                        console.log("微信登录的res结果:");
                        console.log(res);
                        
                        //开始获取openid
                        if (res.code) {
                            //发起网络请求
                            uni.request({
                                method: 'GET',
                                url: 'http://api.lhdtest.com/auth/xcxuserinfo',
                                data: {
                                        app_key: 'wxxcx',
                                        v: '2.75',
                                        code: res.code,
                                },
                                success(res) {
                                        console.log('xcxuserinfo:');
                                        console.log(res);
                                }
                            })
                        } else {
                            console.log('登录失败!' + res.errMsg)
                        }
                        
                    },
                });
            },
        }
    }
</script>

<style>

</style>

说明:刘宏缔的架构森林是一个专注架构的博客,

网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/06/05/uniapp-php-wei-xin-xiao-cheng-xu-deng-lu-yong-code-de-dao/

         对应的源码可以访问这里获取: https://github.com/liuhongdi/
         或: https://gitee.com/liuhongdi

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,服务端php代码:

class Auth extends BaseController
{
   private string $appId = 'wxnideappid';
   private string $appSecret = 'nideappsecret';

    //根据code得到微信用户的信息
    public function xcxUserInfo(){
        $code = $this->request->param('code','','string');
        $result=$this->getSession($code);
        var_dump($result);
    }

    //用code得到微信的session信息,包含用户id
    public function getSession($code){
        $s_data = array();
        $s_data['appid'] = $this->appId;
        $s_data['secret'] = $this->appSecret;
        $s_data['js_code'] = $code;
        $s_data['grant_type']="authorization_code";
        $session_url = 'https://api.weixin.qq.com/sns/jscode2session?' . http_build_query ( $s_data );
        $content = file_get_contents ( $session_url );
        $content = json_decode ( $content, true );
        $content['appid']=$s_data['appid'];
        return $content;
    }
}

三,测试效果

 

 

四,查看hbuilderx的版本: 

 

posted @ 2023-03-14 15:37  刘宏缔的架构森林  阅读(286)  评论(0编辑  收藏  举报