网络知识 娱乐 uniapp+微信小程序获取openId,获取access_token,订阅消息模板,java后台发送消息

uniapp+微信小程序获取openId,获取access_token,订阅消息模板,java后台发送消息

目录

1.前期准备

2.用户订阅消息

3.获取openId(uniapp)

4.获取access_token

5.发送消息

6.请求的代码Springboot(自己写有发送请求方法的可以不用看)


1.前期准备

在微信公众号申请订阅消息

在公共模板这里选用模板,模板种类跟小程序设置的类目有关,只有特殊的类目有长期订阅模板

类目可以在设置中修改

2.用户订阅消息

选用模板后点击详情查看模板的id

 

在小程序上编写以下代码(这个是uniapp框架的代码)

uni.requestSubscribeMessage({
					tmplIds:['1QO7f6SdIiw7loXtIhaIL5IKl4Ze0lS2moDVnjaAlLQ'],
					complete:(res)=>{
						console.log(res)
					}
				})

微信原生大概是这样的,没试过哈

wx.requestSubscribeMessage({
					tmplIds:['1QO7f6SdIiw7loXtIhaIL5IKl4Ze0lS2moDVnjaAlLQ'],
					complete:(res)=>{
						console.log(res)
					}
				})

 参考链接

 其中tmplIds就是我们选用模板的id,是个数组,最多三个。

用户选择确定后便可以进行消息发送。

3.获取openId(uniapp)

获取code 

uni.login({
				provider:"weixin",
				success:(loginRes)=>{
					console.log(loginRes.code);
					
				}
			})

后台通过code获取用户的openId

public String getOpenId(HttpServletRequest request, String code){
        SendParam sendParam = new SendParam();
        sendParam.setUrl("https://api.weixin.qq.com/sns/jscode2session");
        Map param = new HashMap();
        param.put("appid","微信小程序的appid");
        param.put("secret","微信小程序的secret");
        param.put("js_code","用户通过登录方法获取的code");
        param.put("grant_type","authorization_code");
        sendParam.setGetParam(param);
        SendReturn sendReturn =  SendUtils.sendGet(sendParam);
        System.out.println(sendReturn.getReturnString());
        return ReturnData.reJson(ReturnCode.MC001);
    }

用get请求访问

https://api.weixin.qq.com/sns/jscode2session

例如

https://api.weixin.qq.com/sns/jscode2session?appid=xxx&secret=xxx&js_code=xxx&grant_type=authorization_code

访问成功就能获取到用户的openId

4.获取access_token

 public String getAccessToken(){
        SendParam sendParam = new SendParam();
        sendParam.setUrl("https://api.weixin.qq.com/cgi-bin/token");
        Map param = new HashMap();
        param.put("grant_type","client_credential");
        param.put("appid","小程序的appid");
        param.put("secret","小程序的secret");
        sendParam.setGetParam(param);
        SendReturn sendReturn =  SendUtils.sendGet(sendParam);
        return ReturnData.reJson(ReturnCode.MC001);
    }

用get请求访问

https://api.weixin.qq.com/cgi-bin/token

例如

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=xxx&secret=xxx

访问成功即可获取到access_token

access_token是有时效的,默认7200秒。使用的时候记得看是否过期。

5.发送消息

public String send(){
        SendParam sendParam = new SendParam();
        sendParam.setUrl("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=57_CRjtQyjioD2Qe46gxDicfRifwTN-9kfteW9Onc1ZlWizniNXH1ww1j7FUhWc1WXM9ja7GXRPm_mtTIEdGdt5a7lCH9118Axz2Rm0Ku2h57dhMSYiAtwP6QxBr1h62x55bN4bsb7ajFlZ5m73XCSaAAALQG");
        Map param = new HashMap();
        param.put("touser","otnoE5Ry_89dahJ2_OhxIXVcLBPg");
        param.put("template_id","1QO7f6SdIiw7loXtIhaIL5IKl4Ze0lS2moDVnjaAlLQ");
        Map dataMap = new HashMap();
        dataMap.put("thing1",new HashMap(){{put("value","2");}});
        dataMap.put("thing2",new HashMap(){{put("value","2");}});
        dataMap.put("thing3",new HashMap(){{put("value","2021-01-01 00:00:00");}});
        param.put("data", dataMap);
        sendParam.setPostParam(param);
        SendReturn sendReturn =  SendUtils.SendPost(sendParam);
        return ReturnData.reJson(ReturnCode.MC001);
    }

发送post请求!!!post请求!!!

https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=xxxxx

其中access_token就是第四步获取到的access_token,参数要写到url中

之后就是要发送的数据

touser:要发送给用户的openId,获取方法看第三步
template_id:模板id,第一步选择模板时可以看到模板的id
data:要发送的数据,根据模板要求的数据来装配

比如模板要求的数据是这样的

 

那么最后拼凑的数据是这样的

data:{
    thing1:{value:"123"},
    thing2:{value:"123"},
    thing3:{value:"123"},
}

整体数据格式

