package com.szwl.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.szwl.constant.ResponseCodesEnum;
import com.szwl.model.bo.R;
import com.szwl.model.bo.ResponseModel;
import com.szwl.model.entity.TSzsmWx;
import com.szwl.model.utils.HttpClientSslUtils;
import com.szwl.model.utils.JsonUtil;
import com.szwl.model.utils.WeChatUtil;
import com.szwl.service.TSzsmWxService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
/**
*
* 前端控制器
*
*
* @author wuhs
* @since 2022-10-20
*/
@RestController
@RequestMapping("/tSzsmWx")
public class TSzsmWxController {
@Autowired
TSzsmWxService szsmWxService;
/**
* 获取微信openid
* @param
* @return
*/
@GetMapping("/getOpenid")
public ResponseModel> getOpenid(String code) {
// 微信小程序ID
String appid = "wx5071443e63295c29";
// 微信小程序秘钥
String secret = "191b2fb5ad897c53aff19d2b40d677da";
// 根据小程序穿过来的code想这个url发送请求
String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
// 发送请求,返回Json字符串
String str = WeChatUtil.httpRequest(url, "GET", null);
// 转成Json对象 获取openid
JSONObject jsonObject = JSONObject.parseObject(str);
// 我们需要的openid,在一个小程序中,openid是唯一的
String openid = jsonObject.get("openid").toString();
//根据openid去创建账户
if(StringUtils.isNotEmpty(openid)){
//查找是否已注册
LambdaQueryWrapper query = Wrappers.lambdaQuery();
query.eq(TSzsmWx::getOpenId,openid);
List list = szsmWxService.list(query);
if(list.size()>0){
return R.ok(list.get(0));
}else {
TSzsmWx wx = new TSzsmWx();
wx.setCreateDate(new Date());
wx.setModifyDate(new Date());
wx.setOpenId(openid);
szsmWxService.save(wx);
return R.ok(wx);
}
}
return R.ok();
}
/**
* 获取微信openid
* @param
* @return
*/
@GetMapping("/getPhone")
public ResponseModel> getPhone(String code,String id) {
// 微信小程序ID
String appid = "wx5071443e63295c29";
// 微信小程序秘钥
String secret = "191b2fb5ad897c53aff19d2b40d677da";
// //1,获取获取token
// String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
// JSONObject token = null;
// try {
// token = JSON.parseObject(HttpClientSslUtils.doGet(token_url));
// } catch (Exception e) {
// e.printStackTrace();
// }
// if (token == null) {
// return R.ok("获取token失败");
// }
// String accessToken = token.getString("access_token");
// if (StringUtils.isEmpty(accessToken)) {
// return R.ok("获取token失败");
// }
String accessToken =null;
TSzsmWx wx = szsmWxService.getById(1);
accessToken = wx.getAvatarUrl();
//获取phone
String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber"
+ "?access_token=" + accessToken;
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", code);
String reqJsonStr = JsonUtil.objToString(jsonObject);
JSONObject phoneObject = null;
try {
phoneObject = JSON.parseObject(HttpClientSslUtils.doPost(url, reqJsonStr));
if (phoneObject != null) {
String errmsg = phoneObject.getString("errmsg");
if(errmsg.equals("ok")){
String phone_info = phoneObject.getString("phone_info");
JSONObject phoneInfo = JSONObject.parseObject(phone_info);
String phoneNumber = phoneInfo.getString("phoneNumber");
if(StringUtils.isNotEmpty(phoneNumber)){
TSzsmWx szsmWx = szsmWxService.getById(id);
szsmWx.setPhone(phoneNumber);
szsmWxService.save(szsmWx);
return R.ok(szsmWx);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (phoneObject == null) {
return R.ok("获取手机号失败");
}
return R.ok();
}
/**
* 获取不限制的小程序码
* @param
* @return
*/
@GetMapping("/getQRCode")
public ResponseModel> getQRCode(String clientId) {
if(StringUtils.isEmpty(clientId)){
return R.fail(ResponseCodesEnum.A0001);
}
// 微信小程序ID
String appid = "wx5071443e63295c29";
// 微信小程序秘钥
String secret = "191b2fb5ad897c53aff19d2b40d677da";
String accessToken =null;
TSzsmWx wx = szsmWxService.getById(1);
accessToken = wx.getAvatarUrl();
//获取phone
String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
JSONObject jsonObject = new JSONObject();
jsonObject.put("scene", clientId);
String reqJsonStr = JsonUtil.objToString(jsonObject);
JSONObject phoneObject = null;
try {
String s = httpPostWithJSON(url, reqJsonStr);
if(StringUtils.isEmpty(s)){
return R.fail("获取失败");
}else {
return R.ok(s);
}
} catch (Exception e) {
e.printStackTrace();
}
if (phoneObject == null) {
return R.fail("获取失败");
}
return R.ok();
}
public static String httpPostWithJSON(String url, String json)
throws Exception {
String result = null;
URL target = new URL(url);
try {
HttpURLConnection httpURLConnection = (HttpURLConnection) target.openConnection();
httpURLConnection.setRequestMethod("GET");// 提交模式
// 发送POST请求必须设置如下两行
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
// 获取URLConnection对象对应的输出流
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
printWriter.write(json.toString());
// flush输出流的缓冲
printWriter.flush();
InputStream instreams = httpURLConnection.getInputStream();
byte[] dest = new byte[1024];
byte[] bytes = new byte[httpURLConnection.getContentLength()];
int len;
int sum = 0;
while ((len = instreams.read(dest)) != -1) {
System.arraycopy(dest, 0, bytes, sum, len);
if (sum == httpURLConnection.getContentLength()) {
break;
} else {
sum = sum + len;
}
}
// 6. 断开连接,释放资源
httpURLConnection.disconnect();
// 将文件中的内容读入到数组中
Base64.Encoder encode = Base64.getEncoder();
result = "data:image/jpeg;base64,"+encode.encodeToString(bytes);
} catch (Exception e) {
}
return result;
}
}