学习笔记(十一)微信-获取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{/**用户唯一标识*/@TableIdprivate 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 {//根据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 {//根据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 implements IWechatUserService {@Resourceprivate WechatUserMapper mapper;//根据openid更新用户信息@Overridepublic 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 = "小程序路径";// 第一步:用户同意授权,获取codeString 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_tokenString 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)


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部