微信小程序关联微信公众号调用微信jssdk,使用微信扫一扫功能

问题场景

这里是项目本身是vue写的H5项目,同时也需要小程序端,小程序端直接采用了H5内嵌的方式,这样其中的扫码功能就需要调用微信的jssdk。

JS-SDK说明文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html

 

配置部分:

一、绑定JS安全域名

1.由于JS安全域名只能公众号绑定,而我这里是小程序要调用,所以必须先绑定个公众号

进入微信公众平台:mp.weixin.qq.com

登录公众号管理后台:广告与服务——小程序管理——小程序管理——添加——关联小程序

2.绑定JS安全域名

设置与开发——公众号设置——功能设置——JS接口安全域名——设置

注意事项:

(1)设置之前需要把txt文件上传至填写域名或路径指向的web服务器(或虚拟主机)的目录;

若填写域名,将文件放置在域名根目录下,例如wx.qq.com/MP_verify_RzcCVFkrKfNloGsA.txt;

若填写路径,将文件放置在路径目录下,例如wx.qq.com/mp/MP_verify_RzcCVFkrKfNloGsA.txt,并确保可以访问

(2)这里填写的是域名,不带https://

 

 

代码部分:

一、引入JS文件

1.这里采用模块方式引入

npm install jweixin-module --save

 

二、前端代码

1.页面引入JS

import jweixin from 'jweixin-module'

 2.页面代码

onLoad():

onLoad() {
    let en = window.navigator.userAgent.toLowerCase()
    if (en.match(/MicroMessenger/i) == 'micromessenger') {
  //如果是微信环境
this.getJsApiConfig(); } },

 

methods:


// 调用接口获取config信息
getJsApiConfig() {
const apiUrl = location.href.split('#')[0];
// let finalUrl = apiUrl.slice(0,apiUrl.length-1)
console.log(apiUrl)
uni.request({
url: http.requestUrl + '/jsapi/getSign',
methods: 'GET',
data: {
tokenUrl: apiUrl // 当前页面的域名
},
success: (resopnse) => {
if (resopnse.statusCode == 200) {
this.getConfig(resopnse.data);
}
}
});
},
getConfig(res) {
// 配置config信息
jweixin.config({
debug: false,
appId: res.appId, // 必填,公众号的唯一标识
timestamp: res.timestamp, // 必填,生成签名的时间戳
nonceStr: res.nonceStr, // 必填,生成签名的随机串
signature: res.signature, // 必填,签名
jsApiList: ['scanQRCode'] // 必填,需要使用的JS接口列表
});
// 通过ready接口处理成功验证
jweixin.ready(function() {
jweixin.checkJsApi({
jsApiList: ['scanQRCode'],
success: function(res) {
console.log('检验成功');
}
});
});
// 通过error接口处理失败验证
jweixin.error(function(res) {
console.log('校验失败');
});
},

扫码:

jweixin.scanQRCode({
  needResult: 0, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
  scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码,默认二者都有
  success: function (res) {
    var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果
  }
});

 

三、后台代码(JAVA)

 

controller:

import com.alibaba.fastjson.JSON;
import com.insigma.business.yzrc.wxconfig.util.Constants;
import com.insigma.business.yzrc.wxconfig.service.wxJsServiceImpl;
import com.insigma.business.yzrc.wxconfig.util.HttpClientUtil;
import com.insigma.business.yzrc.wxconfig.entity.WXTokenModel;
import com.insigma.business.yzrc.wxconfig.util.RedisOperator;


import com.insigma.framework.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/jsapi")

public class WxConfigController {
    @Autowired
    @Qualifier("wxJsService")
    private wxJsServiceImpl jsApiService;

    @Autowired
    RedisOperator redisOperator;

    @GetMapping(value = "/getSign")
    @ResponseBody
    public Map<String, String> scanJsApi(@Param("tokenUrl") String tokenUrl, HttpServletRequest request) {
        Map<String, String> res = jsApiService.sign(tokenUrl);
        return res;
    }

