学习笔记(十一)微信-获取openid

最近在学习微信方面的开发,首先记录一下获取openid的实现。

前言

针对微信公众号获取用户openid,首先阅读微信的官方文档:网页授权 | 微信开放文档

一、需求

微信用户进入小程序后,点击授权,获取用户的openid并存入数据库。

二、思路

1、获取微信用户code

2、根据微信用户的code获取openid和用户信息

3、将信息存入数据库

三、实现

1、util类

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpClientUtils {

    /**
     * 发起一个GET请求, 返回数据是以JSON格式返回
     * @param url
     * @return
     * @throws IOException
     */
    public static JSONObject doGet(String url) throws IOException {
        JSONObject jsonObject = null;
        CloseableHttpClient client = HttpClients.createDefault();


        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = JSONObject.parseObject(result);
        }

        httpGet.releaseConnection();
        return jsonObject;
    }

}

2、entity类

先在数据库中新建一个用来存放微信用户信息的表。

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

import java.util.Date;

@Data
@TableName("wechat_user")
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value="wechat_user对象", description="用户区划信息")
public class WechatUser{

    /**用户唯一标识*/
    @TableId
    private String openid;

    /**昵称*/
    private String nickName;

    /**性别*/
    private Integer sex;

    /**国家*/
    private String country;

    /**省份*/
    private String province;

    /**城市*/
    private String city;

    /**头像*/
    private String headImgUrl;

    /**订阅*/
    private String subscribe;

    /**类型*/
    private Integer type;

    /**手机号*/
    private String phone;

    /**createTime*/
    private Date createTime;

    /**updateTime*/
    private Date updateTime;

}

3、mapper类

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Update;
import org.jeecg.modules.wechat.entity.WechatUser;

public interface WechatUserMapper extends BaseMapper<WechatUser> {

    //根据openid更新用户信息
    @Update("update wechat_user set nick_name = #{nickName}, head_img_url = #{headImgUrl}, phone = #{phone},sex = #{sex},update_time = now() where openid = #{openid}")
    int updateUser(WechatUser userEntity);

}

4、service及serviceImpl类

import com.baomidou.mybatisplus.extension.service.IService;
import org.jeecg.modules.wechat.entity.WechatUser;

public interface IWechatUserService extends IService<WechatUser> {

    //根据openid更新用户信息
    int updateUser(WechatUser userEntity);
}
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.modules.wechat.entity.WechatUser;
import org.jeecg.modules.wechat.mapper.WechatUserMapper;
import org.jeecg.modules.wechat.service.IWechatUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class WechatUserServiceImpl extends ServiceImpl<WechatUserMapper, WechatUser> implements IWechatUserService {

    @Resource
    private WechatUserMapper mapper;

    //根据openid更新用户信息
    @Override
    public int updateUser(WechatUser userEntity) {
        return mapper.updateUser(userEntity);
    }
}

5、controller类

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.wechat.entity.WechatUser;
import org.jeecg.modules.wechat.service.IWechatUserService;
import org.jeecg.modules.wechat.util.HttpClientUtils;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.io.*;

@Slf4j
@RequiredArgsConstructor
@Api(tags = "微信接口")
@RestController
@RequestMapping(value = "/wx")
public class WechatController {

    final IWechatUserService wechatUserService;


    @ApiOperation("获取微信用户code")
    @GetMapping("/wxlogin")
    public String wxlogin() {
        String appid = "你的公众号appid";
        String http = "小程序路径";

        // 第一步:用户同意授权,获取code
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid +
                "&redirect_uri=" + http +
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=STATE#wechat_redirect";
        System.out.println("url:"+url);
        return url;
    }

    @ApiOperation("根据微信用户code获取openid和用户信息")
    @GetMapping("/wxcallback")
    public Result<?> wxcallback(String code, ModelMap map) throws IOException {
        String appid = "你的公众号openid";
        String appsecret = "你的公众号secret";
        // 第二步:通过code换取网页授权access_token
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid +
                "&secret=" + appsecret +
                "&code=" + code +
                "&grant_type=authorization_code";
        JSONObject jsonObject = HttpClientUtils.doGet(url);

        String openid = jsonObject.getString("openid");
        String access_Token = jsonObject.getString("access_token");

        System.out.println("jsonObject:"+jsonObject);

        // 第四步:拉取用户信息(需scope为 snsapi_userinfo)
        url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_Token +
                "&openid=" + openid +
                "&lang=zh_CN";
        JSONObject userInfoJson = HttpClientUtils.doGet(url);
        System.out.println("UserInfo:" + userInfoJson);

        // 2种情况: 我们是有账号体系的,微信帐号做来一个关联,来关联我们的账号体系
        WechatUser userEntity = wechatUserService.getById(openid);
        if (userEntity == null) {  //用户信息存入数据库
            userEntity = new WechatUser();
            userEntity.setType(0);
            userEntity.setOpenid(openid);
            userEntity.setSex((Integer) userInfoJson.get("sex"));
            userEntity.setNickName((String)userInfoJson.get("nick_name"));
            userEntity.setHeadImgUrl((String)userInfoJson.get("head_img_url"));
            userEntity.setCountry((String)userInfoJson.get("country"));
            userEntity.setProvince((String)userInfoJson.get("province"));
            userEntity.setCity((String)userInfoJson.get("city"));
            userEntity.setSubscribe((String)userInfoJson.get("subscribe"));
            userEntity.setPhone((String)userInfoJson.get("phone"));
            wechatUserService.save(userEntity);
        } else {  //更新用户信息
            userEntity.setNickName((String)userInfoJson.get("nickname"));
            userEntity.setHeadImgUrl((String)userInfoJson.get("headimgurl"));
            userEntity.setPhone((String)userInfoJson.get("phone"));
            userEntity.setSex((Integer) userInfoJson.get("sex"));
            wechatUserService.updateUser(userEntity);
        }

        return Result.OK(userInfoJson);
    }

}

