فهرست منبع

微信登录功能

李天标 5 سال پیش
والد
کامیت
b72aa58e34

+ 5 - 0
pom.xml

@@ -47,6 +47,11 @@
 			<version>4.0.1.9</version>
 		</dependency>
 		<dependency>
+			<groupId>com.arronlong</groupId>
+			<artifactId>httpclientutil</artifactId>
+			<version>1.0.4</version>
+		</dependency>
+		<dependency>
 			<groupId>org.springframework.boot</groupId>
 			<artifactId>spring-boot-starter</artifactId>
 		</dependency>

+ 5 - 3
src/main/java/com/shawn/model/entity/TWeixin.java

@@ -25,7 +25,7 @@ public class TWeixin {
 	@ApiModelProperty(value="")
 	private String adminId;
 
-	@ApiModelProperty(value="")
+	@ApiModelProperty(value="微信开放id")
 	private String openId;
 
 	@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
@@ -38,12 +38,14 @@ public class TWeixin {
 	@ApiModelProperty(value="")
 	private Date modifyDate;
 
-	@ApiModelProperty(value="")
+	@ApiModelProperty(value="微信昵称")
 	private String nickName;
 
-	@ApiModelProperty(value="")
+	@ApiModelProperty(value="微信头像")
 	private String avatarUrl;
 
+
+
 	/**自定义统一方法设置主键**/
 	public void setPrimaryKey(Integer primaryKey) {
 		 setId(primaryKey);

+ 37 - 0
src/main/java/com/shawn/model/entity/weixinParm.java

@@ -0,0 +1,37 @@
+package com.shawn.model.entity;
+
+import com.fasterxml.jackson.annotation.JsonFormat;
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+import lombok.ToString;
+import lombok.experimental.Accessors;
+import org.springframework.format.annotation.DateTimeFormat;
+
+import java.util.Date;
+
+@Accessors(chain = true)
+@NoArgsConstructor
+@Getter
+@Setter
+@ToString
+public class weixinParm {
+
+    @ApiModelProperty(value="微信开放id")
+    private String openId;
+
+    @ApiModelProperty(value="微信昵称")
+    private String nickName;
+
+    @ApiModelProperty(value="微信头像")
+    private String avatarUrl;
+
+    @ApiModelProperty(value="用户名")
+    private String username;
+
+    @ApiModelProperty(value="密码")
+    private String password;
+
+
+}

+ 1 - 0
src/main/java/com/shawn/repository/TWeixinMapper.java

@@ -11,4 +11,5 @@ import com.shawn.model.param.TWeixinParam;
 import com.shawn.repository.base.BaseDaoInterface;
 
 public interface TWeixinMapper extends BaseDaoInterface<TWeixin,TWeixinExample,TWeixinParam, Integer>{
+    TWeixin findByEntity(TWeixin weiXin);
 }

+ 8 - 0
src/main/java/com/shawn/service/impl/TWeixinServiceImpl.java

@@ -14,6 +14,9 @@ import com.shawn.model.param.TWeixinParam;
 import com.shawn.repository.TWeixinMapper;
 import com.shawn.service.base.BaseService;
 import com.shawn.service.interfac.TWeixinServiceInterface;
+
+import java.util.List;
+
 @Service
 public class TWeixinServiceImpl extends BaseService<TWeixin,TWeixinExample,TWeixinParam,Integer> implements TWeixinServiceInterface{
 	@Autowired
@@ -28,4 +31,9 @@ public class TWeixinServiceImpl extends BaseService<TWeixin,TWeixinExample,TWeix
 		return "TWeixin";
 	}
 
+	@Override
+	public TWeixin findByEntity(TWeixin weiXin) {
+
+		return tWeixinMapper.findByEntity(weiXin);
+	}
 }

+ 3 - 0
src/main/java/com/shawn/service/interfac/TWeixinServiceInterface.java

@@ -10,5 +10,8 @@ import com.shawn.model.entity.TWeixinExample;
 import com.shawn.model.param.TWeixinParam;
 import com.shawn.service.base.BaseServiceInterface;
 
+import java.util.List;
+
 public interface TWeixinServiceInterface extends BaseServiceInterface<TWeixin,TWeixinExample,TWeixinParam,Integer>{
+   TWeixin findByEntity(TWeixin weiXin);
 }

+ 265 - 0
src/main/java/com/shawn/util/HttpClientUtil.java

@@ -0,0 +1,265 @@
+package com.shawn.util;
+
+import org.apache.http.Header;
+import org.apache.http.HttpEntity;
+import org.apache.http.NameValuePair;
+import org.apache.http.client.entity.UrlEncodedFormEntity;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.message.BasicNameValuePair;
+import org.apache.http.util.EntityUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public class HttpClientUtil {
+
+
+
+    private static final Logger log = LoggerFactory.getLogger(HttpClientUtil.class);
+
+
+
+    public static String UTF8 = "UTF-8";
+
+
+
+    public static String httpPost(String url, Map<String, String> params, String encoding) throws Exception {
+
+        log.debug("收到HTTP POST请求");
+
+
+
+        String result = "";
+
+// 创建默认的httpClient实例.
+
+        CloseableHttpClient httpclient = HttpClients.createDefault();
+
+// 创建httppost
+
+        HttpPost httppost = new HttpPost(url);
+
+
+
+//参数
+
+        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
+
+        if (params != null) {
+
+            log.debug("发送post参数");
+
+            Set<String> keys = params.keySet();
+
+
+
+            for (String key : keys) {
+
+                log.debug("param:" + key);
+
+                formparams.add(new BasicNameValuePair(key, params.get(key)));
+
+            }
+
+
+
+        }
+
+
+
+        UrlEncodedFormEntity uefEntity;
+
+        try {
+
+            uefEntity = new UrlEncodedFormEntity(formparams, encoding);
+
+            httppost.setEntity(uefEntity);
+
+
+
+            log.debug("executing request " + httppost.getURI());
+
+
+
+            CloseableHttpResponse response = httpclient.execute(httppost);
+
+
+
+            try {
+
+                log.debug("返回HTTP状态:" + response.getStatusLine());
+
+
+
+                Header[] headers = response.getAllHeaders();
+
+
+
+                log.debug("返回HTTP头");
+
+                log.debug("--------------------------------------");
+
+                for (Header header : headers) {
+
+                    log.debug(header.getName() + "-->" + header.getValue());
+
+                }
+
+                log.debug("--------------------------------------");
+
+
+
+                HttpEntity entity = response.getEntity();
+
+                if (entity != null) {
+
+                    result = EntityUtils.toString(entity, encoding);
+
+                    log.debug("--------------------------------------");
+
+                    log.debug("Response content: " + result);
+
+                    log.debug("--------------------------------------");
+
+                }
+
+
+
+            } finally {
+
+                response.close();
+
+            }
+
+        } catch (IOException e) {
+
+            throw e;
+
+        } finally {
+
+// 关闭连接,释放资源
+
+            try {
+
+                httpclient.close();
+
+            } catch (IOException e) {
+
+            }
+
+        }
+
+
+
+        return result;
+
+    }
+
+
+
+    public static String httpGet(String url, String encoding) throws Exception {
+
+
+
+        log.debug("收到HTTP GET请求");
+
+
+
+        String result = "";
+
+
+
+        CloseableHttpClient httpclient = HttpClients.createDefault();
+
+        try {
+
+// 创建httpget.
+
+            HttpGet httpget = new HttpGet(url);
+
+            log.debug("executing request " + httpget.getURI());
+
+// 执行get请求.
+
+            CloseableHttpResponse response = httpclient.execute(httpget);
+
+            try {
+
+
+
+                log.debug("返回HTTP状态:" + response.getStatusLine());
+
+
+
+                Header[] headers = response.getAllHeaders();
+
+
+
+                log.debug("返回HTTP头");
+
+                log.debug("--------------------------------------");
+
+                for (Header header : headers) {
+
+                    log.debug(header.getName() + "-->" + header.getValue());
+
+                }
+
+                log.debug("--------------------------------------"); // 获取响应实体
+
+                HttpEntity entity = response.getEntity();
+
+                if (entity != null) {
+
+                    result = EntityUtils.toString(entity, encoding);
+
+// 打印响应内容
+
+                    log.debug("Response content: " + result);
+
+                }
+
+                log.debug("------------------------------------");
+
+            } finally {
+
+                response.close();
+
+            }
+
+        } catch (Exception e) {
+
+            throw e;
+
+        } finally {
+
+// 关闭连接,释放资源
+
+            try {
+
+                httpclient.close();
+
+            } catch (IOException e) {
+
+            }
+
+        }
+
+        return result;
+
+
+
+    }
+
+
+
+}

+ 44 - 0
src/main/java/com/shawn/util/WeChatUtil.java

@@ -0,0 +1,44 @@
+package com.shawn.util;
+
+import javax.net.ssl.HttpsURLConnection;
+import java.io.BufferedReader;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.net.URL;
+
+public class WeChatUtil {
+
+    public static String httpRequest(String requestUrl,String requestMethod,String output){
+        try{
+            URL url = new URL(requestUrl);
+            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
+            connection.setDoOutput(true);
+            connection.setDoInput(true);
+            connection.setUseCaches(false);
+            if(null != output){
+                OutputStream outputStream = connection.getOutputStream();
+                outputStream.write(output.getBytes("utf-8"));
+                outputStream.close();
+            }
+            // 从输入流读取返回内容
+            InputStream inputStream = connection.getInputStream();
+            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
+            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
+            String str = null;
+            StringBuffer buffer = new StringBuffer();
+            while ((str = bufferedReader.readLine()) != null){
+                buffer.append(str);
+            }
+            bufferedReader.close();
+            inputStreamReader.close();
+            inputStream.close();
+            inputStream = null;
+            connection.disconnect();
+            return buffer.toString();
+        }catch(Exception e){
+            e.printStackTrace();
+        }
+        return "";
+    }
+}

+ 3 - 8
src/main/java/com/shawn/web/controller/TAdminController.java

@@ -5,19 +5,14 @@
 
 package com.shawn.web.controller;
 
-import java.util.Date;
-import java.util.List;
-import java.util.Optional;
+import java.util.*;
+
 
-import com.shawn.util.FgObjectUtil;
 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.PostMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
 
 import com.shawn.model.dto.ResultMessage;
 import com.shawn.web.controller.base.BaseController;

+ 136 - 8
src/main/java/com/shawn/web/controller/TWeixinController.java

@@ -6,20 +6,21 @@
 package com.shawn.web.controller;
 
 import java.util.Date;
+import java.util.List;
 
+import com.alibaba.fastjson.JSONObject;
+import com.shawn.model.entity.*;
+import com.shawn.service.interfac.TAdminServiceInterface;
+import com.shawn.util.WeChatUtil;
+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.PostMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
 
 import com.shawn.model.dto.ResultMessage;
 import com.shawn.web.controller.base.BaseController;
 import com.shawn.web.exception.MyException;
-import com.shawn.model.entity.TWeixin;
-import com.shawn.model.entity.TWeixinExample;
 import com.shawn.model.param.TWeixinParam;
 import com.shawn.service.interfac.TWeixinServiceInterface;
 
@@ -35,10 +36,137 @@ public class TWeixinController extends BaseController<TWeixin,TWeixinExample,TWe
 		super(service);
 	}
 
+    @Autowired
+    private TAdminServiceInterface tAdminService;
+
 	@Override
 	protected TWeixinExample createNewExample() {
 		return new TWeixinExample();
 	}
-	
-    
+	/**
+	 * 微信登录
+	 * @param
+	 * @return
+	 */
+	@PostMapping("/weiXinLogin")
+	public ResponseEntity<?> weiXinLogin(@RequestBody TWeixin weiXin) {
+        TWeixin tWeixin = tWeixinService.findByEntity(weiXin);
+        if(tWeixin!=null){
+            String adminId = tWeixin.getAdminId();
+            if(adminId.length()>0){
+                TAdminExample example = new TAdminExample();
+                TAdminExample.Criteria criteria = example.createCriteria();
+                criteria.andIdEqualTo(Long.valueOf(adminId));
+                List<TAdmin> list = tAdminService.selectByOption(example);
+                if(list.size()>0){
+                    tWeixin.setModifyDate(new Date());
+                    tWeixin.setNickName(weiXin.getNickName());
+                    tWeixin.setAvatarUrl(weiXin.getAvatarUrl());
+                    tWeixinService.updateById(tWeixin);
+                    return ResponseEntity.status(HttpStatus.OK)
+                            .body(new ResultMessage().setCode(true).setData(list.get(0)).setMessage("SUCCESS"));
+                }
+            }
+        }else {
+            return ResponseEntity.status(HttpStatus.OK)
+                    .body(new ResultMessage().setCode(true).setData(weiXin).setMessage("off"));
+        }
+
+
+        return null;
+
+	}
+    /**
+     * 微信注册
+     * @param
+     * @return
+     */
+    @PostMapping("/weiXinZhuce")
+    public ResponseEntity<?> weiXinZhuce(@RequestBody weixinParm weiXin) {
+        // 检查必输项
+        if(StringUtils.isEmpty(weiXin.getUsername())||StringUtils.isEmpty(weiXin.getPassword())){
+            throw new MyException("用户名密码不能为空");
+        }
+        TAdminExample example = new TAdminExample();
+        TAdminExample.Criteria criteria = example.createCriteria();
+        criteria.andUsernameEqualTo(weiXin.getUsername());
+        criteria.andPasswordEqualTo(weiXin.getPassword());
+        List<TAdmin> list = tAdminService.selectByOption(example);
+        if(list.size()>0){
+            Long adminId = list.get(0).getId();
+            TWeixin newWeixin = new TWeixin();
+            String adminid = String.valueOf(adminId);
+            newWeixin.setAdminId(adminid);
+            newWeixin.setNickName(weiXin.getNickName());
+            newWeixin.setAvatarUrl(weiXin.getAvatarUrl());
+            newWeixin.setOpenId(weiXin.getOpenId());
+            newWeixin.setCreateDate(new Date());
+            newWeixin.setModifyDate(new Date());
+            Integer integer = tWeixinService.insert(newWeixin);
+            return ResponseEntity.status(HttpStatus.OK)
+                    .body(new ResultMessage().setCode(true).setData(list.get(0)).setMessage("SUCCESS"));
+        }
+        return ResponseEntity.status(HttpStatus.OK)
+                .body(new ResultMessage().setCode(false).setData(null).setMessage("用户名或密码错误"));
+    }
+    /**
+     * 微信注册
+     * @param
+     * @return
+     */
+    @PostMapping("/weiXinSearch")
+    public ResponseEntity<?> weiXinSearch(@RequestBody TWeixin weiXin) {
+        TWeixinExample example = new TWeixinExample();
+        TWeixinExample.Criteria criteria = example.createCriteria();
+        criteria.andAdminIdEqualTo(weiXin.getAdminId());
+        List<TWeixin> tWeixins = tWeixinService.selectByOption(example);
+        if(tWeixins.size()>0){
+            return ResponseEntity.status(HttpStatus.OK)
+                    .body(new ResultMessage().setCode(true).setData(tWeixins).setMessage("SUCCESS"));
+        }else {
+            return ResponseEntity.status(HttpStatus.OK)
+                    .body(new ResultMessage().setCode(true).setData(null).setMessage("没有绑定微信"));
+        }
+    }
+
+    /**
+     * 解除微信绑定
+     * @param
+     * @return
+     */
+    @PostMapping("/deleteWeixin")
+    public ResponseEntity<?> deleteWeixin(@RequestBody TWeixin weiXin) {
+
+        Integer integer = tWeixinService.deleteById(weiXin.getId());
+
+        return ResponseEntity.status(HttpStatus.OK)
+                    .body(new ResultMessage().setCode(true).setData(integer).setMessage("SUCCESS"));
+    }
+
+    /**
+     * 获取微信openid
+     * @param
+     * @return
+     */
+    @GetMapping("/getOpenid")
+    public ResponseEntity<?> getOpenid(String code) {
+        // 微信小程序ID
+        String appid = "wx3844925af1740a7d";
+        // 微信小程序秘钥
+        String secret = "c1f0363a78d1c580388d6c4f14674733";
+
+        // 根据小程序穿过来的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();
+        return ResponseEntity.status(HttpStatus.OK)
+                .body(new ResultMessage().setCode(true).setData(openid).setMessage("SUCCESS"));
+
+    }
 }

+ 6 - 0
src/main/resources/com/shawn/repository/mybatis/TWeixinMapper.xml

@@ -99,6 +99,12 @@
     from t_weixin
     where id = #{id,jdbcType=INTEGER}
   </select>
+  <select id="findByEntity" parameterType="com.shawn.model.entity.TWeixin" resultMap="BaseResultMap">
+    select
+    <include refid="Base_Column_List" />
+    from t_weixin
+    where open_id = #{openId,jdbcType=VARCHAR}
+  </select>
   <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
     delete from t_weixin
     where id = #{id,jdbcType=INTEGER}