微信小程序发送客服消息之小程序卡片

实现效果:

在后台服务器对订单进行回复以后,会给用户推送一张小程序卡片告诉用户他的订单已被回复。点击卡片可以跳转进入订单页面,查看回复。(相比于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;
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1、开启公众号开发者模式 公众平台的技术文档目的为了简明扼要的交代接口的使用,语句难免苦涩难懂,甚至对于不同的读者...
    good7758阅读 5,485评论 0 1
  • 【微信小程序】发送消息模板教程(后台以PHP示例): 1、本教程对外开放,未经博主同意,禁止转载。 2、准备材料:...
    第九程序官方阅读 10,466评论 0 8
  • 1、客服消息功能概述 在页面中使用 <contact-button/> 可以显示进入客服会话按钮。 当用户在客服会...
    码农随想录阅读 68,712评论 13 26
  • 先引入JS 文件 this.wxShare() 在created里调用 首先登陆微信公众号 JSSDK使用步骤 步...
    寄鱼予海与你阅读 11,773评论 1 3
  • 洛阳王城公园广场舞团占领“篮球场”事件,仍未得到妥善处理。相关部门引导广场舞大妈们到附近公园跳舞,篮球场早上偶尔开...
    熏莉阅读 1,346评论 0 0

友情链接更多精彩内容