在上小节介绍了cordova中如何使用cordova-plugin-wechat
1.创建微信应用
在微信开放平台注册一个账号,然后创建一个应用,填写相应的资料,最后提交等待审核。
审核通过后,就会获得AppID
和 AppSecret
2.添加插件
在添加插件前,请先创建一个cordova项目,参考第一小节。
cordova plugin add cordova-plugin-wechat --variable wechatappid=YOUR_WECHAT_APPID
cordova build android
3.在web工程调用
www/index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="initial-scale=1, width=device-width, viewport-fit=cover">
<link rel="stylesheet" type="text/css" href="css/index.css">
<title>Hello World</title>
</head>
<body>
<div class="app">
<h1>Apache Cordova</h1>
<button id="wechat">微信</button>
<div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p>
</div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
www/js/index.js
//代码最后添加
document.getElementById('wechat').addEventListener('click', function () {
var scope = "snsapi_userinfo";
var state = "_" + (+new Date());
Wechat.auth(scope, state, function (response) {
// you may use response.code to get the access token.
alert(JSON.stringify(response));
}, function (reason) {
alert("Failed: " + reason);
});
})