当前位置:   article > 正文

H5通过Url Scheme方式传参跳转微信小程序_网页带参打开微信小程序

网页带参打开微信小程序

1.获取微信access_token并生成Url Scheme

@Slf4j
@Api(tags = "微信模块")
@RestController
@RequestMapping("/weChat")
public class WeChatController {


    @Autowired
    private WeChatService weChatService;
    @Autowired
    private RedisUtil redisUtil;
    @Value("${wxConfig.app-id}")
    private String AppID;
    @Value("${wxConfig.app-secret}")
    private String AppSecret;

    

    /**
     * @return {@link String}
     * @author macro
     * @description 获取微信小程序token
     */
    @AutoLog(value = "获取微信小程序token")
    @ApiOperation(value = "获取微信小程序token", notes = "获取微信小程序token")
    @GetMapping(value = "/getAccessToken")
    public String getAccessToken() throws IOException {
        //1.先判断redis有没有
        if (redisUtil.hasKey("access_token")) {
            //redis有直接返回
            return redisUtil.get("access_token").toString();
        } else {
            //2.redis没有
            /*2.1请求微信 获取token*/
            String httpUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
            httpUrl = httpUrl + "&appid=" + AppID + "&secret=" + AppSecret;
            CloseableHttpClient client = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(httpUrl);
            CloseableHttpResponse res = client.execute(httpGet);
            HttpEntity entity = res.getEntity();
            String result = EntityUtils.toString(entity, "UTF-8");
            JSONObject jsonObject = JSON.parseObject(result);
            if (jsonObject.containsKey("access_token")) {
                String accessToken = jsonObject.getString("access_token");
                //放入redis,并设置过期时间为两小时
                redisUtil.set("access_token", accessToken);
                redisUtil.expire("access_token", 2 * 60 * 60);
                return accessToken;
            } else {
                return null;
            }
        }
    }


    /**
     * @return {@link Map< String, Object>}
     * @author macro
     * @description 生成小程序跳转链接
     */
    @AutoLog(value = "生成小程序跳转链接")
    @ApiOperation(value = "生成小程序跳转链接", notes = "生成小程序跳转链接")
    @PostMapping(value = "/getAppletUrl")
    public Result<?> getAppletUrl(@RequestBody UrlSchemeQueryDTO queryEntity) throws IOException {
        //校验参数,参数都传递了才能生成url并跳转
        if (StringUtils.isBlank(queryEntity.getDyId()) || StringUtils.isBlank(queryEntity.getJumpPath()) ||
                null == queryEntity.getCoinAmt() || BigDecimal.ZERO.compareTo(queryEntity.getCoinRmb()) == 0) {
            return Result.error("请求参数非法!");
        }

        //微信生成 URL Scheme接口地址
        String httpUrl = "https://api.weixin.qq.com/wxa/generatescheme?access_token=";
        //需要跳转的小程序路径
        String path = "pages/pay/index";
        //获取AccessToken
        String AccessToken = this.getAccessToken();
        //token为空,报错返回
        if (AccessToken == null) {
            return Result.error("未获取到token!");
        } else {
            /*token非空 拿着token去请求*/
            try {
                JSONObject jsonParam = new JSONObject();
                JSONObject jump_wxa = new JSONObject();
                //跳转参数-跳转的页面路径
                jump_wxa.put("path", queryEntity.getJumpPath());
                jump_wxa.put("query", "dyId=" + queryEntity.getDyId() + "&coinAmt=" + queryEntity.getCoinAmt() + "&coinRmb=" + queryEntity.getCoinRmb().toString());
                //小程序环境  release:正式
                jump_wxa.put("env_version", "release");
                //跳转到的目标小程序信息。
                jsonParam.put("jump_wxa", jump_wxa);
                //默认值0,到期失效的 scheme 码失效类型,失效时间:0,失效间隔天数:1
                jsonParam.put("expire_type", 1);
                //到期失效的 scheme 码的失效间隔天数。生成的到期失效 scheme 码在该间隔时间到达前有效。最长间隔天数为30天。is_expire 为 true 且 expire_type 为 1 时必填
                jsonParam.put("expire_interval", 2);
                String params = jsonParam.toString();
                //请求微信接口,获取url
                JSONObject resultUrl = getUrlScheme(httpUrl, AccessToken, params);

                //请求微信接口,生成失败,返回错误码及错误信息
                if (!resultUrl.getString("errcode").equals("0")) {
                    return Result.error(resultUrl.getString("errcode"), resultUrl.getString("errmsg"));
                }
                /*请求成功 返回url*/
                String newUrl = resultUrl.getString("openlink");
                return Result.ok(newUrl);
            } catch (SocketTimeoutException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * @param httpUrl     微信接口的url
     * @param accessToken token
     * @param params      请求参数
     * @author: macro
     * @description: 请求URL Scheme接口,获取url
     * @return: com.alibaba.fastjson.JSONObject URL
     **/
    private JSONObject getUrlScheme(String httpUrl, String accessToken, String params) throws IOException {
        String content;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(300 * 1000)
                .setConnectTimeout(300 * 1000)
                .build();
        HttpPost post = new HttpPost(httpUrl + accessToken);
        post.setConfig(requestConfig);
        post.setHeader("Content-Type", "application/json;charset=utf-8");
        //URLEncoder.encode(name)
        StringEntity postingString = new StringEntity(params, "utf-8");
        post.setEntity(postingString);
        CloseableHttpResponse response = httpClient.execute(post);
        content = EntityUtils.toString(response.getEntity());
        JSONObject resultUrl = JSONObject.parseObject(content);
        return resultUrl;
    }


}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144

2.前端获取Url Scheme跳转到微信小程序

wxPay() {
        // ======================获取跳转的URL==============================
        //跳转的微信小程序的路径,传递给后端进行处理
        this.info.jumpPath="pages/pay/index"
        /*获取URL*/
        let jumpUrl=''
        uni.request({
          url: configService.apiUrl + this.url.getAppletUrl,
          method: 'POST',
          data: this.info,
          success: (result) => {
            if(result.data.success){
              jumpUrl=result.data.result
              //获取到URL进行跳转
              window.location.href=jumpUrl
            }
          },
          fail: function (err) {
            uni.showToast({
              title: '打开失败,请稍后再试!',
              icon: 'none',
              duration: 2000
            })
          }
        });
			},
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/553102
推荐阅读
相关标签
  

闽ICP备14008679号