Browse Source

微信公众号服务配置-关注用户更新unionId

chao 3 years ago
parent
commit
582e8b32be

+ 39 - 1
src/main/java/com/caimei365/wechat/controller/WechatDebugApi.java

@@ -1,13 +1,20 @@
 package com.caimei365.wechat.controller;
 
+import com.alibaba.fastjson.JSONObject;
+import com.caimei365.wechat.dao.WeChatDao;
+import com.caimei365.wechat.entity.WeChatUser;
 import com.caimei365.wechat.utils.HttpUtil;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Value;
+import org.springframework.util.StringUtils;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.PostMapping;
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RestController;
 
+import javax.annotation.Resource;
+import java.util.List;
+
 /**
  * 微信接口调试API
  *
@@ -20,7 +27,12 @@ public class WechatDebugApi {
 
     @Value("${wechat.apiUrl}")
     private String wechatApiUrl;
-
+    @Value("${wechat.caimei.appid}")
+    private String caimeiAppid;
+    @Value("${wechat.caimei.secret}")
+    private String caimeiSecret;
+    @Resource
+    private WeChatDao weChatDao;
     /**
      * 获取微信 access_token
      */
@@ -56,4 +68,30 @@ public class WechatDebugApi {
         log.info("【微信接口调试】公众号迁移后更新OpenId:{}", result);
         return result;
     }
+
+    /**
+     * 关注用户更新unionId
+     */
+    @PostMapping("/wechat/debug/user/union")
+    public String changeOpenId(String token) {
+        List<WeChatUser> userList = weChatDao.getWeChatUserList();
+        for (WeChatUser user : userList) {
+            if(!StringUtils.hasLength(user.getUnionId())) {
+                String openid = user.getOpenid();
+                try {
+                    // 获取用户unionId:/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
+                    String unionIdUrl = wechatApiUrl + "/cgi-bin/user/info?access_token="+ token + "&openid=" + openid + "&lang=zh_CN";
+                    String result2 = HttpUtil.httpRequest(unionIdUrl, "GET", null);
+                    log.info("openid:" + openid + ",获取用户unionId:" + result2);
+                    JSONObject parse2 = JSONObject.parseObject(result2, JSONObject.class);
+                    String unionId = parse2.getString("unionid");
+                    user.setUnionId(unionId);
+                    weChatDao.updateWeChatUser(user);
+                } catch (Exception e) {
+                    log.error("获取unionId失败:", e);
+                }
+            }
+        }
+        return "【微信接口调试】关注用户更新unionId";
+    }
 }

+ 13 - 0
src/main/java/com/caimei365/wechat/dao/WeChatDao.java

@@ -1,5 +1,6 @@
 package com.caimei365.wechat.dao;
 
+import com.caimei365.wechat.entity.WeChatUser;
 import com.caimei365.wechat.entity.WechatArticleDetail;
 import com.caimei365.wechat.entity.WechatReply;
 import org.apache.ibatis.annotations.Mapper;
@@ -31,4 +32,16 @@ public interface WeChatDao {
      * 根据ID获取文本内容
      */
     String getTextContent(Integer id);
+
+    /**
+     * 获取微信用户
+     */
+    WeChatUser getWeChatUserByOpenid(String openid);
+    List<WeChatUser> getWeChatUserList();
+
+    /**
+     * 保存关注用户
+     */
+    void insertWeChatUser(WeChatUser user);
+    void updateWeChatUser(WeChatUser user);
 }

+ 26 - 0
src/main/java/com/caimei365/wechat/entity/WeChatUser.java

@@ -0,0 +1,26 @@
+package com.caimei365.wechat.entity;
+
+import lombok.Data;
+
+/**
+ * Description
+ *
+ * @author : Charles
+ * @date : 2022/3/8
+ */
+@Data
+public class WeChatUser {
+    private static final long serialVersionUID = 1L;
+    /**
+     * id
+     */
+    private Integer id;
+    /**
+     * openid
+     */
+    private String openid;
+    /**
+     * unionId
+     */
+    private String unionId;
+}

+ 34 - 0
src/main/java/com/caimei365/wechat/service/impl/WechatServerServiceImpl.java

@@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
 import com.caimei365.wechat.dao.WeChatDao;
 import com.caimei365.wechat.entity.WeChatConstant;
