springboot 跳转微信小程序 生成URL Scheme URL Link

实现方案

        通过微信文档中的URL linkURL Scheme方式生成,更多事项细节见官方文档

话不多说,直接上代码

工具类

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Tenk
 */
@RequiredArgsConstructor
@Component
public class WxAppletNotifyUtils {

    private final WxAppletConfig wxAppletConfig;

    private static final String linkUrl="https://api.weixin.qq.com/wxa/generate_urllink?access_token=ACCESS_TOKEN";

    private static final String tokenUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";


    /**
     * 生成小程序跳转短链 code
     * @param path 小程序页面路径 null为首页
     * @param query 与前端商量,携带的参数
     * @return
     */
    public String jumpAppletShortUrl(String path,String query,Integer days){
        String accessToken = getAccessToken();
        String url=linkUrl.replace("ACCESS_TOKEN",accessToken);
        JSONObject body = JSONUtil.createObj();
        body.putOpt("path",path);
        body.putOpt("query",query);
        //链接过期类型:0时间戳 1间隔天数
        body.putOpt("expire_type",1);
        //指定失效天数,最多30
        days=(days==null||days>30)?30:days;
        body.putOpt("expire_interval",days);
        //小程序版本,正式版为 "release",体验版为"trial",开发版为"develop"
        body.putOpt("env_version","release");
        String post = HttpUtil.post(url, body.toJSONString(2));
        JSONObject jsonObject = JSONUtil.parseObj(post);
        return jsonObject.get("url_link", String.class, false);
    }

    /**
     * scheme 跳转微信小程序,需中转H5
     * @param path
     * @param query
     * @param days
     * @return
     */
    public String jumpAppletSchemeUrl(String path,String query,Integer days){
        String url = schemeUrl.replace("ACCESS_TOKEN", getAccessToken());
        JSONObject body = JSONUtil.createObj();
        JSONObject jumpWxa = JSONUtil.createObj();
        jumpWxa.putOpt("path",path);
        jumpWxa.putOpt("query",query);
        jumpWxa.putOpt("env_version","release");
        body.putOpt("jump_wxa",jumpWxa);
        //链接过期类型:0时间戳 1间隔天数
        body.putOpt("expire_type",1);
        body.putOpt("is_expire",true);
        //指定失效天数,最多30
        days=(days==null||days>30)?30:days;
        body.putOpt("expire_interval",days);
        String post = HttpUtil.post(url, body.toJSONString(2));
        JSONObject result = JSONUtil.parseObj(post);
        return result.toJSONString(2);
    }

    public String getAccessToken(){
        String token;
        //缓存存在token
        if(RedisUtils.hasKey(CacheConstants.APPLET_ACCESS_TOKEN)){
            //redis直接获取小程序token
            token = RedisUtils.getCacheObject(CacheConstants.APPLET_ACCESS_TOKEN);
        }else{
            //拼接url
            String url = tokenUrl.replace("APPID", wxAppletConfig.getAppId())
                .replace("APPSECRET", wxAppletConfig.getSecret());
            //get请求
            String result = HttpUtil.get(url);
            //解析结果
            JSONObject jsonObject = JSONUtil.parseObj(result);
            //get AccessToken
            token=jsonObject.get("access_token",String.class,true);
            //get 过期时间 单位秒
            Long expiresIn = jsonObject.get("expires_in", Long.class, true);
            //存入redis并减少60秒
            RedisUtils.setCacheObject(CacheConstants.APPLET_ACCESS_TOKEN,token, Duration.ofSeconds(expiresIn-60));
        }
        return token;
    }
}

配置类

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix = "wx.applet")
public class WxAppletConfig {

    //小程序登录获取openid的url
    private String sessionUrl;
    //小程序id
    private String appId ;
    //小程序密钥
    private String secret ;
}

yml配置

返回结果示例

URL Link / URL Scheme

{
 "errcode": 0,
 "errmsg": "ok",
 "url_link": "https://wxaurl.cn/xxxxxxxxx"
}
{
 "errcode": 0,
 "errmsg": "ok",
 "openlink": "weixin://dl/business/?t=xxxxxxxxx",
} 

 单元测试

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * @Author: Tenk
 */
@SpringBootTest // 此注解只能在 springboot 主包下使用 需包含 main 方法与 yml 配置文件
@DisplayName("自定义测试")
public class CustomizeTest {

    @Autowired
    private WxAppletNotifyUtils appletUtils;

    @DisplayName("测试微信跳转链接")
    @Test
    public void urlLink(){
        String shortUrl = appletUtils.jumpAppletShortUrl("/pages/login",null, 30);
        System.out.println(shortUrl);

        String schemeUrl = appletUtils.jumpAppletSchemeUrl("/pages/login", null, 1);
        System.out.println(schemeUrl);
    }
}

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_Tenk_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值