{
    "touser":"XXXX",
    "template_id":"xxxxx",
    "data":{
        "thing1":{"value":"123"},
        "thing2":{"value":"234"},
        "thing3":{"value":"456"}
    }
}

用postMan看的话是这样的

请求成功后即可。

要注意的是,如果用的是一次性模板,用户订阅一次,服务端才能发送一次,若需要发送两次就需要用户订阅两次(也就是说要订阅两次)!!!!!????

长期模板的话,用户点击订阅后就不需要重复订阅,服务端也能一直发送消息。

6.请求的代码Springboot(自己写有发送请求方法的可以不用看)

代码垃圾,轻点喷 勿喷

SendParam
package ??????;

import org.springframework.http.HttpMethod;

import java.util.Map;


public class SendParam {
    private String url;
    private Object postParam;
    private Map getParam;
    private HttpMethod sendType;
    private Class classTr;

    public SendParam() {
        this.sendType = HttpMethod.GET;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Object getPostParam() {
        return postParam;
    }

    public void setPostParam(Object postParam) {
        this.postParam = postParam;
    }

    public Map getGetParam() {
        return getParam;
    }

    public void setGetParam(Map getParam) {
        this.getParam = getParam;
    }

    public HttpMethod getSendType() {
        return sendType;
    }

    public void setSendType(HttpMethod sendType) {
        this.sendType = sendType;
    }

    public Class getClassTr() {
        return classTr;
    }

    public void setClassTr(Class classTr) {
        this.classTr = classTr;
    }
}
SendReturn
package ???????;

import org.springframework.http.HttpStatus;

public class SendReturn {
    private boolean isSuccess;
    private String returnString;
    private T obj;
    private HttpStatus statusCode;
    private int statusCodeValue;


    public SendReturn() {
        this.isSuccess=true;
    }

    public boolean isSuccess() {
        return isSuccess;
    }

    public void setSuccess(boolean success) {
        isSuccess = success;
    }

    public String getReturnString() {
        return returnString;
    }

    public void setReturnString(String returnString) {
        this.returnString = returnString;
    }

    public T getObj() {
        return obj;
    }

    public void setObj(T obj) {
        this.obj = obj;
    }

    public HttpStatus getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(HttpStatus statusCode) {
        this.statusCode = statusCode;
    }

    public int getStatusCodeValue() {
        return statusCodeValue;
    }

    public void setStatusCodeValue(int statusCodeValue) {
        this.statusCodeValue = statusCodeValue;
    }
}
SendUtils
package ??????;

import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.Map;

@Component
public class SendUtils {

    private static RestTemplate restTemplate;

    @Autowired
    ApplicationContext applicationContext;

    @PostConstruct
    public void init() {
        SendUtils.restTemplate = applicationContext.getBean(RestTemplate.class);
    }

    private static Gson gson = new Gson();


    /**
     * 发送get请求
     * @param send
     * @return
     */
    public static SendReturn sendGet(SendParam send){
        String url = send.getUrl()+"?";
        if(send.getGetParam()!=null){
            Map map = send.getGetParam();
            for(Map.Entry entity : map.entrySet()){
                url += entity.getKey()+"="+entity.getValue()+"&";
            }
            url = url.substring(0,url.length()-1);
        }

        SendReturn sendReturn = new SendReturn();
        try{
            ResponseEntity responseEntity = restTemplate.getForEntity(url, String.class);
            if(send.getClassTr()!=null){
                Object o = gson.fromJson(responseEntity.getBody(),send.getClassTr());
                sendReturn.setObj(o);
            }
            sendReturn.setStatusCode(responseEntity.getStatusCode());
            sendReturn.setStatusCodeValue(responseEntity.getStatusCodeValue());
            sendReturn.setReturnString(responseEntity.getBody());
        }catch (Exception e){
            System.out.println(e);
            sendReturn.setSuccess(false);
        }
        return sendReturn;
    }


    /**
     * 发送post请求
     * @param send
     * @return
     */
    public static SendReturn SendPost(SendParam send){
        SendReturn sendReturn = new SendReturn();
        try{
            ResponseEntity responseEntity = restTemplate.postForEntity(send.getUrl(),send.getPostParam(),String.class);
            if(send.getClassTr()!=null){
                Object o = gson.fromJson(responseEntity.getBody(),send.getClassTr());
                sendReturn.setObj(o);
            }
            sendReturn.setStatusCode(responseEntity.getStatusCode());
            sendReturn.setStatusCodeValue(responseEntity.getStatusCodeValue());
            sendReturn.setReturnString(responseEntity.getBody());
        }catch (Exception e){
            System.out.println(e);
            sendReturn.setSuccess(false);
        }
        return sendReturn;
    }




}

修改请求配置(这里用的是okhttp哈)

RestTemplateConfig
package ????;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * 数据请求配置
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
    }


}

maven上要加上okhttp3和gson的依赖哈

pom.xml


            com.squareup.okhttp3
            okhttp



            com.google.code.gson
            gson
            2.8.5

 最后能不能跑我是不知道了,我也没单独拆开测试过,我觉得是应该能跑的,该写的,该配置的都贴在上边了,祝好运!