小程序一次性订阅消息(消息通知):java服务端实现
在Java后端实现小程序一次性订阅消息,你需要使用微信官方提供的API,并且确保你有小程序的appId
和appSecret
。以下是一个简单的Java示例代码,用于发送一次性订阅消息:
import com.google.gson.JsonObject;
import okhttp3.*;
import java.io.IOException;
public class WechatMiniProgramSubscribeMessage {
private static final String APP_ID = "你的小程序appId";
private static final String APP_SECRET = "你的小程序appSecret";
private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
private static final String SUBSCRIBE_MESSAGE_URL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s";
public static void sendSubscribeMessage(String openId, String templateId, JsonObject data) throws IOException {
// 获取access_token
String accessToken = getAccessToken();
// 发送订阅消息
sendMessage(accessToken, openId, templateId, data);
}
private static String getAccessToken() throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(String.format(ACCESS_TOKEN_URL, APP_ID, APP_SECRET))
.build();
try (Response response = client.newCall(request).execute()) {
String responseString = response.body().string();
JsonObject jsonObject = JsonParser.parseString(responseString).getAsJsonObject();
return jsonObject.get("access_token").getAsString();
}
}
private static void sendMessage(String accessToken, String openId, String templateId, JsonObject data) throws IOException {
OkHttpClient client = new OkHttpClient();
JsonObject json = new JsonObject();
json.addProperty("touser", openId);
json.addProperty("template_id", templateId);
json.add("page", null); // 可选
json.add("data", data);
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody requestBody = RequestBody.create(JSON, json.toString());
Request request = new Request.Builder()
.url(String.format(SUBSCRIBE_MESSAGE_URL, accessToken))
.post(requestBody)
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println(response.body().string());
}
}
public static void main(String[] args) {
Jso
评论已关闭