java調用企業微信接口API發送消息(替代短信驗證碼的一種解決方案)

java調用企業微信接口API發送消息(替代短信驗證碼的一種解決方案)

文章採納源地址:https://www.cnblogs.com/kuzaman/p/6564632.html

使用微信發送驗證碼配置頁面:

以下步驟獲取頁面上的參數

1、註冊企業微信:

 

    註冊網址:https://work.weixin.qq.com/
    註冊成功後微信掃碼/企業微信掃碼進行登陸
登陸成功頁面:

2、獲取企業ID

3、點擊企業應用創建一個用來發送驗證碼的應用

驗證碼應用頁面:這裏獲取企業應用的id【agentID】和管理組的憑證祕鑰【CorpSecret】

 

4、body是你要發送的文本信息【可以是任意內容但是有文本長度的限制】

5、ToUser這個參數是成員的賬號【大小寫都可以】

6、如何加入新的成員

 

掃描下方二維碼下載企業微信,註冊加入企業


掃描下方二維碼,關注企業微信插件即可通過微信接収消息

 

 

7、後臺代碼:

 

依賴包:
package com.wechat.send;
 
/**
 * 微信消息發送實體類
 * @author zhangmingliang
 */
public class WeChatData {
    //發送微信消息的URLString sendMsgUrl="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
    /**
     * 成員賬號
     */
    private String touser;
    /**
     * 消息類型
     */
    private String msgtype;
    /**
     * 企業應用的agentID
     */
    private int agentid;
    /**
     * 實際接收Map類型數據
     */
    private Object text;
 
    public Object getText() {
        return text;
    }
    public void setText(Object text) {
        this.text = text;
    }
    public String getMsgtype() {
        return msgtype;
    }
    public void setMsgtype(String msgtype) {
        this.msgtype = msgtype;
    }
    public int getAgentid() {
        return agentid;
    }
    public void setAgentid(int agentid) {
        this.agentid = agentid;
    }
    public String getTouser() {
        return touser;
    }
    public void setTouser(String touser) {
        this.touser = touser;
    }
 
}
 
 
 
 
package com.ultrapower.umap.entity.factor;


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


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.http.HttpEntity;
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.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;


/**
 * 微信發送消息
 * @author zhangmingliang
 */
public class WeChatMsgSend {
    private CloseableHttpClient httpClient;
    /**
     *  用於提交登陸數據
     */
    private HttpPost httpPost;
    /**
     *  用於獲得登錄後的頁面
     */
    private HttpGet httpGet;


    public static final String CONTENT_TYPE = "Content-Type";


    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    private static Gson gson = new Gson();


    /**
     * 微信授權請求,GET類型,獲取授權響應,用於其他方法截取token
     * @param Get_Token_Url
     * @return String 授權響應內容
     * @throws IOException
     */
    protected String toAuth(String Get_Token_Url) throws IOException {


        httpClient = HttpClients.createDefault();
        httpGet = new HttpGet(Get_Token_Url);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        String resp;
        try {
            HttpEntity entity = response.getEntity();
            resp = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
        LoggerFactory.getLogger(getClass()).info(" resp:{}", resp);
        return resp;
    }


    /**corpid應用組織編號   corpsecret應用祕鑰
     * 獲取toAuth(String Get_Token_Url)返回結果中鍵值對中access_token鍵的值
     * @param
     */
    public  String getToken(String corpid,String corpsecret) throws IOException {
        WeChatMsgSend sw = new WeChatMsgSend();
        WeChatUrlData uData = new WeChatUrlData();
        uData.setGet_Token_Url(corpid,corpsecret);
        String resp = sw.toAuth(uData.getGet_Token_Url());
        System.out.println("resp=====:"+resp);
        try{
        Map<String, Object> map = gson.fromJson(resp,new TypeToken<Map<String, Object>>() {}.getType());
            return map.get("access_token").toString();
        }catch (Exception e) {
        return resp;
}
    }




    /**
     * @Title:創建微信發送請求post數據
     * touser發送消息接收者    ,msgtype消息類型(文本/圖片等),
     * application_id應用編號。
     * 本方法適用於text型微信消息,contentKey和contentValue只能組一對
     * @return String
     */
    public String createpostdata(String touser, String msgtype,
                                    int application_id, String contentKey ,String contentValue) {
        WeChatData wcd = new WeChatData();
        wcd.setTouser(touser);
        wcd.setAgentid(application_id);
        wcd.setMsgtype(msgtype);
        Map<Object, Object> content = new HashMap<Object, Object>();
        content.put(contentKey,contentValue);
        wcd.setText(content);
        return gson.toJson(wcd);
    }


    /**
     * @Title  創建微信發送請求post實體
     * charset消息編碼    ,contentType消息體內容類型,
     * url微信消息發送請求地址,data爲post數據,token鑑權token
     * @return String
     */
    public String post(String charset, String contentType, String url,
                       String data,String token) throws IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        httpPost = new HttpPost(url+token);
        httpPost.setHeader(CONTENT_TYPE, contentType);
        httpPost.setEntity(new StringEntity(data, charset));
        CloseableHttpResponse response = httpclient.execute(httpPost);
        String resp;
        try {
            HttpEntity entity = response.getEntity();
            resp = EntityUtils.toString(entity, charset);
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
        LoggerFactory.getLogger(getClass()).info("call [{}], param:{}, resp:{}", url, data, resp);
        return resp;
    }


}
 
 
package com.wechat.send;
 
/**
 * 微信授權請求
 * @author zhangmingliang
 */
public class WeChatUrlData {
    /**
     *  企業Id
     */
    private String corpid;
    /**
     * secret管理組的憑證密鑰
     */
    private String corpsecret;
    /**
     * 獲取ToKen的請求
     */
    private String Get_Token_Url;
    /**
     * 發送消息的請求
     */
    private String SendMessage_Url;
 
    public String getCorpid() {
        return corpid;
    }
    public void setCorpid(String corpid) {
        this.corpid = corpid;
    }
    public String getCorpsecret() {
        return corpsecret;
    }
    public void setCorpsecret(String corpsecret) {
        this.corpsecret = corpsecret;
    }
    public void setGet_Token_Url(String corpid,String corpsecret) {
        this.Get_Token_Url ="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+corpid+"&corpsecret="+corpsecret;
    }
    public String getGet_Token_Url() {
        return Get_Token_Url;
    }
    public String getSendMessage_Url(){
        return SendMessage_Url;
    }
 
}
 
 
 
package com.wechat.send;
 
import java.io.IOException;
 
public class Test {
 
    public static void main(String[] args) {
        WeChatMsgSend swx = new WeChatMsgSend();
        try {
            String token = swx.getToken("wwbae2c89178c02d3f","hQR5YpgtxY8B3d9S5hmTzYEgiD2yvlibHk1H5hTp6Ms");
            String postdata = swx.createpostdata("ZhangMingLiang", "text", 1000002, "content","This alert Email come from IapppayBJQA");
            String resp = swx.post("utf-8", WeChatMsgSend.CONTENT_TYPE,(new WeChatUrlData()).getSendMessage_Url(), postdata, token);
            System.out.println("獲取到的token======>" + token);
            System.out.println("請求數據======>" + postdata);
            System.out.println("發送微信的響應數據======>" + resp);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章