准备工作
1,去申请微信测试公众号,地址:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
使用微信登陆,获得测试的appid和secret(重点)
再把前端的ip和端口写在账号授权这边
2,在项目的yml文件把appid和secret写进yml文件,或者也可以配置在配置文件里面,我这边用@value读取。
application.yml
wx: # 测试公众号 appid: wx580cacbdb7b4a2a7 secret: 8520645c735581232d26dcdecff1b9d5
3,新建配置文件wxConfig.java
@Component public class wxConfig { /** * appid 读取application.yml */ @Value("${wx.appid}") private String appid ; /** * secret 读取application.yml */ @Value("${wx.secret}") private String secret ; public String getAppid() { return appid; } public void setAppid(String appid) { this.appid = appid; } public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } }
4,新建HttpClientUtuil.java
public class HttpClientUtil { public static String doGet(String url, Map<String, String> param) { // 创建Httpclient对象 CloseableHttpClient httpclient = HttpClients.createDefault(); String resultString = ""; CloseableHttpResponse response = null; try { // 创建uri URIBuilder builder = new URIBuilder(url); if (param != null) { for (String key : param.keySet()) { builder.addParameter(key, param.get(key)); } } URI uri = builder.build(); // 创建http GET请求 HttpGet httpGet = new HttpGet(uri); // 执行请求 response = httpclient.execute(httpGet); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { resultString = EntityUtils.toString(response.getEntity(), "UTF-8"); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } public static String doGet(String url) { return doGet(url, null); } public static String doPost(String url, Map<String, String> param) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建参数列表 if (param != null) { List<NameValuePair> paramList = new ArrayList<>(); for (String key : param.keySet()) { paramList.add(new BasicNameValuePair(key, param.get(key))); } // 模拟表单 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList); httpPost.setEntity(entity); } // 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; } public static String doPost(String url) { return doPost(url, null); } public static String doPostJson(String url, String json) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建请求内容 StringEntity entity = new StringEntity(json, String.valueOf(ContentType)); httpPost.setEntity(entity); // 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } return resultString; }
5,因为项目是前后端分离的项目,前端用appid把code拿到传给后端,所以只展示用code获取accesstoken,再用accesstoken换取wxUser
新建WxController.java
@ApiOperation(value = "微信登陆") // @ApiImplicitParams({ // @ApiImplicitParam(name = "userPhone", value = "手机号码", required = true, dataType = "String"), // @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String") // }) @RequestMapping(value = "wxlogin", method = RequestMethod.POST) public Object wxCallBack(HttpServletRequest request, HttpServletResponse response ) throws IOException { DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); JSONObject jsonObject = new JSONObject(); //跟前端说把code放在请求体里面 String code = request.getParameter("code"); //获取access_token String url = "https://api.weixin.qq.com/sns/oauth2/access_token" + "?appid=" + wxConfig.getAppid()+ "&secret=" + wxConfig.getSecret() + "&code=" + code + "&grant_type=authorization_code"; String result = HttpClientUtil.doGet(url); //返回结果的json对象 JSONObject resultObject = JSON.parseObject(result); //请求获取userInfo String infoUrl = "https://api.weixin.qq.com/sns/userinfo" + "?access_token=" + resultObject.getString("access_token") + "&openid=" + resultObject.getString("openid") + "&lang=zh_CN"; String resultInfo = HttpClientUtil.doGet(infoUrl); //此时已获取到userInfo,再根据业务进行处理 JSONObject wxuse = JSON.parseObject(resultInfo); user user = userServer. userByopenid(wxuse.getString("openid")); if (user != null ||"".equals(user)){ //这边省略 JWT的token签发,和user服务,如不知道token如何签发,请看我这篇博客:https://www.achinblog.cn/?id=6 String token = JWT.generateToken(sgymagent.getId()); //对用户的密码进行处理 user.setPassword(""); jsonObject.put("token", token); jsonObject.put("state", "1"); jsonObject.put("user", user); jsonObject.put("msg", "登陆成功"); }else { jsonObject.put("state", "0"); } return jsonObject; }
到此,微信登陆就做完了,下面是实现微信消息推送
使用的第三方SDK是weixin-java-mp,maven地址:
<dependency> <groupId>com.github.binarywang</groupId> <artifactId>weixin-java-mp</artifactId> <version>2.7.0</version> </dependency>
在测试公众号里面新建测试模板
{{first.DATA}}
付款金额:{{keyword1.DATA}}
交易单号:{{keyword2.DATA}}
{{remark.DATA}}
新建PushMessageServer
public interface PushMessageService { void templateOrderStatus(); }
实现类
public class PushMessageServiceImpl implements PushMessageService { @Autowired wxConfig wxConfig; @Override public void templateOrderStatus() { //1,配置 WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage(); wxStorage.setAppId(wxConfig.getAppid());//appid wxStorage.setSecret(wxConfig.getSecret());//appsecret WxMpService wxMpService = new WxMpServiceImpl(); wxMpService.setWxMpConfigStorage(wxStorage); //推送消息 WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder() .toUser(openid)//要推送的用户openid .templateId("iEhR8oomRvtai6TMklblddPC6qhux6_WiwwJtLd888")//模板id .url("http://www.baidu.com")//点击模板消息要访问的网址 .build(); //3,如果是正式版发送消息,,这里需要配置你的信息 templateMessage.addWxMpTemplateData(new WxMpTemplateData("first", "您的订单已完成付款,商家将即时为您发货。", "000000")); templateMessage.addWxMpTemplateData(new WxMpTemplateData("keyword1","555.99", "#000000")); templateMessage.addWxMpTemplateData(new WxMpTemplateData("keyword2","456789876543567898765", "#000000")); templateMessage.addWxMpTemplateData(new WxMpTemplateData("remark","谢谢惠顾!", "#000000")); try { String msg = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage); System.out.println("推送成功:" + msg); } catch (Exception e) { System.out.println("推送失败:" + e.getMessage()); e.printStackTrace(); } }
至此推送就做好了,如有疑问欢迎留言
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。