tp5微信公众号获取用户openid_微信公众号获取openId

package com.hifo.artifact.api.controller;

import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.UUID;

import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

import com.hifo.artifact.api.domain.bean.User; import com.hifo.artifact.api.service.UserService; import com.hifo.artifact.api.utils.JsonUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject; import com.hifo.artifact.api.utils.StringUtils; import com.hifo.artifact.api.utils.WebRequestUtils;

@Controller @RequestMapping("/wap") public class WXWapJumpController2 { private String defaultState="1"; private String scope="snsapi_userinfo"; private String appId="*****"; private String appSecret="**********";

@Autowired

UserService userService;

/**

* auth2.0第一步获取code

* retryFlag表示是否是第一次验证失败了,重新获取,

* 如果是的话,要把第一次redirect_url后面的code和statue参数先抹去

* [@throws](https://my.oschina.net/throws) IOException

*/

private void getCode(HttpServletRequest request,HttpServletResponse response,boolean retryFlag) throws IOException{

String path = request.getContextPath();

String basePath = request.getScheme() + "://"

+ request.getServerName() + path;

String returnUrl = basePath + "/wapjump/auth"+"?"+StringUtils.outputString(request.getQueryString());

if(retryFlag){

if(returnUrl.lastIndexOf("?code=")!=-1){

returnUrl=returnUrl.substring(0,returnUrl.lastIndexOf("?code="));

}else if(returnUrl.lastIndexOf("&code=")!=-1){

returnUrl=returnUrl.substring(0,returnUrl.lastIndexOf("&code="));

}

}

//returnUrl编码一下,不然会出现参数丢失

try {

returnUrl=URLEncoder.encode(returnUrl,"utf-8");

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

response.sendRedirect(String.format(

"https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect",

appId, returnUrl,scope,defaultState));

}

@GetMapping("/auth")

public void auth(HttpServletRequest request,HttpServletResponse response) throws Exception {

String backurl=request.getParameter("backurl");//url编码后的

String []codes=request.getParameterValues("code");

String []states=request.getParameterValues("state");

String code=null;

String state=null;

//取url中最后一个code参数

if(codes!=null&&codes.length!=0){

code=codes[codes.length-1];

}

//取url中最后一个state参数

if(states!=null&&states.length!=0){

state=states[states.length-1];

}

/************************************** 网页授权第一步,获取code *********************************************/

if (state == null||code==null) {

getCode(request,response,false);

/************* 网页授权第二步,获取accesstoken(非普通accesstoken)和openid(snsapi_userinfo) *******************/

} else {

String json=WebRequestUtils.sendHttpGet(String.format(

"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",

appId, appSecret, code),"utf-8");

JSONObject ar=JSONObject.parseObject(json);

if(StringUtils.outputString(ar.get("errcode")).equals("40029")){

//重新走auth2.0第一步获取code

getCode(request,response,true);

}else{

String open_id = ar.getString("openid");

//获取unionId

//这里不能调用cgi接口,因为cgi接口只能获取*已关注用户的头像等信息

String userInfo_json=WebRequestUtils.sendHttpGet(String.format(

"https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN",ar.getString("access_token"),open_id

),"utf-8");

JSONObject userInfo=JSONObject.parseObject(userInfo_json);

String unionId=userInfo.getString("unionid");

User user = JsonUtil.jsonToPojo(userInfo_json,User.class);

//数据入库(不要重复入库)

//TODO

System.out.println(open_id);

System.out.println(unionId);

//根据公众号放回的UnionId判断该用户是否存在

User userSelect = userService.selectUserByUid(user.getUnionId());

if(userSelect!=null){

if(userSelect.getToken()==null){

userSelect.setToken(user.getOpenId());

userService.updateUserById(userSelect);

}

}else{

String id = UUID.randomUUID().toString();

user.setId(id);

user.setFreeTimes(50);

user.setQueryTimes(0);

user.setOpenId("");

user.setToken(user.getOpenId());

userService.save(user);

}

response.sendRedirect(URLDecoder.decode(backurl, "utf-8"));

}

}

}

}

转载至链接:https://my.oschina.net/zzp123456/blog/1840122

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值