java实现,企业微信获取token然后根据手机号获取用户id

 

import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

//模拟浏览器发送http请求完成固定地址的请求
public class QyWxUtils {
   private static final CloseableHttpClient httpclient = HttpClients.createDefault();
   //获取企业微信的企业号,根据不同企业更改
   private final static String CORPID = "你的企业id";
   //获取企业应用的密钥,根据不同应用更改
   private final static String CORPSECRET = "你的企业密匙";
   //获取访问权限码URL 接口是固定的
   private final static String ACCESS_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
   // 调用手机号调用账号接口 是固定的
   private final static String GET_URSRID_URL = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token=";
   // 根据手机号 得到用户账号
   public static String GetUserID(String mobile,String token){
      String url=GET_URSRID_URL + token;
      JSONObject json = new JSONObject();
      json.put("mobile", mobile);
      DefaultHttpClient client = new DefaultHttpClient();
      HttpPost post = new HttpPost(url);
      JSONObject response = null;
      try {
         StringEntity s = new StringEntity(json.toString());
         s.setContentEncoding("UTF-8");
         s.setContentType("application/json");//发送json数据需要设置contentType
         post.setEntity(s);
         HttpResponse res = client.execute(post);
         if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
            HttpEntity entity = res.getEntity();
            String result = EntityUtils.toString(res.getEntity());// 返回json格式:
            response = JSONObject.fromObject(result);
         }
      } catch (Exception e) {
         throw new RuntimeException(e);
      }
      return (String) response.get("userid");
   }
   // 获取token
   public static String GetToken(String corpid,String corpsecret) {
      Map<String, String> header = new HashMap<>();
      header.put("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
      String url=ACCESS_TOKEN_URL + "?corpid=" + corpid + "&corpsecret=" + corpsecret;
      HttpGet httpGet = new HttpGet(url);
      //设置头部
      for(Map.Entry entry:header.entrySet()){
         httpGet.setHeader(entry.getKey().toString(),entry.getValue().toString());
      }
      CloseableHttpResponse response = null;
      try {
         response = httpclient.execute(httpGet);
      } catch (IOException e1) {
         e1.printStackTrace();
      }
      String result = null;
      try {
         HttpEntity entity = response.getEntity();
         if (entity != null) {
            result = EntityUtils.toString(entity);
         }
      } catch (ParseException | IOException e) {
         e.printStackTrace();
      } finally {
         try {
            response.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }
      JSONObject jsonObject = JSONObject.fromObject(result);
      String access_token = (String) jsonObject.get("access_token");
      return access_token;
   }

   public static void main(String[] args) throws Exception {
      String token = GetToken(CORPID, CORPSECRET);
      String userID = GetUserID("你的手机号", token);
      System.out.println("userID = " + userID);
   }
}

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
A: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.util.Map; public class WeChatHelper { private static final String APP_ID = "Your_App_ID"; // 你的微信应用ID private static final String APP_SECRET = "Your_App_Secret"; // 你的微信应用秘钥 /** * 获取微信用户手机号 * @param code 微信用户登录后获取到的code * @return 手机号 */ public static String getPhoneNumber(String code) { StringBuilder sb = new StringBuilder(); try { // 获取access_token String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+APP_ID+"&secret="+APP_SECRET+"&code="+code+"&grant_type=authorization_code"; URL url = new URL(accessTokenUrl); URLConnection conn = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { sb.append(line); } in.close(); Map<String,String> tokenMap = JSON.parseObject(sb.toString(), new TypeReference<Map<String, String>>(){}); // 获取用户信息 String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+tokenMap.get("access_token")+"&openid="+tokenMap.get("openid")+"&lang=zh_CN"; url = new URL(userInfoUrl); conn = url.openConnection(); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); sb = new StringBuilder(); while ((line = in.readLine()) != null) { sb.append(line); } in.close(); Map<String,String> userMap = JSON.parseObject(sb.toString(), new TypeReference<Map<String, String>>(){}); // 返回手机号 return userMap.get("phone_number"); } catch (Exception e) { e.printStackTrace(); return ""; } } } ``` 使用方法: ```java String code = "xxxxxxxxxxxxxxxxxxxxx"; // 微信用户登录后获取到的code String phoneNumber = WeChatHelper.getPhoneNumber(code); // 获取用户手机号 ``` 注意事项: - 需要引入fastjson依赖; - 需要替换APP_ID和APP_SECRET变量为你自己的微信应用ID和秘钥; - 需要在微信开放平台设置授权回调域名,并将域名添加到小程序配置文件中。 - 需要在小程序端使用wx.login()方法获取用户登录的code。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值