总结

1、首先根据微信官方文档内容,调用所需接口;

2、学习过程中参考了以下文章,写的很清楚,帮助我避免了很多问题,感谢!

链接:java获取微信用户信息(含源码,直接改下appid就可以使用了) - 炫意HTML5 (xyhtml5.com)

<think>好的,用户想了解如何用Java开发笔记微信小程序。首先,我需要明确用户的需求,可能他们希望从零开始搭建一个具有笔记功能的小程序,并且后端使用Java。接下来,我需要整理开发流程,确保涵盖前端和后端的整合步骤。 首先,小程序前端部分需要使用微信提供的开发工具,可能涉及WeUI框架,引用[3]提到WeUI是官方样式库,所以应该推荐使用。然后,后端Java部分需要搭建Spring Boot项目,因为这是常用的Java框架,引用[4]提到整合微信小程序和Java后端,可能需要配置控制器和处理请求。 用户可能对前后端通信不太熟悉,需要详细说明API设计,比如创建笔记获取列表等接口。同时,数据存储方面,引用[2]提到Java与Redis整合,但这里可能需要更基础的数据库,比如MySQL,所以需要说明如何集成MyBatis或JPA。 另外,引用[4]中提到在微信开发工具中创建项目时不填写AppID,适用于内部测试,这点需要注意。用户可能还关心如何调试和部署,需要指导如何配置HTTPS,因为微信小程序要求后端使用HTTPS。 还要考虑安全性,比如用户登录验证,微信小程序通常使用微信登录,可能需要获取openid,但用户问题可能更关注笔记功能本身,所以暂时可以简化身份验证部分,或者使用模拟数据。 最后,生成相关问题时要覆盖开发流程中的关键点,比如框架选择、前后端通信、数据存储、界面优化和部署等,帮助用户进一步深入学习。</think>### 使用 Java 开发笔记微信小程序的步骤指南 #### 一、开发环境搭建 1. **前端工具**:安装微信开发者工具[^3],创建小程序项目时选择不填写 AppID(适用于本地测试)[^4] 2. **后端环境**: - 使用 Maven 创建 Java Web 项目 - 集成 Spring Boot 框架简化开发流程 - 配置 Tomcat 服务器或内嵌容器 ```java // Spring Boot 启动类示例 @SpringBootApplication public class NotesApplication { public static void main(String[] args) { SpringApplication.run(NotesApplication.class, args); } } ``` #### 二、前后端通信实现 1. **API 设计规范**: - 创建笔记:`POST /api/notes` - 获取笔记列表:`GET /api/notes` - 更新笔记:`PUT /api/notes/{id}` - 删除笔记:`DELETE /api/notes/{id}` 2. **微信小程序网络请求**: ```javascript // 小程序端请求示例 wx.request({ url: 'https://yourdomain.com/api/notes', method: 'POST', data: { title: '示例', content: '测试内容' }, success: (res) => console.log(res.data) }) ``` #### 三、数据存储实现 1. **数据库选择**: - MySQL 关系型数据库(存储结构化数据) - 集成 MyBatis 或 Spring Data JPA ```java // JPA 实体类示例 @Entity @Table(name = "notes") public class Note { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private String content; // getters/setters } ``` 2. **文件存储**: - 使用阿里云 OSS 或腾讯云 COS 存储附件 - 本地文件存储(仅限开发环境) #### 四、界面开发建议 1. **使用 WeUI 样式库**: ```xml <!-- 示例:笔记列表项 --> <view class="weui-cell"> <view class="weui-cell__bd">{{item.title}}</view> <view class="weui-cell__ft">{{item.createTime}}</view> </view> ``` 2. **功能模块划分**: - 笔记列表页 - 笔记编辑页 - 分类管理页 - 搜索功能页 #### 五、安全与部署 1. **HTTPS 配置**: - 申请 SSL 证书(Let's Encrypt 免费证书) - Spring Boot 配置示例: ```properties server.port=443 server.ssl.key-store=classpath:keystore.p12 server.ssl.key-store-password=yourpassword ``` 2. **微信登录集成**: - 通过 `wx.login` 获取 code - 后端通过 code 换取 openid ```java // 登录验证示例 public String wechatLogin(String code) { // 调用微信API换取openid // 生成自定义登录态token return token; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值