微信公众号网页调用扫一扫功能,后台生成参数

参考资料:
https://www.cnblogs.com/shikaijie/p/9358781.html
https://zhuanlan.zhihu.com/p/89007691

文章目录

  • 前言
  • 一、使用步骤
    • 1.生成ticket工具
    • 2.生成sign工具类
  • 总结


前言

需求:公众号开发里面开发H5网页,需要调用微信扫一扫功能去进行扫码。步骤主要是先获取accessToken,然后通过accessToken去获取ticket,然后组装生成signature


提示:以下是本篇文章正文内容,下面案例可供参考

一、使用步骤

1.生成ticket工具

生成ticket:

public static String getTicket(){
        String urlToken="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APP_ID+"&secret="+APP_SECRET+"";
        String backToken = sendGet(urlToken, "utf-8", 6000);
        System.out.println("token:"+backToken);
        String accessToken = (String) JSONObject.parseObject(backToken).get("access_token");
        String url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+accessToken+"&type=jsapi";
        String backTicket = sendGet(url,"utf-8",60000);
        System.out.println("Ticket:"+backTicket);
        String ticket = (String) JSONObject.parseObject(backTicket).get("ticket");
        System.out.println(ticket);
        return ticket;

    }

请求工具:

public static String sendGet(String url, String charset, int timeout)
    {
        String result = "";
        try
        {

            try
            {
                URL u = new URL(url);
                URLConnection conn = u.openConnection();
                conn.connect();
                conn.setConnectTimeout(timeout);
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
                String line="";
                while ((line = in.readLine()) != null)
                {
                    result = result + line;
                }
                in.close();
            } catch (IOException e) {
                return result;
            }
        }
        catch (Exception e)
        {
            return result;
        }
        return result;
    }

2.生成sign工具类

代码如下(示例):



import com.bowu66.museumscience.model.dto.activity.WxConfigResult;
import lombok.experimental.UtilityClass;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.UUID;

@UtilityClass
public class WxSign {

    /**
     * 生成sign
     * @return 返回前端请求数据
     */
    public static WxConfigResult sign() {
        /*当前页面地址 与微信js接口域相呼应 **/
        String url = "前端调用扫一扫页面地址";
        /*获取微信需要的ticket**/
        String jsapi_ticket = WxUtils.getTicket();

        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写,且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "×tamp=" + timestamp +
                "&url=" + url;

        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return WxConfigResult.builder()
                .url(url)
                .jsapi_ticket(jsapi_ticket)
                .nonce_str(nonce_str)
                .signature(signature)
                .timestamp(timestamp)
                .appId(WxUtils.APP_ID)
                .build();
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 16);
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}

返回封装数据:

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class WxConfigResult implements Serializable {

    private static final long serialVersionUID = -9107757302735999076L;

    @ApiModelProperty("公众号appId")
    private String appId;
    @ApiModelProperty("前端调用扫一扫的功能的页面地址")
    private String url;
    @ApiModelProperty("生成的ticket")
    private String jsapi_ticket;
    @ApiModelProperty("生成秘钥使用的随机串")
    private String nonce_str;
    @ApiModelProperty("生成秘钥使用的时间戳")
    private String timestamp;
    @ApiModelProperty("生成的秘钥")
    private String signature;
}

前端请求

@PostMapping(value = "/getWxConfigs", produces = "application/json")
    public WxConfigResult getWxConfigs(HttpServletRequest request, HttpServletResponse response){
        return  WxSign.sign();
    }

总结

这样前端H5页面就可以调用微信扫一扫功能。公众里还需要设置一下JS请求域名,不然调用微信扫一扫会失败。

微信公众号网页调用扫一扫功能,后台生成参数_第1张图片

你可能感兴趣的:(工具类,java)