You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
1.5 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.cyl.wechat;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.cyl.wechat.response.WechatUserAuth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
@Service
@Slf4j
public class WechatAuthService {
@Autowired
private RestTemplate restTemplate;
public WechatUserAuth getUserToken(String code) {
Map<String, String> params = new HashMap<>();
params.put("APPID", WechatPayData.appId);
params.put("SECRET", WechatPayData.secret);
params.put("CODE", code);
ResponseEntity<String> responseEntity = restTemplate.getForEntity(
"https://api.weixin.qq.com/sns/oauth2/access_token?appid={APPID}&secret={SECRET}&code={CODE}&grant_type=authorization_code",
String.class, params);
String body = responseEntity.getBody();
try {
WechatUserAuth object = JSON.parseObject(body, WechatUserAuth.class);
if (object == null) {
log.error("获取user wechat accesstoken失败");
return null;
}
log.info("get user wechat accesstoken{}",JSONUtil.toJsonStr(object));
return object;
} catch (Exception e) {
log.info("get user wechat accesstoken error",e);
}
return null;
}
}