【实战】H5跳转到小程序

前置

获取接口调用凭据 | 微信开放文档
获取加密scheme码 | 微信开放文档

代码

配置

wechat:
  AppID: 
  AppSecret: 

核心代码

跳转到小程序主页
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.higentec.common.domain.R;
import com.higentec.seedTraceability.common.utils.StringUtils;
import com.higentec.seedTraceability.common.utils.http.HttpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author hanyl
 * @apiNote
 * @date 2024/4/24 15:57
 */
@RestController
@RequestMapping("/wx")
@Api(tags = "微信")
public class WxController
{

    @Value("${wechat.AppID}")
    private String WECHAT_APPID;

    @Value("${wechat.AppSecret}")
    private String WECHAT_APPSECRET;
    
    /**
     * 获取接口调用凭据,跳转到小程序主页
     */
    @ApiOperation(value = "获取接口调用凭据")
    @GetMapping("/cgi-bin/token")
    public R<String> token()
    {
        // https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getAccessToken.html
        String tokenResult = HttpUtils.sendGet
                ("https://api.weixin.qq.com/cgi-bin/token?appid="
                        + WECHAT_APPID
                        + "&secret="
                        + WECHAT_APPSECRET
                        + "&grant_type=client_credential");
        JSONObject tokenMap = (JSONObject) JSON.parse(tokenResult);
        String access_token = tokenMap.getString("access_token");
        if (StringUtils.isEmpty(access_token)){
            return R.fail("获取接口调用凭据失败");
        }
        // https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/url-scheme/generateScheme.html#%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E
        String link = HttpUtils.sendPost(
                "https://api.weixin.qq.com/wxa/generatescheme?access_token=" + access_token, "");
        JSONObject linkMap = (JSONObject) JSON.parse(link);
        if ("ok".equals(linkMap.getString("errmsg"))){
            return R.ok(linkMap.getString("openlink"));
        }
        return R.fail("暂时无法跳转小程序");
    }
}

跳转到指定页面
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.higentec.common.domain.R;
import com.higentec.seedTraceability.common.utils.StringUtils;
import com.higentec.seedTraceability.common.utils.http.HttpUtils;
import com.higentec.seedTraceability.system.domain.vo.JumpWxaVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author hanyl
 * @apiNote
 * @date 2024/4/24 15:57
 */
@RestController
@RequestMapping("/wx")
@Api(tags = "微信")
public class WxController {

    @Value("${wechat.AppID}")
    private String WECHAT_APPID;

    @Value("${wechat.AppSecret}")
    private String WECHAT_APPSECRET;

    /**
     * 获取接口调用凭据,跳转到指定页面
     */
    @ApiOperation(value = "获取接口调用凭据")
    @GetMapping("/cgi-bin/token")
    public R<String> token() {
        String tokenResult = HttpUtils.sendGet
                ("https://api.weixin.qq.com/cgi-bin/token?appid="
                        + WECHAT_APPID
                        + "&secret="
                        + WECHAT_APPSECRET
                        + "&grant_type=client_credential");
        JSONObject tokenMap = (JSONObject) JSON.parse(tokenResult);
        String access_token = tokenMap.getString("access_token");
        if (StringUtils.isEmpty(access_token)) {
            return R.fail("获取接口调用凭据失败");
        }

        //  https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/url-scheme/generateScheme.html#%E6%8E%A5%E5%8F%A3%E8%AF%B4%E6%98%8E
        Map<String, JumpWxaVo> paramMap = new HashMap<>();
        JumpWxaVo jump_wxa = new JumpWxaVo();
        jump_wxa.setPath("跳转页面");
        jump_wxa.setQuery("a=a&b=b");
        jump_wxa.setEnv_version("trial");
        paramMap.put("jump_wxa",jump_wxa);
        System.out.println(JSON.toJSONString(paramMap));
        String link = HttpUtil.post(
                "https://api.weixin.qq.com/wxa/generatescheme?access_token=" + access_token, JSON.toJSONString(paramMap));
        JSONObject linkMap = (JSONObject) JSON.parse(link);

        if ("ok".equals(linkMap.getString("errmsg"))) {
            return R.ok(linkMap.getString("openlink"));
        }
        return R.fail("暂时无法跳转小程序");
    }
}

