1.微信小程序授权
controller 层代码
@Autowired
private WxUtils wxUtils;
//小程序 授权
@RequestMapping(value = "/wx/login", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
public Result login(@RequestParam("appId")String appId, @RequestParam("secret")String secret, @RequestParam("code")String code) {
Result result = new Result();
String s = wxUtils.code2Session(appId, secret, code);
result.setData(s);
result.success("success");
return result;
}
wxUtils 工具类
@Component
@Slf4j
public class WxUtils {
private final RestTemplate restTemplate;
{
restTemplate = new RestTemplate();
ResponseErrorHandler responseErrorHandler = new ResponseErrorHandler() {
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return false;
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
HttpStatus statusCode = response.getStatusCode();
String statusText = response.getStatusText();
log.info("【微信接口请求失败】 errorCode={},errorMsg={}", statusCode, statusText);
throw new ChannelException("微信网络繁忙,请稍后再试。");
}
};
restTemplate.setErrorHandler(responseErrorHandler);
}
/**
* @params: []
* @return: java.lang.String
* @Description: 获取用户openId
*/
public String code2Session(String appId, String secret, String code) {
//组装参数
Map<String, String> params = new HashMap<>();
params.put("appid", appId);
params.put("secret", secret);
params.put("code", code);
params.put("grant_type", "authorization_code");
StringBuilder sb = new StringBuilder(UrlConstants.WX_CODE_2_SESSION);
sb.append("?")
.append("appid=").append(appId).append("&")
.append("secret=").append(secret).append("&")
.append("js_code=").append(code).append("&")
.append("grant_type=").append("authorization_code");
String result = restTemplate.getForObject(sb.toString(), String.class);
JSONObject jsonResult = JSON.parseObject(result);
String openid = jsonResult.getString("openid");
if (StringUtils.isEmpty(openid)) {
log.error("【微信code2Session失败!】url={},Params:{},wxResult={}", sb.toString(), JSON.toJSONString(params), result);
throw new ChannelException("获取用户信息失败,请稍后再试。");
}
return jsonResult.getString("openid");
}
}
2.微信小程序,用户手机号获取
微信小程序,根据code(code为手机号获取凭证)获取用户加密手机号文章来源地址https://www.toymoban.com/news/detail-621457.html
获取用户手机号方法
//小程序 根据code 获取用户手机号
private String getPhoneNum(String code){
if (org.apache.commons.lang3.StringUtils.isNotBlank(code)){
//先获取access_token = appid + secret
HttpResponse response = HttpRequest.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret + "").execute();
JSONObject tokenJson = JSON.parseObject(response.body());
if(!tokenJson.containsKey("access_token")){
throw new RuntimeException("微信官方修改了获取access_token令牌接口!");//"501",
}
String accessToken = tokenJson.get("access_token").toString();
log.info("====[微信小程序获取用户手机号]====accessToken: "+accessToken);
//用 access_token + code 获取手机号
JSONObject jsonCode = new JSONObject();
jsonCode.put("code",code);
String resPhone = HttpUtil.post("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken, jsonCode.toString());
log.info("====[微信小程序获取用户手机号]====resPhone: "+resPhone);
if(org.springframework.util.StringUtils.isEmpty(resPhone) || !resPhone.contains("phone_info") || !resPhone.contains("phoneNumber")){
throw new RuntimeException("微信官方修改了小程序获取用户手机号码相关接口!");//"501",
}
JSONObject resPhoneInfo = JSON.parseObject(resPhone);
JSONObject phoneInfo=resPhoneInfo.getJSONObject("phone_info");
System.out.println(resPhoneInfo);
System.out.println(phoneInfo);
String phoneNumber = phoneInfo.get("phoneNumber").toString();
//return R.SUCCESS.setNewData(MapUtil.builder().put("phoneNumber",phoneNumber).build());
return phoneNumber;
}
return null;
}
文章来源:https://www.toymoban.com/news/detail-621457.html
到了这里,关于微信小程序:登录授权,根据手机号获取凭证,获取用户手机号的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!