    /**
     * 获取公众号的access_token
     *
     * @return
     */
    @GetMapping("/getAccessToken")
    public ResponseMessage getAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token";
        Map<String, String> param = new HashMap<>(16);
        param.put("grant_type", "client_credential");
        param.put("appid", Constants.GZH_APPID);
        param.put("secret", Constants.GZH_SECRET);
        String wxResult = HttpClientUtil.doGet(url, param);
        System.out.println(wxResult);
        WXTokenModel model = JSON.parseObject(wxResult, WXTokenModel.class);
        redisOperator.set(Constants.GZH_TOKEN, model.getAccess_token(), Long.parseLong(model.getExpires_in()));
        return ResponseMessage.ok(model);
    }

}

 

WXTokenModel实体类:
public class WXTokenModel {
    private String access_token;
    private String expires_in;
    private String errcode;
    private String errmsg;

    public String getAccess_token() {
        return access_token;
    }

    public void setAccess_token(String access_token) {
        this.access_token = access_token;
    }

    public String getExpires_in() {
        return expires_in;
    }

    public void setExpires_in(String expires_in) {
        this.expires_in = expires_in;
    }

    public String getErrcode() {
        return errcode;
    }

    public void setErrcode(String errcode) {
        this.errcode = errcode;
    }

    public String getErrmsg() {
        return errmsg;
    }

    public void setErrmsg(String errmsg) {
        this.errmsg = errmsg;
    }
}

 

Service层:

import com.alibaba.fastjson.JSON;
import com.insigma.business.yzrc.wxconfig.entity.WXTokenModel;
import com.insigma.business.yzrc.wxconfig.util.*;
import com.insigma.framework.ResponseMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

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

@Component("wxJsService")
@Transactional

public class wxJsServiceImpl {


    @Autowired
    private RedisOperator redis;

    /**
     * 获取签名
     *
     * @param url
     * @return
     */
    public Map<String, String> sign(String url) {

        Map<String, String> resultMap = new HashMap<>(16);

        //这里的jsapi_ticket是获取的jsapi_ticket。
        String jsapiTicket = this.getJsApiTicket();
        //这里签名中的nonceStr要与前端页面config中的nonceStr保持一致,所以这里获取并生成签名之后,还要将其原值传到前端
        String nonceStr = createNonceStr();
        //nonceStr
        String timestamp = createTimestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写,且必须有序
        string1 = "jsapi_ticket=" + jsapiTicket +
                "&noncestr=" + nonceStr +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println("string1:" + string1);

        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();
        }

        resultMap.put("url", url);
        resultMap.put("jsapi_ticket", jsapiTicket);
        resultMap.put("nonceStr", nonceStr);
        resultMap.put("timestamp", timestamp);
        resultMap.put("signature", signature);
        resultMap.put("appId", Constants.GZH_APPID);

        return resultMap;
    }

    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 createNonceStr() {
        return UUID.randomUUID().toString();
    }

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

    public String getJsApiTicket() {
        CacheObjectType cacheObject = CacheObjectType.WX_TOKEN;
        String ticket = redis.get(cacheObject.getPrefix() + "jsapi_ticket");
        if (StringUtils.isBlank(ticket)) {
            ticket = WechatUtil.getJsApiTicket(this.getAccessToken());
            redis.set(cacheObject.getPrefix() + "jsapi_ticket", ticket,
                    cacheObject.getExpiredTime());
        }
        return ticket;
    }

    public String getAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token";
        String accessToken = "";
        Map<String, String> param = new HashMap<>(16);
        param.put("grant_type", "client_credential");
        param.put("appid", Constants.GZH_APPID);
        param.put("secret", Constants.GZH_SECRET);
        String wxResult = HttpClientUtil.doGet(url, param);
        System.out.println(wxResult);
        WXTokenModel model = JSON.parseObject(wxResult, WXTokenModel.class);
        redis.set(Constants.GZH_TOKEN, model.getAccess_token(), Long.parseLong(model.getExpires_in()));
        accessToken = model.getAccess_token();
        return accessToken;
    }

    private String getToken() {
        String token = redis.get(Constants.GZH_TOKEN);
        return token;
    }
}

 