测试

image.png

工具类

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.higentec.seedTraceability.common.constant.Constants;
import com.higentec.seedTraceability.common.utils.StringUtils;

/**
 * 通用http发送方法
 * 
 * @author ruoyi
 */
public class HttpUtils
{
    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url 发送请求的 URL
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url)
    {
        return sendGet(url, StringUtils.EMPTY);
    }

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url 发送请求的 URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param)
    {
        return sendGet(url, param, Constants.UTF8);
    }

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url 发送请求的 URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @param contentType 编码类型
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param, String contentType)
    {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try
        {
            String urlNameString = StringUtils.isNotBlank(param) ? url + "?" + param : url;
            log.info("sendGet - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
            String line;
            while ((line = in.readLine()) != null)
            {
                result.append(line);
            }
            log.info("recv - {}", result);
        }
        catch (ConnectException e)
        {
            log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {
            log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {
            log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {
            log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
        }
        finally
        {
            try
            {
                if (in != null)
                {
                    in.close();
                }
            }
            catch (Exception ex)
            {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url 发送请求的 URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param)
    {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try
        {
            log.info("sendPost - {}", url);
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null)
            {
                result.append(line);
            }
            log.info("recv - {}", result);
        }
        catch (ConnectException e)
        {
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
        }
        finally
        {
            try
            {
                if (out != null)
                {
                    out.close();
                }
                if (in != null)
                {
                    in.close();
                }
            }
            catch (IOException ex)
            {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }

    public static String sendSSLPost(String url, String param)
    {
        StringBuilder result = new StringBuilder();
        String urlNameString = url + "?" + param;
        try
        {
            log.info("sendSSLPost - {}", urlNameString);
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
            URL console = new URL(urlNameString);
            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String ret = "";
            while ((ret = br.readLine()) != null)
            {
                if (ret != null && !"".equals(ret.trim()))
                {
                    result.append(new String(ret.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
                }
            }
            log.info("recv - {}", result);
            conn.disconnect();
            br.close();
        }
        catch (ConnectException e)
        {
            log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {
            log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {
            log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {
            log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
        }
        return result.toString();
    }

    private static class TrustAnyTrustManager implements X509TrustManager
    {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType)
        {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType)
        {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers()
        {
            return new X509Certificate[] {};
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier
    {
        @Override
        public boolean verify(String hostname, SSLSession session)
        {
            return true;
        }
    }
}

统一返回实体类

import com.higentec.common.constant.Constants;
import java.io.Serializable;

public class R<T> implements Serializable {
    private static final long serialVersionUID = 1L;
    public static final int SUCCESS;
    public static final int FAIL;
    private int code;
    private String msg;
    private T data;

    public R() {
    }

    public static <T> R<T> ok() {
        return restResult((Object)null, SUCCESS, (String)null);
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, SUCCESS, (String)null);
    }

    public static <T> R<T> ok(T data, String msg) {
        return restResult(data, SUCCESS, msg);
    }

    public static <T> R<T> fail() {
        return restResult((Object)null, FAIL, (String)null);
    }

    public static <T> R<T> fail(String msg) {
        return restResult((Object)null, FAIL, msg);
    }

    public static <T> R<T> fail(T data) {
        return restResult(data, FAIL, (String)null);
    }

    public static <T> R<T> fail(T data, String msg) {
        return restResult(data, FAIL, msg);
    }

    public static <T> R<T> fail(int code, String msg) {
        return restResult((Object)null, code, msg);
    }

    private static <T> R<T> restResult(T data, int code, String msg) {
        R<T> apiResult = new R();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }

    public int getCode() {
        return this.code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return this.msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return this.data;
    }

    public void setData(T data) {
        this.data = data;
    }

    static {
        SUCCESS = Constants.SUCCESS;
        FAIL = Constants.FAIL;
    }
}

生活的闲言碎语
最近打算加上生成二维码,然后下载。想做并发处理,一直没成功,ε=(´ο`*)))唉。。。。
最近也比较忙,肩膀痛死了
又是发疯的一天

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值