+import com.caimei365.wechat.entity.WeChatUser;
 import com.caimei365.wechat.entity.WechatArticleDetail;
 import com.caimei365.wechat.entity.WechatReply;
 import com.caimei365.wechat.service.WechatServerService;
@@ -34,6 +35,8 @@ import java.util.Map;
 @Service
 public class WechatServerServiceImpl implements WechatServerService {
 
+    @Value("${wechat.apiUrl}")
+    private String wechatApiUrl;
     @Value("${caimei.wwwDomain}")
     private String wwwDomain;
     @Value("${caimei.coreDomain}")
@@ -236,6 +239,37 @@ public class WechatServerServiceImpl implements WechatServerService {
     public String handleSubscribeMsg(Map<String, String> requestMap) {
         // 用户openid
         String openid = requestMap.get(WeChatConstant.FROM_USER_NAME);
+        String unionId = null;
+        WeChatUser user = weChatDao.getWeChatUserByOpenid(openid);
+        if (null == user || !StringUtils.hasLength(user.getUnionId())){
+            try {
+                // 获取 access_token
+                String url = wechatApiUrl + "/cgi-bin/token?grant_type=client_credential&appid=" + caimeiAppid + "&secret=" + caimeiSecret;
+                String result1 = HttpUtil.httpRequest(url, "GET", null);
+                JSONObject parse = JSONObject.parseObject(result1, JSONObject.class);
+                String token = parse.getString("access_token");
+                // 获取用户unionId
+                String unionIdUrl = wechatApiUrl + "/cgi-bin/user/info?access_token="+ token + "&openid=" + openid + "&lang=zh_CN";
+                String result2 = HttpUtil.httpRequest(unionIdUrl, "GET", null);
+                log.info("openid:" + openid + ",获取用户unionId:" + result2);
+                JSONObject parse2 = JSONObject.parseObject(result2, JSONObject.class);
+                unionId = parse2.getString("unionid");
+            } catch (Exception e) {
+                log.error("获取unionId失败:", e);
+            }
+        }
+        // 保存关注用户
+        if (null == user) {
+            user = new WeChatUser();
+            user.setOpenid(openid);
+            user.setUnionId(unionId);
+            weChatDao.insertWeChatUser(user);
+        } else {
+            if (!StringUtils.hasLength(user.getUnionId())) {
+                user.setUnionId(unionId);
+                weChatDao.updateWeChatUser(user);
+            }
+        }
         // 微信号公众号Id
         String wxType = requestMap.get(WeChatConstant.TO_USER_NAME);
         log.info(">>>>>>>>>>处理接收的订阅关注事件,openid:" + openid + ",wxType:" + wxType);

+ 3 - 3
src/main/resources/config/beta/application-beta.yml

@@ -35,9 +35,9 @@ wechat:
   apiUrl: https://api.weixin.qq.com
   publicUrl: https://mp.weixin.qq.com
   caimei:
-    id: gh_123456
-    appid: wx123456
-    secret: abc123456
+    id: gh_9b933597cef7
+    appid: wx0938e78f38bc203d
+    secret: a3b417fc249a964ad0df2813a1f19102
   hehe:
     id: gh_7890123
     appid: wx7890123

+ 12 - 0
src/main/resources/mapper/WeChatDao.xml

@@ -18,4 +18,16 @@
     <select id="getTextContent" resultType="java.lang.String">
         SELECT content FROM wechat_text WHERE id = #{id}
     </select>
+    <select id="getWeChatUserByOpenid" resultType="com.caimei365.wechat.entity.WeChatUser">
+        SELECT id, openid, unionId FROM wechat_user WHERE openid = #{openid}
+    </select>
+    <select id="getWeChatUserList" resultType="com.caimei365.wechat.entity.WeChatUser">
+        SELECT id, openid, unionId FROM wechat_user
+    </select>
+    <insert id="insertWeChatUser">
+        INSERT INTO wechat_user (openid, unionId)  VALUES (#{openid}, #{unionId})
+    </insert>
+    <update id="updateWeChatUser">
+        UPDATE wechat_user SET openid = #{openid}, unionId = #{unionId} WHERE id = #{id}
+    </update>
 </mapper>