【实战】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;
    }
}

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

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: H5跳转到微信小程序是一种通过在H5页面中添加跳转链接实现从H5页面跳转到微信小程序的功能。下面是一个H5跳转到微信小程序的demo: 1. 首先,在H5页面中添加一个跳转到微信小程序的按钮或链接。可以使用HTML的<a>标签和href属性来实现。例如: ```html <a href="weixin://dl/business/?appid=wxappid">点击跳转到微信小程序</a> ``` 在上面的代码中,weixin://dl/business/ 是微信用于跳转小程序的协议。 2. 将wxappid替换为你要跳转的微信小程序的AppID。可以在微信公众平台上的小程序管理后台找到小程序的AppID。 3. 当用户点击该按钮或链接时,系统会自动检测用户的设备是否安装了微信小程序。如果安装了,会自动打开小程序;如果未安装,会跳转到微信的下载页面。 需要注意的是,以上方法只适用于在微信内部打开的H5页面。在其他浏览器或App中打开的H5页面无法使用该方法跳转到微信小程序。 另外,如果你是小程序开发者,还可以使用微信小程序提供的API实现跳转到其他小程序的功能。具体的实现方法可以参考微信小程序的开发文档。 ### 回答2: 在实现H5跳转到微信小程序的demo中,我们可以通过以下步骤来完成: 1. 首先,我们需要在H5页面中引入微信提供的JS-SDK库文件,可以通过以下代码实现: ```html <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script> ``` 2. 然后,我们需要在微信开放平台上注册并获取微信小程序的AppID。将获取到的AppID填写在H5页面的`wx.config`配置中,具体代码如下: ```javascript wx.config({ appId: 'YourAppID', timestamp: '', nonceStr: '', signature: '', jsApiList: [] }); ``` 在`jsApiList`中填写小程序提供的JS接口,比如跳转小程序的`launchMiniProgram`接口。 3. 接下来,我们需要在H5页面中添加一个跳转按钮,并绑定点击事件。在点击事件中调用`wx.miniProgram`的`navigateBack`方法来实现跳转小程序,具体代码如下: ```javascript document.getElementById('jumpBtn').addEventListener('click', function() { wx.miniProgram.navigateTo({ url: '/pages/index/index' }); }); ``` 其中,`url`参数填写要跳转到的小程序页面路径。 4. 最后,在微信小程序的对应页面中添加一个返回按钮,点击事件中调用`wx.miniProgram`的`navigateBack`方法来返回到H5页面,具体代码如下: ```javascript wx.miniProgram.navigateBack(); ``` 通过以上步骤,我们就可以实现H5页面跳转到微信小程序的demo了。当用户点击H5页面中的跳转按钮时,就会跳转到指定的小程序页面;而在小程序页面中点击返回按钮,则会返回到H5页面。 ### 回答3: H5跳转到微信小程序的实现方式有多种。以下是一种具体的实现示例: 首先,在H5页面中,可以通过添加一个按钮或链接来实现跳转到微信小程序的功能。例如,在HTML代码中添加一个按钮元素,然后使用JavaScript代码来监听按钮的点击事件。 HTML代码示例: ```html <button id="jumpButton">跳转小程序</button> ``` 接着,在JavaScript代码中,通过调用微信小程序接口`wx.miniProgram.navigateTo`来实现跳转到指定的小程序页面。需要在button的点击事件处理函数中编写相关代码。 JavaScript代码示例: ```javascript document.getElementById('jumpButton').addEventListener('click', function() { // 跳转小程序的页面路径,在小程序开发工具中可以找到 var path = '/pages/index/index'; // 跳转时携带的参数,在小程序中可以通过options参数获取 var params = { id: 123 }; // 调用微信小程序接口跳转到指定页面 wx.miniProgram.navigateTo({ url: path + '?id=' + params.id }); }); ``` 在以上示例中,点击按钮后,会调用`wx.miniProgram.navigateTo`接口,携带指定的页面路径和参数跳转小程序的页面。可以根据实际需求修改`path`和`params`变量的值来实现跳转到不同的小程序页面和传递不同的参数。 需要注意的是,以上示例中的代码是基于微信小程序的开发接口实现的,所以要确保在微信浏览器中打开H5页面才能正常跳转到微信小程序。此外,需要提前在微信小程序的配置文件中进行相应的设置,以确保能正确跳转到指定小程序页面。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值