
便捷蛙
文章
背景:
微信的快速崛起,使得微信扫码这个功能越来越普遍。今天就简单的介绍一下JS调用微信扫码的功能。
既然是微信要实现的功能,所以当然和微信脱不了干系。我们必须要引入微信的JS-SDK文件,这里介绍一下原生js实现方式。
登录微信公众平台:https://mp.weixin.qq.com/ 进行账号注册。
1、 通过左侧菜单点击 设置与开发 >> 基本配置 功能获取:AppID, AppSecret。
2、配置IP白名单
白名单的配置决定了是否有权限调用微信接口获取签名所需的access_token和jsapi_ticket
通过左侧菜单进入开发=》接口权限可查看所有接口调用权限,调用限制次数等信息。
引入JS-SDK文件
<script src="http://res2.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
前端调用代码(参考):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="jquery-3.3.1.min.js"></script>
</head>
<style>
body{
font-size: 20px;
}
button{
padding: 10px 15px;
background-color: #333;
color: white;
border: 0;
font-size: 18px;
margin: 20px;
}
</style>
<body>
<div class="">
<button onclick="choosePic()">上传照片</button>
<button onclick="bindScanQRCode()">扫一扫</button>
<button onclick="getLocationFun()">获取当前位置</button>
<button onclick="getuserInfo()">微信授权</button>
<div>
<img id="upimg" onclick="bindPreviewImage()" src="" />
上传图片,可点击图片预览
</div>
<p id="get-location"></p>
<!-- <p id="serverid"></p> -->
</div>
<script type="text/javascript" src="http://res2.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
<script>
//拼接参数
function getParam(data){
let url = '';
for(var k in data){
let value = data[k] !==undefined ? data[k] : '';
url += `&${k}=${encodeURIComponent(value)}`
}
return url ? url.substring(1) : ''
};
//随机字符串
function randomWord(randomFlag, min, max) {
let str = "",
range = min,
arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
if (randomFlag) {
range = Math.round(Math.random() * (max - min)) + min;// 任意长度
}
for (let i = 0; i < range; i++) {
pos = Math.round(Math.random() * (arr.length - 1));
str += arr[pos];
}
return str;
};
//随机字符串 、时间戳可写后台 一并返回
const w_timestamp = Math.round(new Date().getTime()/1000).toString();//时间戳
const w_appid = "wx53c2286d072ecd42";
const r_words = randomWord(true,16,16);
let imgUrl = ""; //图片链接
$.ajax({ //
type: "POST",
url: "https://***.com/api/v1/GetSignature",
data:{
"AppId": w_appid,
"NonceStr": r_words,
"TimeStamp": w_timestamp,
"Url": window.location.href,
"RefreshCache": 0
},
async: true,
success: function (data) {
if(data.Code!==200) return;
// 初始化微信配置
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: w_appid, // 公众号的唯一标识
timestamp: w_timestamp, // 生成签名的时间戳
nonceStr: r_words, // 生成签名的随机串
signature: data.Data,// 签名,
jsApiList: ["chooseImage","uploadImage","scanQRCode","getLocation"] //需要使用的JS接口列表
});
}
});
//图片选择
function choosePic() {
wx.chooseImage({
count: 1, // 默认9
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success:(res)=>{
var localIds = res.localIds; // 返回选定照片的本地列表
upimgWxData(localIds[0]);
}
});
};
//上传图片到媒体
function upimgWxData(localid) {
console.log(localid)
console.log('上传媒体')
wx.uploadImage({
localId: localid, // 需要上传的图片的本地ID
isShowProgressTips: 1,// 默认为1,显示进度提示
success: function (res) {
console.log(res)
const serverId = res.serverId; // 返回图片的服务器端ID
//document.getElementById("serverid").innerHTML = serverId;
$.ajax({ //上传图片
url: "https://***.com/api/v1/SaveImgByMaterialId",
type: "POST",
data:{
"AppId": w_appid,
"MaterialId": serverId
},
async: true,
success:(res)=> {
if(res.code==200){
console.log(res.Data)
imgUrl = res.Data.URL;
document.getElementById("upimg").src = imgUrl;
return;
}
console.log('图片上传失败!')
},
fail:(err)=>{
console.log('图片上传失败!')
},
})
}
});
};
//预览图片
function bindPreviewImage(){
wx.previewImage({
current: imgUrl, // 当前显示图片的http链接
urls: [imgUrl] // 需要预览的图片http链接列表
});
};
//扫码
function bindScanQRCode(){
wx.scanQRCode({
needResult: 0, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码,默认二者都有
success: function (res) {
console.log(res);
}
});
};
//获取地理位置
function getLocationFun(){
wx.getLocation({
type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
success: function (res) {
document.getElementById("get-location").innerHTML = "维度:"+res.latitude+"经度:"+res.longitude;
}
});
};
//微信授权
function getuserInfo(){
let local = window.location.href,state=null;
if(local.indexOf("?")!=-1){ //传递参数(可不传)
state = local.substring(local.indexOf("?")+1,local.length);
state = encodeURIComponent(state); //转码
};
const m_url ="https://open.weixin.qq.com/connect/oauth2/authorize";
const params = {
appid:w_appid,
// 授权回调地址
redirect_uri: "https://***.com/callback",
response_type:"code",
scope:"snsapi_userinfo",
state:state //"3d6be0a4035d839573b04816624a415e" 自定义参数
};
//用户同意授权,跳转,即可获取code - 通过code传递给后端换取openid
window.location.href= m_url+"?"+getParam(params)+"#wechat_redirect";
};
</script>
</body>
</html>
下一篇>
没有下一篇咯~
点击登录,秀出你的神评!