实现效果:
在后台服务器对订单进行回复以后,会给用户推送一张小程序卡片告诉用户他的订单已被回复。点击卡片可以跳转进入订单页面,查看回复。(相比于text消息的好处是用户体验更好,可直接点击进入小程序操作)
微信图片_20181228142811.jpg
实现过程:
微信小程序API:https://developers.weixin.qq.com/miniprogram/dev/api/sendCustomerMessage.html
服务器端如果要给用户发送消息,需要给微信的URL发出一个post请求。
请求的地址是 https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN。
其中ACCESS_TOKEN是接口调用凭证。
通过向https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET发送get请求获取。
appid为小程序的appid,secret为小程序唯一凭证密钥。(「微信公众平台 - 设置 - 开发设置」)
请求的参数是
{
"touser": "OPENID",
"msgtype": "miniprogrampage",
"miniprogrampage": {
"title": "title",
"pagepath": "pagepath",
"thumb_media_id": "thumb_media_id"
}
}
touser:对应填入的用户openID
msgtype:填入"miniprogrampage",表示信息类型为小程序卡片。
title:为小程序卡片显示的标题。
pagepath:对应小程序的页面路径。
thumb_media_id:图片标识ID,即小程序卡片中的图片。
实现对应的代码如下
//replyUserMission函数
//输入openid,给对应openid用户发送小程序卡片。
public static void replyUserMission(String openid) throws JSONException, IOException {
String accessToken= WechatService.gainAccessToken();
//得到小程序的accessToken
String postImage="https://api.weixin.qq.com/cgi-bin/media/upload?access_token="+accessToken+"&type=image";
//上传图片的URL
Resource resource = new ClassPathResource("images/image.png");
//获取resource中的图片
InputStream is=resource.getInputStream();
//得到输入流
byte[] imageByte=new byte[is.available()];//= ImageReader.readImage(imagePath);
is.read(imageByte);
is.close();
//将输入流的信息转为二进制序列。
String res= HttpUtil.httpPost(postImage,imageByte);
//将图片post给微信服务器
JSONObject obj=new JSONObject(res);
String thumb_media_id=obj.getString("media_id");
System.out.println("thumb_media_id"+thumb_media_id);
//解析服务器返回的json数据,获取thumb_media_id
WechatService.replyMiniProgramme(openid,"您的订单有回复","pages/viewSQL/viewSQL",thumb_media_id);
//给用户推送小程序卡片
}
引用到的gainAccessToken静态函数,用于获取AccessToken
public static String gainAccessToken() throws JSONException {
String httpurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=填入自己的appid&secret=对应的secretKey";
//请求AccessToken的URL
HttpURLConnection connection = null;
InputStream is = null;
BufferedReader br = null;
String result = null;// 返回结果字符串
try {
// 创建远程url连接对象
URL url = new URL(httpurl);
// 通过远程url连接对象打开一个连接,强转成httpURLConnection类
connection = (HttpURLConnection) url.openConnection();
// 设置连接方式:get
connection.setRequestMethod("GET");
// 设置连接主机服务器的超时时间:15000毫秒
connection.setConnectTimeout(15000);
// 设置读取远程返回的数据时间:60000毫秒
connection.setReadTimeout(60000);
// 发送请求
connection.connect();
// 通过connection连接,获取输入流
if (connection.getResponseCode() == 200) {
is = connection.getInputStream();
// 封装输入流is,并指定字符集
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
// 存放数据
StringBuffer sbf = new StringBuffer();
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp);
sbf.append("\r\n");
}
result = sbf.toString();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != br) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
connection.disconnect();// 关闭远程连接
}
JSONObject jsonObject = new JSONObject(result);
String str = jsonObject.getString("access_token");
return str;
}
发送POST请求和接收回复的类
public class HttpUtil {
public static String httpPost(String httpUrl,byte[] imagebyte){
HttpPost httpPost = new HttpPost(httpUrl);
ByteArrayBody image = new ByteArrayBody(imagebyte, ContentType.APPLICATION_JSON,"image.png");//传递图片的时候可以通过此处上传image.jpg随便给出即可
MultipartEntityBuilder me = MultipartEntityBuilder.create();
me.addPart("image", image);//image参数为在服务端获取的key通过image这个参数可以获取到传递的字节流,这里不一定就是image,你的服务端使用什么这里就对应给出什么参数即可
DefaultHttpClient client= new DefaultHttpClient();
HttpEntity reqEntity = me.build();
httpPost.setEntity(reqEntity);
HttpResponse responseRes = null;
try {
responseRes=client.execute(httpPost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
client.close();
}
int status = responseRes.getStatusLine().getStatusCode();
String resultStr =null;
if (status == 200) {
byte[] content;
try {
content = getContent(responseRes);
resultStr = new String(content,"utf-8");
System.out.println("httpPost返回的结果==:"+resultStr);
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(resultStr);
if(resultStr !=null){
return resultStr;
}else{
return "";
}
}
private static byte[] getContent(HttpResponse response)
throws IOException {
InputStream result = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = resEntity.getContent();
int len = 0;
while ((len = result.read()) != -1) {
out.write(len);
}
return out.toByteArray();
}
} catch (IOException e) {
e.printStackTrace();
throw new IOException("getContent异常", e);
} finally {
out.close();
if (result != null) {
result.close();
}
}
return null;
}
}
发送用户小程序卡片
//返回用户一个mini小程序卡片
String accessToekn=gainAccessToken();
URL url = new URL("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToekn);
//post参数
String newpostData="{\n" +
" \"touser\": \""+openid+"\",\n" +
" \"msgtype\": \"miniprogrampage\",\n" +
"\"miniprogrampage\": {"+
"\"title\":\""+title+"\","+
"\"pagepath\": \""+pagepath+"\","+
"\"thumb_media_id\": \""+thumb_media_id+"\""+
"}"+
"}";
byte[] postDataBytes = newpostData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
for (int c; (c = in.read()) >= 0;)
sb.append((char)c);
String response = sb.toString();
System.out.println("response:"+response);
return response;
}
网友评论