C#, .net H5跳转到微信小程序

首次发布:2024-12-15

获取加密scheme码 的C#代码

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public static class WChatUtil
    {
        // 凭证有效时间,单位:秒。目前是7200秒之内的值。
        private static int expiresIn = 7200;
        //appid=wx53b530****b45ad8 小程序Id; 获取地址https://mp.weixin.qq.com/ 开发者管理->开发设置
        //secret=8ee99bb51321****7de249e82bf65611   获取地址https://mp.weixin.qq.com/ 开发者管理->开发设置->AppSecret(小程序密钥)
        private static string appId = "wx53b530****b45ad8";  // 你的小程序App ID,需替换真实值  wx53b530****b45ad8
        private static string appSecret = "8ee99bb51321****7de249e82bf65611";  // 你的小程序App Secret,需替换真实值  8ee99bb51321****7de249e82bf65611

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

        /// <summary>
        /// 获取微信小程序的AccessToken。
        /// 如果AccessToken尚未获取或已过期,则会向微信服务器发起请求获取新的AccessToken。
        /// </summary>
        /// <returns>微信小程序AccessToken</returns>
        public static string? GetAccessToken()
        {
            // 如果AccessToken为空或已过期,则重新获取
            if (accessToken == null || DateTimeOffset.UtcNow.ToUnixTimeSeconds() > expireTime)
            {
                RefreshAccessToken().Wait();
            }
            return accessToken;
        }

        /// <summary>
        /// 刷新AccessToken,向微信服务器发送请求获取新的AccessToken。
        /// </summary>
        private static async Task RefreshAccessToken()
        {
            // 构建请求URL
            string url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={appSecret}";

            using (HttpClient httpClient = new HttpClient())
            {
                using (HttpResponseMessage response = await httpClient.GetAsync(url))
                {
                    string responseJson = await response.Content.ReadAsStringAsync();
                    // 使用Newtonsoft.Json解析JSON响应
                    JObject jsonObject = JObject.Parse(responseJson);

                    // 从JSON响应中获取AccessToken
                    accessToken = jsonObject["access_token"]?.ToString();
                    // 计算过期时间戳
                    expireTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds() + (expiresIn - 60); // 提前60秒过期,避免刚好过期时的并发问题
                }
            }
        }

        /// <summary>
        /// 获取scheme
        /// </summary>
        /// <param name="path">url路径</param>
        /// <param name="query">url参数</param>        
        /// <returns>返回从微信服务器获取的相应内容(通常为JSON格式字符串)</returns>
        public static string GenerateScheme(string path,string query)
        {
            string? accessToken = GetAccessToken();
            // 拼接URL
            string url = $"https://api.weixin.qq.com/wxa/generatescheme?access_token={accessToken}";
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // 创建一个 JSON 格式的请求主体
                    // jsonRequestString格式样例 = "{\"jump_wxa\":{\"path\":\"/pages/item/item\",\"query\":\"DBI=1&Id=3974912\",\"env_version\":\"release\"},\"is_expire\":true,\"expire_type\":1,\"expire_interval\":1}";
                    GetSchemeModel getScheme=new GetSchemeModel();
                    getScheme.jump_wxa.path=path;
                    getScheme.jump_wxa.query=query;
                    string jsonRequestString =JsonConvert.SerializeObject(getScheme);
                    HttpContent httpContent = new StringContent(jsonRequestString, Encoding.UTF8, "application/json");
                    var response = client.PostAsync(url, httpContent).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        return response.Content.ReadAsStringAsync().Result;
                    }
                    return "错误" + response.StatusCode;
                }
            }
            catch (Exception ex)
            {
                return "错误" + ex.Message;
            }
        }
    }
}

实体类

/// <summary>
/// 获取加密scheme码
/// </summary>
public class GetSchemeModel
{
    public JumpWxa jump_wxa = new JumpWxa();
    public bool is_expire = true;
    public int expire_type = 1;
    public int expire_interval = 1;
}
public class JumpWxa
{
    /// <summary>
    /// url路径
    /// </summary>
    public string path = "/pages/item/item";
    /// <summary>
    /// url参数
    /// </summary>
    public string query = "DBI=1&Id=3974912";
}
/// <summary>
/// 获取加密scheme码结果
/// </summary>
public class GetSchemeResultModel
{
    public int errcode;
    public string? errmsg;
    public string? openlink;
}

获取加密scheme码的相关参数官方地址https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/url-scheme/generateScheme.html

调用获取加密scheme码

string s = WChatUtil.GenerateScheme("/pages/index/index", "");
var v= JsonConvert.DeserializeObject<GetSchemeResultModel>(s);

H5跳转到微信中程序代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>H5跳转到微信小程序</title></head>
<body >    
                            <a  href="weixin://dl/business/?t=fw6OOkBIrqt">H5跳转微信小程序</a>
</body>
</html>

获取微信小程序AppID和AppSecret的网页位置

image.png

视频教程

本文来自 www.LuoFenMing.com