Website search box uses WeChat scanner


Customers require that certain instruments and devices be managed by a tag QR code, just like the Taobao search box which can directly take photos of the search product.A previous one has been made Web page calls the function of camera to recognize QR code , which has two drawbacks:

  • Recognition needs to be taken first, not directly identified
  • Recognition rate is low, especially photo jitter. A little more QR code content or a little smaller QR code will not be recognized.

Adding these two points together is pretty bad.

Use WeChat Scavenger

Since our system has been integrated into the WeChat Public Number, we are ready to invoke the WeChat scanner (only pages opened within WeChat can use the WeChat scanner).
Reference Official Documents

Bind Domain Name

Open Public Number Settings

Select Functional Settings

Add JS interface security domain name, note the file specified in WeChat in the last image below the domain name directory you added. If the file is not in the root directory, the domain name needs to be filled in to the subdirectory

Introducing JS files

Create a default mvc project using vs2019
Page reference js used in index.cshtml pages
<script src=""></script>

Front End Main Code

$(function () {
     * Determine whether WeChat opens pages internally
     * */
    function isWeiXin() {
        var ua = window.navigator.userAgent.toLowerCase();
        console.log(ua);//mozilla/5.0 (iphone; cpu iphone os 9_1 like mac os x) applewebkit/601.1.46 (khtml, like gecko)version/9.0 mobile/13b143 safari/601.1
        if (ua.match(/MicroMessenger/i) == 'micromessenger') {
            return true;
        else {
            return false;
     * Only WeChat internal page opens for use
     * */
    if (isWeiXin()) {
            type: "post",
            url: "/Home/GetSingDataAsync",
            data: {
                "url": location.href.split('#')[0]
            dataType: "json",
            success: function (data) {
                    debug: true, // Turn on debugging mode, and the return values of all APIs invoked will be displayed in the client alert. To view the incoming parameters, you can open them on the pc side, and the parameter information will be printed through the log, only on the pc side.
                    appId: data.appId, // Required, unique identification of public number
                    timestamp: data.timestamp, // Required, time stamp for signature generation
                    nonceStr: data.nonceStr, // Required, generate a random string of signatures
                    signature: data.signature,// Required, signed, see Appendix 1
                    jsApiList: [
                        'scanQRCode',// WeChat sweep interface
                    ] // Required, list of JS interfaces to use, all JS interfaces listed in Appendix 2
                wx.error(function (res) {
                    alert("Error:" + res.errMsg);//The advantage of this place is that wx.config is misconfigured, pop-up window where is wrong, and then query based on the WeChat document.
                wx.ready(function () {
                        jsApiList: ['scanQRCode'],
                        success: function (res) {
                            //Scan QR code
                                needResult: 1, // Default is 0, scan result is processed by WeChat, 1 returns scan result directly,
                                scanType: ["qrCode"], // You can specify whether to scan QR codes or QR codes, both of which are available by default
                                success: function (res) {
                                    var result = res.resultStr; // Return from scanner when needResult is 1
                                    alert(result);//Because I have a link on my side after scanning, and I jump to the page
                                error: function () {
            error: function (url) {
                alert("An error occurred!");
    } else {
        alert("Please use WeChat to open");

Backend Code

public class HomeController : Controller
    //Replace APPID and APP_SECRET with your own
    private const string APPID = "******";
    private const string APP_SECRET = "******";
    //For debugging purposes, I've written to the cache since I first got Token and Ticket here (7200s expires)
    private static string Token = "24_cQsz9scwyXLnPaAes5JlfHTfuQ2e3Iw5L8JyWfUpQiMnTk4IToOTZ7dP0Fv190ZHTy5ST--jeuDzYwoUj_hvhSHDX288YYLYVcrmvMzRPwld8ccTTzWGNTKZz53jYKDy5f8U1E886msDPsrwORGbAJABET";
    private static string Ticket = "HoagFKDcsGMVCIY2vOjf9qZA_fkPP3enjnT58qu16hzZN-3kwAP0NK6jgQM0jyAc0sK8cxaGkT9_DSgp6cHCpw";
    public ActionResult Index()

        return View();

    public ActionResult About()
        ViewBag.Message = "Your application description page.";

        return View();

    public ActionResult Contact()
        ViewBag.Message = "Your contact page.";

        return View();

    public async Task GetToken()
        await GetTicketAsync();
    //Get token and ticket
    private async Task<string> GetTicketAsync()

        var tokenUrl = $"{APPID}&secret={APP_SECRET}";

        var client = new System.Net.WebClient();
        client.Encoding = Encoding.UTF8;
        client.Headers.Add("Content-Type", "Application/x-www-form-urlencoded");
        var responseData = client.UploadData(tokenUrl, "POST", new byte[0]);
        var responseText = Encoding.UTF8.GetString(responseData);
        var token = JsonConvert.DeserializeAnonymousType(responseText, new { access_token = "", expires_in = "" });

        Token = token.access_token;
        var ticketUrl = $"{Token}&type=jsapi";
        var ticResponseData = client.UploadData(ticketUrl, "POST", new byte[0]);
        var ticResponseText = Encoding.UTF8.GetString(ticResponseData);
        var ticket = JsonConvert.DeserializeAnonymousType(ticResponseText, new { errcode = "", errmsg = "", ticket = "", expires_in = "" });
        Ticket = ticket.ticket;
        return "";
    //Get Signature String
    public async Task<string> GetSingDataAsync(string url)

        var sign = new SignData();
        sign.appId = APPID;
        sign.nonceStr = Create_nonce_str();
        sign.timestamp = Create_timestamp();
        //var url = Request.Url.AbsoluteUri;
        if (url.IndexOf('#') > 0)
            url = url.Substring(0, url.IndexOf('#'));
        sign.url = url;
        var string1 = "jsapi_ticket=" + Ticket +
                "&noncestr=" + sign.nonceStr +
                "&timestamp=" + sign.timestamp +
                "&url=" + sign.url;

        //var string1 = GetTestSign();

        var sha1 = SHA1.Create();
        sign.signature = ByteToHex(sha1.ComputeHash(Encoding.UTF8.GetBytes(string1)));
        return JsonConvert.SerializeObject(sign);
    //Test the signature string to see if the signature method is correct, as WeChat officially provided
    private string GetTestSign()
        var nonceStr = "Wm3WZYTPz0wzccnW";
        var ticket = "sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg";
        var timestamp = "1414587457";
        var url = "";
        var string1 = "jsapi_ticket=" + ticket +
                "&noncestr=" + nonceStr +
                "&timestamp=" + timestamp +
                "&url=" + url;
        return string1;

    /// <summary>
    ///Random String
    /// </summary>
    /// <returns></returns>
    private string Create_nonce_str()
        return Guid.NewGuid().ToString().Substring(0, 8);
    /// <summary>
    /// </summary>
    /// <returns></returns>
    private string Create_timestamp()
        return (DateTime.Now.Ticks / 100000000).ToString();
    private string ByteToHex(byte[] hash)
        var sb = new StringBuilder();
        foreach (var b in hash)
        return sb.ToString();

Code Uploaded github

Keywords: Javascript encoding SHA1 JSON Mac

Added by Jaxeed on Thu, 15 Aug 2019 09:44:47 +0300