Util类:

CacheObjectType:
public enum CacheObjectType {

    VERIFY_CODE("sms:S:code:", 60 * 5),

    WX_TOKEN("wx:S:token", 7000);

    private String prefix;
    private int expiredTime;

    CacheObjectType(String prefix, int expiredTime) {
        this.prefix = prefix;
        this.expiredTime = expiredTime;
    }

    public String getPrefix() {
        return prefix;
    }

    public int getExpiredTime() {
        return expiredTime;
    }
}

 

Constants:
public class Constants {
    //换取ticket的url
    public static final String JSAPI_TICKET = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
    //微信公众号token在redis中存储时的key值
    public static final String GZH_TOKEN = "wx-access-token";

    public static final String AppDomain = "hrss.yangzhou.gov.cn";
    //小程序
//    public static final String GZH_APPID = "wx4903dedb037fe45e";
//    public static final String GZH_SECRET = "0dcc0e3c15b4a3fb18373102e8d326bf";

    //公众号
    public static final String GZH_APPID = "wx069b430b09218c0f";
    public static final String GZH_SECRET = "d7be3dcb059e1499dbc16dc7f93ec482";

}

 

HttpClientUtil:
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpClientUtil {


    public static String doGet(String url, Map<String, String> param) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPost(String url) {
        return doPost(url, null);
    }

    public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

}

 

RedisOperator:
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisOperator {

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 实现命令:SET key value,设置一个key-value(将字符串值 value关联到 key)
     *
     * @param key
     * @param value
     */
    public void set(String key, String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 实现命令:SET key value EX seconds,设置key-value和超时时间(秒)
     *
     * @param key
     * @param value
     * @param timeout (以秒为单位)
     */
    public void set(String key, String value, long timeout) {
        redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
    }

    /**
     * 实现命令:GET key,返回 key所关联的字符串值。
     *
     * @param key
     * @return value
     */
    public String get(String key) {
        return (String) redisTemplate.opsForValue().get(key);
    }
}

WechatUtil:
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

/**
 * 微信工具类
 */
public class WechatUtil {

    /**
     * 获得jsapi_ticket
     */

    public static String getJsApiTicket(String token) {
        String url = Constants.JSAPI_TICKET
                + "?access_token=" + token
                + "&type=jsapi";

        String response = HttpClientUtil.doGet(url);

//        WXSessionModel model = JsonUtils.jsonToPojo(response, WXSessionModel.class);

//        String response = OkHttpUtil.doGet(url);
        if (StringUtils.isBlank(response)) {
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(response);
        System.out.println(response);
        String ticket = jsonObject.getString("ticket");
        return ticket;
    }

}

/getSign接口调用成功返回的接口案例:

 

 

 成功调用微信开发者工具控制台返回:

 

 

 

提示:

1.用开发者工具调试的时候,如果控制台看不出是什么原因,可以这样做:

微信开发者工具——调试——调试微信开发者工具——network,再重新进入一下页面,查看network中的preverify中的erify_info_list,里面会有报错和错误编码,方便大家百度。

2.如果是和本项目场景一样,是小程序绑定公众号调用,那么后台传入的appid和appsecret一定要是公众号的appid和appsecret,

而不是小程序的。这个大坑给我卡了一天,因为小程序有webview组件可以调用jssdk,但是jssdk还是公众号的,相当于小程序给你个容器,东西还是公众号的。

3.祝大家成功调用,欢迎留言交流~

 

posted @ 2022-06-21 11:13  Teemo_zhao  阅读(2944)  评论(1编辑  收藏  举报