学习笔记(十一)微信-获取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)

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在微信支付中获取用户的openid,您需要进行以下步骤: 1. 首先,您需要在微信公众平台设置获取openid的域名。只有被设置过的域名才是有效的获取openid的域名。如果没有设置过域名,获取openid的操作将会失败。\[2\] 2. 在您的开发中,您需要使用统一下单接口来进行支付。在统一下单接口中,需要传递用户的openid作为参数。\[2\] 3. 要获取用户的openid,您可以通过以下步骤: - 用户在微信客户端中打开您的网页或应用程序。 - 您需要在网页或应用程序中生成一个授权链接,链接中包含您的公众号的appid、secret和一个code参数。 - 用户点击授权链接后,会跳转到微信的授权页面,用户需要确认授权。 - 授权成功后,微信会将一个code参数返回给您的网页或应用程序。 - 您可以使用这个code参数,通过调用微信的接口来获取用户的openid。\[3\] 请注意,以上步骤仅适用于JSAPI支付方式。对于其他支付方式,例如扫码支付和非微信内置浏览器H5支付,可能会有不同的获取openid的方式。如果您对其他支付方式的获取openid有疑问,可以进一步咨询微信支付的官方文档或联系微信支付的技术支持。 #### 引用[.reference_title] - *1* [微信公众号支付 (一、获取openId)](https://blog.csdn.net/weixin_38941916/article/details/78013090)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [微信公众号支付--1--获取openid](https://blog.csdn.net/hjfcgt123/article/details/104172909)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值