本文主要是介绍webForm 与 Vue 做微信公众号做扫一扫功能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、引用JS
webForm 是在 aspx页面引用的微信的JS与Css
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.css" /><script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script><script type="text/javascript" src="http://code.jquery.com/mobile/1.4.4/jquery.mobile-1.4.4.min.js"></script><script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script><script type="text/javascript" src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
Vue 框架是 需要引用一个 weixin-jsapi 插件
// 下载安装命令
npm install weixin-jsapi --save
// 在man.js中引入 weixin-jsapi
import wx from "weixin-jsapi";
二、在js中配置wx.config 与 wx.ready
wx.config({debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。appId: 'wx2ba651e123456ca', // 必填,公众号的唯一标识timestamp: timestamp, // 必填,生成签名的时间戳(随便填写)nonceStr: noncestr, // 必填,生成签名的随机串(随便填写)signature: signature, // 必填,签名,见附录1jsApiList: ['scanQRCode'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2});wx.ready(function () {// config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。wx.scanQRCode({needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码,默认二者都有success: function (res) {var result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果if (typeof (result) != "undefined") {//alert(result);扫码成功后返回的结果,二维码条码的内容window.location.href = result;} else {alert('扫描失败!');}}});});wx.error(function (res) {//alert(res);// config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。});
重要配置的是wx.config中的内容,配置不对打不开扫一扫,signature 我是后台调用接口获取的
后台写的一个wxHelper.cs 类,返回 的是三个参数 timestamp 、noncestr、signature
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections.Generic;
using System.Net;
using FoodSDC.DAL;/// <summary>
/// wxHelper 的摘要说明
/// </summary>
public partial class wxHelper
{/// <summary>/// 签名生成时间/// </summary>public static string dtime = "";/// <summary>/// 签名提交url地址/// </summary>public static string url = "";/// <summary>/// 生成签名的时间戳/// </summary>public static string time = "";/// <summary>/// 生成签名的随机串/// </summary>public static string randstr = "";/// <summary>/// 签名/// </summary>public static string signstr = "";/// <summary>/// appid 自己公众号的/// </summary>private readonly static string appid = "wx2ba132456421ca";/// <summary>/// secret /// </summary>private readonly static string secret = "e416546546546464613fc";/// <summary>/// AccessToken(生成AccessToken(返回信息))/// </summary>public static string access_token = "";public wxHelper(){//// TODO: 在此处添加构造函数逻辑//}/// <summary>/// 获得accesstoken/// </summary>/// <returns></returns>public static string AccessToken(){return SendRequest("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret, Encoding.UTF8);}/// <summary>/// 根据accesstoken获得ticket/// </summary>/// <returns></returns>public static string GetTicket(){access_token = AccessToken();string url1 = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token.Substring(access_token.IndexOf(':') + 2, access_token.IndexOf(',') - 3 - access_token.IndexOf(':')) + "&type=jsapi";string requstStr = SendRequest(url1, Encoding.UTF8);string ticket = requstStr.Substring(requstStr.IndexOf("ticket") + 9, requstStr.LastIndexOf(',') - 1 - requstStr.IndexOf("ticket") - 9);// 获得json参数没搞,懂的自己优化return ticket;}/// <summary>/// 获取jssdk所需签名/// </summary>/// <param name="url"></param>/// <returns></returns>public static string GetSignature(string link){DateTime dti = DateTime.Now;dtime = dti.ToString("yyyy-MM-dd HH:mm:ss");string noncestr = dti.ToString("yyyyMMddHHmmss");int timestamp = 1510124527;string ticket = GetTicket();time = "1510124527";randstr = noncestr;string string1 = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "×tamp=" + timestamp + "&url=" + link;url = string1;//string signature = System.Web.FormsAuthentication.HashPasswordForStoringInConfigFile(string1, "SHA1");string signature = Sha1Signature(string1, Encoding.UTF8);return signature.ToLower(); // 生成后一定转换为小写}/// <summary>/// Sha1签名/// </summary>/// <param name="str">内容</param>/// <param name="encoding">编码</param>/// <returns></returns>private static string Sha1Signature(string str, Encoding encoding = null){if (encoding == null) encoding = Encoding.UTF8;var buffer = encoding.GetBytes(str);var data = System.Security.Cryptography.SHA1.Create().ComputeHash(buffer);StringBuilder sub = new StringBuilder();foreach (var t in data){sub.Append(t.ToString("x2"));}return sub.ToString();}/// <summary> /// Get方式获取url地址输出内容 /// </summary> /// <param name="url">url</param> /// <param name="encoding">返回内容编码方式,例如:Encoding.UTF8</param> public static string SendRequest(string url, Encoding encoding){HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);webRequest.Method = "GET";HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();StreamReader sr = new StreamReader(webResponse.GetResponseStream(), encoding);string str = sr.ReadToEnd();return str;}/// <summary>/// 将值记录到数据库中防止出现调用限制/// </summary>/// <param name="url"></param>public static void SignatureAdd(string link){time = "";randstr = "";signstr = "";signstr = GetSignature(link);string sqlI = "insert into wxinfo(timestamp,nonceStr,signature,time,url,link,access_token) values('" + time + "','" + randstr + "','" + signstr + "','" + dtime + "','" + url + "','" + link + "','" + access_token + "') ";int count = SQLHelper.ExecuteNonQuery_SY(sqlI, null);}/// <summary>/// 获得微信权限信息,格式:时间戳,随机数,签名/// </summary>/// <param name="link"></param>/// <returns></returns>public static string GetWXInfo(string link){bool result = false;// 获得最后一条新增数据string sql = " select top 1 * from wxinfo where link='" + link + "' order by id desc ";//DataTable dt = DbHelperMySQL.GetTable(sql);DataTable dt = SQLHelper.ExecuteDataSet_SY(sql, null).Tables[0];if (dt != null){if (dt.Rows.Count > 0){// 当前时间小于获得获得tincket时间时调用数据库中if (DateTime.Now < Convert.ToDateTime(dt.Rows[0]["time"].ToString()).AddSeconds(7200)){time = dt.Rows[0]["timestamp"].ToString();randstr = dt.Rows[0]["nonceStr"].ToString();signstr = dt.Rows[0]["signature"].ToString();url = dt.Rows[0]["url"].ToString();result = true;}}}if (result == false)SignatureAdd(link);return time + "," + randstr + "," + signstr;}}
将参数配置到wx.config中,如果还是打不开,就把 wx.config 中的 debug: true 进行调试 返回的错误信息会alert 出来,自己在做的时候遇到的两个问题,
第一个是,登录https://mp.weixin.qq.com/cgi-bin/safecenterstatus?action=view&t=setting/safe-index&token=2056975201&lang=zh_CN
将后台访问接口的服务器ip地址加入到微信公众号IP白名单中
第二个 是 将 前台网站的 域名 配置到微信公众号中
还需要将
这个文件 放在前端文件的目录中
其他问题,看微信开发文档基本都有 概述 | 微信开放文档
这篇关于webForm 与 Vue 做微信公众号做扫一扫功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!