微信小程序 获取小程序码 java后台案例

2021/9/6 17:10:26

本文主要是介绍微信小程序 获取小程序码 java后台案例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

为满足不同需求和场景,这里提供了两个接口,开发者可挑选适合自己的接口。

  • 接口 A: 适用于需要的码数量较少的业务场景
    • 生成小程序码,可接受 path 参数较长,生成个数受限,数量限制见 注意事项,请谨慎使用。
  • 接口 B:适用于需要的码数量极多的业务场景
    • 生成小程序码,可接受页面参数较短,生成个数不受限。

以接口B为例:
  通过该接口生成的小程序码,永久有效,数量不限制,用户扫描该码进入小程序后,将直接进入 path 对应的页面。

  官方文档链接:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html

  接口地址:https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=ACCESS_TOKEN

效果图

QRcodeController.java

import com.alibaba.druid.util.HttpClientUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pinpinhuo.web.utils.WxUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/weixinCode")
public class QRCodeController {

    /**
     * 详情看官方文档 https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html
     * 此处以官方接口B为例
     * 生成小程序码,可接受页面参数较短,生成个数不受限
     * param :参数 例如:123    page:需要跳转的页面地址 例如:pages/index
     */
    @RequestMapping("/getCode")
    public void smallProgramCode(String param, String page, HttpServletResponse response) {
        OutputStream stream = null;
        try {
            //获取AccessToken
            String accessToken = getAccessToken();
            //设置响应类型
            response.setContentType("image/png");
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
            //组装参数
            Map<String, Object> paraMap = new HashMap<>();
            //二维码携带参数 不超过32位 参数类型必须是字符串
            paraMap.put("scene", param);
            //二维码跳转页面
            paraMap.put("page", page);
            //二维码的宽度
            paraMap.put("width", 450);
            //自动配置线条颜色,如果颜色依然是黑色,则说明不建议配置主色调
            paraMap.put("auto_color", false);
            //是否需要透明底色, is_hyaline 为true时,生成透明底色的小程序码
            paraMap.put("is_hyaline", false);
            //执行post 获取数据流
            byte[] result = WxUtil.doImgPost(url, paraMap);
            //输出图片到页面
            response.setContentType("image/png");
            stream = response.getOutputStream();
            stream.write(result);
            stream.flush();
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取ACCESS_TOKEN
     * 官方文档地址:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html
     * <p>
     * 需要正确的 appid  和 secret  查看自己的微信开放平台
     */
    public String getAccessToken() {
        //这里需要换成你d的小程序appid
        String appid = "wx8feahukgeaer4fe9a";
        //这里需要换成你d的小程序secret
        String appSecret = "f02185k9zafbwrtbjyr33h7318c1tj";
        //获取微信ACCESS_TOKEN 的Url
        String accent_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
        String url = accent_token_url.replace("APPID", appid).replace("APPSECRET", appSecret);
        //发送请求
        String s = WxUtil.get(url);

        Map<String, Object> resultMap = JSON.parseObject(s,new HashMap<>().getClass());
        System.out.println("access_token------>" + resultMap.get("access_token").toString());
        return resultMap.get("access_token").toString();
    }
}

  

WxUtil.java

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.ConnectionPoolTimeoutException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.net.SocketTimeoutException;
import java.util.Map;

public class WxUtil {
    
    /**
     * 获取数据流
     * @param url
     * @param paraMap
     * @return
     */
    public static byte[] doImgPost(String url, Map<String, Object> paraMap) {
        byte[] result = null;
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json");
        try {
            // 设置请求的参数
            JSONObject postData = new JSONObject();
            for (Map.Entry<String, Object> entry : paraMap.entrySet()) {
                postData.put(entry.getKey(), entry.getValue());
            }
            httpPost.setEntity(new StringEntity(postData.toString(), "UTF-8"));
            HttpClient httpClient = HttpClientBuilder.create().build();
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toByteArray(entity);
        } catch (ConnectionPoolTimeoutException e) {
            e.printStackTrace();
        } catch (ConnectTimeoutException e) {
            e.printStackTrace();
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
        }
        return result;
    }
}


这篇关于微信小程序 获取小程序码 java后台案例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程