H5网页跳转微信小程序

发布时间 2023-12-12 17:39:03作者: 於生

获取scheme码

该接口用于获取小程序 scheme 码,适用于短信、邮件、外部网页、微信内等拉起小程序的业务场景。目前仅针对国内非个人主体的小程序开放,详见获取 URL scheme

 

效果:https://www.youlingrc.com/minishare.html

项目地址:https://github.com/yusheng9/openwxchat

 

H5:index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>优领用工-我要招聘</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <style type="text/css">
            html, body {
                height: 100%;
                margin: 0;
                padding: 0;
            }
            .page {
                background: linear-gradient(to bottom, #28AC86 50%, #DBEAE7 50%);
                width: 100%;
                height: 100vh;
                overflow: hidden;
                position: relative;
              }
              .page .main{
                background: url('https://img.youlingrc.com/images/20231018142538.png') no-repeat center;
                background-size: contain;
                width: 100%;
                height: 100vh;
              }
              .btn{
                width: 80%;
                height: 60px;
                background: #28AC86;
                color: white;
                position: absolute;
                left: 10%;
                bottom: 8%;
                font-size: 2.1em;
                display: flex;
                align-items: center;
                justify-content: center;
                border-radius: 20px;
                box-shadow: 5px 6px 16px rgba(0, 0, 0, 0.3);
              }
        </style>
    </head>
    <body>
        
        <div class="page">
            <div class="main">
              <div class="btn">我要招聘</div>
            </div>
        </div>
          
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
        <script>
            
            
            $(function(){
                
                let openlink = '';
                $.ajax({
                    url: 'http://127.0.0.1:8080/wchat/api/generatescheme',
                    type: 'POST',  // 或者 'GET',根据您的需求
                    data: JSON.stringify({
                        path: "pages/home/home",
                        query: "source=8"
                    }),
                    contentType: 'application/json',
                    success: function (res) {
                        // 请求成功时的处理逻辑
                        console.log('请求成功', res);
                        if (res.code === "20000") {
                            let data = res.content
                            if (data.openlink){
                                openlink = data.openlink
                            }
                        }
                    },
                    error: function (xhr, status, error) {
                        // 请求失败时的处理逻辑
                        console.log('请求失败', status, error);
                    }
                });
                
                $(".btn").click(function () {
                    // 检测用户代理字符串
                    var userAgent = navigator.userAgent;
                    console.log('userAgent',userAgent)
            
                    // 定义PC浏览器的关键词
                    var pcKeywords = ["Windows", "Macintosh"];
            
                    // 检查用户代理是否包含PC关键词
                    var isPC = pcKeywords.some(function (keyword) {
                        return userAgent.indexOf(keyword) !== -1;
                    });
                    // 如果是PC浏览器,显示提示消息
                    if (isPC) {
                        alert("请使用手机浏览器打开。");
                        return
                    }
                    window.location.href = openlink
                });
                
            })
        </script>
    </body>
</html>

 

 

java后端服务:

WChatUtil.java

package com.example.openwxchat.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class WChatUtil {

    //凭证有效时间,单位:秒。目前是7200秒之内的值。
    private static Integer expiresIn = 7200;


    private final static String APPID = "wx9e6939****aadf0d";  // 你的小程序App ID
    private final static String APPSECRET = "4fc41066df*********ad68124ee39fd";  // 你的小程序App Secret

    // 存储AccessToken和其有效期的变量
    private static String accessToken;
    private static long expireTime; // 过期时间戳,单位:秒

    /**
     * 获取微信小程序的AccessToken。
     * 如果AccessToken尚未获取或已过期,则会向微信服务器发起请求获取新的AccessToken。
     *
     * @return 微信小程序AccessToken
     */
    public static String getAccessToken() {
        // 如果AccessToken为空或已过期,则重新获取
        if (accessToken == null || System.currentTimeMillis() > expireTime * 1000) {
            refreshAccessToken();
        }
        return accessToken;
    }

    /**
     * 刷新AccessToken,向微信服务器发送请求获取新的AccessToken。
     */
    private static void refreshAccessToken() {
        // 构建请求URL
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + APPSECRET;

        // 使用HttpClient发送POST请求
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);

        try {
            HttpResponse response = httpClient.execute(httpPost);
            String responseJson = EntityUtils.toString(response.getEntity());
            // 使用FastJSON解析JSON响应
            JSONObject jsonObject = JSONObject.parseObject(responseJson);

            // 从JSON响应中获取AccessToken
            accessToken = jsonObject.getString("access_token");
            // 计算过期时间戳
            expireTime = System.currentTimeMillis() + (expiresIn - 60) * 1000; // 提前60秒过期,避免刚好过期时的并发问题
        } catch (IOException e) {
            // 处理异常
        }
    }

    //获取scheme
    public static String generateScheme(String jump_wxa) {
        String accessToken = getAccessToken();
        // 拼接URL
        String url = "https://api.weixin.qq.com/wxa/generatescheme?access_token=" + accessToken;
        try {
            HttpClient client = HttpClients.createDefault(); // 构建一个Client
            HttpPost post = new HttpPost(url); // 构建一个Post请求
            post.setHeader("Content-Type", "application/json"); // 设置请求头为JSON

            // 创建一个 JSON 格式的请求主体
            JSONObject jsonRequest = new JSONObject();
            jsonRequest.put("jump_wxa", JSON.parseObject(jump_wxa));
            StringEntity input = new StringEntity(jsonRequest.toString(), "UTF-8");
            post.setEntity(input);

            HttpResponse response = client.execute(post); // 提交POST请求
            HttpEntity result = response.getEntity(); // 拿到返回的HttpResponse的"实体"
            String content = EntityUtils.toString(result);
            // 返回JSON格式的响应字符串
            return content;
        } catch (Exception e) {
            e.printStackTrace();
            // 返回错误信息
            return "{\"error\": \"" + e.getMessage() + "\"}";
        }
    }
}

 

ApiController.java

package com.example.openwxchat.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.openwxchat.param.GenerateschemeParam;
import com.example.openwxchat.utils.WChatUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/wchat/api")
@RestController
public class ApiController {

    @PostMapping("/generatescheme")
    public Object generatescheme(@RequestBody GenerateschemeParam param){
        JSONObject jump_wxa_json = new JSONObject();
        jump_wxa_json.put("path",param.getPath());
        jump_wxa_json.put("query",param.getQuery());
        String scheme = WChatUtil.generateScheme(JSONObject.toJSONString(jump_wxa_json));
        return ResponseEntity.ok(scheme);
    }
}