A starter template for TypeScript and WeChat with a detailed README describing how to use the two together.
TypeScript JavaScript HTML
Switch branches/tags
Nothing to show
Clone or download
Latest commit 3fb8b46 Nov 13, 2017
sandersn committed Nov 13, 2017 Merge pull request #2 from Microsoft/update-request-types
@types/request has same major version as request
Permalink
Failed to load latest commit information.
images initial commit May 9, 2017
public/js initial commit May 9, 2017
types initial commit May 9, 2017
views initial commit May 9, 2017
.gitignore initial commit May 9, 2017
LICENSE Initial commit May 9, 2017
README.md initial commit May 9, 2017
README_en.md initial commit May 9, 2017
index.js initial commit May 9, 2017
index.ts initial commit May 9, 2017
package.json @types/request has same major version as request Nov 10, 2017
tsconfig.json initial commit May 9, 2017

README.md

English version

本教程将覆盖了基本的在使用微信JSSDK的网页上运用TypeScript的例子。

开始之前

  1. 安装node.js

  2. 拥有/申请网页将使用的域名以及能够使用Node.js的服务器。可参照Create a Node.js Application on Web App文档使用Azure。

  3. 完成微信开发文档步骤一:绑定域名。如果没有自己的公众号,可注册并使用微信测试号。记录下自己的appId, appsecret以及将使用的host URL。

搭建node.js/express后台

初始

建立一个新的npm package,

mkdir wxapp
cd wxapp
npm init

在生成的package.jsonscripts中添加以下scripts,

"scripts": {
    "start": "node index.js",
    "build-ts": "node ./node_modules/typescript/bin/tsc"
},

安装需要的packages(express, ejs, request以及sha1),

npm install --save express ejs request sha1

安装TypeScript以及之前安装的packages的类型定义。

npm install --save-dev typescript @types/node @types/express @types/request @types/sha1

由于暂时DefinitelyTyped中并没有JSSDK相关的类型定义文件(.d.ts),请将本项目中的types文件夹(包含类型定义文件wechat.d.ts)复制到根目录(wxapp)中以便TypeScript获取JSSDK的类型定义。

配置TypeScript

wxapp根目录下添加TypeScript配置文件tsconfig.json

{
  "compilerOptions": {
    "target": "es6",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'. */
    "moduleResolution": "node"                /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
  }
}

可以根据项目的需求自行添加其他编译选项,比如strict

获取jsapi_ticket

对应通过config接口注入权限验证配置文档,调用微信JSSDK需要在自己的服务器后台向微信服务器获取jsapi_ticket并在前端通过wx.config进行验证。大致实现流程,

在根目录添加后台的初始文件index.ts

import * as express from "express";
import * as request from "request";
import sha1 = require("sha1");

let app = express(); 

// Insert metadata
let appId = '';             // Insert your appId
let appsecret = '';         // insert your appsecret
let url = '';               // insert host url, e.g. http://wxapp.azurewebsites.net/
let nonceStr = '';          // insert any string

// define an interface containing params for wx.config
interface configObj {
    appId: string,
    timestamp: string,
    nonceStr: string,
    signature: string
}

// handshake with WeChat server and get signature for wx.config
function getWXConfig(cb) {
    request.get('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+appId+'&secret='+appsecret, (err, res, body) => {
        request.get('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='+JSON.parse(body).access_token+'&type=jsapi', (err, res, body) => {
            let ticket = JSON.parse(body).ticket;
            let o: configObj = {
                appId: appId,
                nonceStr: nonceStr, 
                timestamp: new Date().getTime() / 1000 + '',
                signature: ''
            };
            o.signature = sha1('jsapi_ticket='+ticket+'&noncestr='+o.nonceStr+'&timestamp='+o.timestamp+'&url='+url).toString();
            cb(o);
        });
    });
}

app.engine('.html', require('ejs').__express);          // set up ejs as view engine
app.set('views', __dirname + '/views');                 // set views dir
app.set('view engine', 'html');                         // use .html for ejs files
app.use(express.static('public'))                       // expose assets in /public
app.get('/', function (req, res) {
    getWXConfig(config => {
        // handshake with WeChat server and render index.html with the returned signature
        res.render('index', {
            appId: config.appId,
            timestamp: config.timestamp,
            nonceStr: config.nonceStr,
            signature: config.signature,
        });
    })
});
app.listen(8080);

index.ts中修改并填入自己的appId等等参数,

// Insert metadata
let appId = '';                     // Insert your appId
let appsecret = '';                 // insert your appsecret
let url = '';                       // insert host url, e.g. http://wxapp.azurewebsites.net/
let nonceStr = 'hellotypescript';   // insert any string

建立的node.js+express后台会通过getWXConfig向微信服务器获取jsapi_ticket,并将wx.config所需的参数通过ejs渲染(res.render(...))至客户端页面。

index.ts中已定义将后台推至客户端的文件放入/views(包含所有需要ejs渲染的html文件)以及/public(其余的文件)文件夹。之后的步骤将覆盖前端的页面。

app.set('views', __dirname + '/views');                 // set views dir
app.use(express.static('public'))                       // expose assets in /public

客户端页面

index.html

在根目录下建立views文件夹并在其中添加index.html(推至客户端的主页),

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title> WeChat TypeScript sample </title>
</head>
<body>
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script type="text/javascript">
    wx.config({
        debug: false,
        appId: '<%=appId%>',
        timestamp: '<%=timestamp%>',
        nonceStr: '<%=nonceStr%>',
        signature: '<%=signature%>',
        jsApiList: [
            'checkJsApi',
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareWeibo',
            'onMenuShareQZone',
            'hideMenuItems',
            'showMenuItems',
            'hideAllNonBaseMenuItem',
            'showAllNonBaseMenuItem',
            'translateVoice',
            'startRecord',
            'stopRecord',
            'onVoiceRecordEnd',
            'playVoice',
            'onVoicePlayEnd',
            'pauseVoice',
            'stopVoice',
            'uploadVoice',
            'downloadVoice',
            'chooseImage',
            'previewImage',
            'uploadImage',
            'downloadImage',
            'getNetworkType',
            'openLocation',
            'getLocation',
            'hideOptionMenu',
            'showOptionMenu',
            'closeWindow',
            'scanQRCode',
            'chooseWXPay',
            'openProductSpecificView',
            'addCard',
            'chooseCard',
            'openCard'
        ]
    });
</script>
<script type="text/javascript" src="/js/demo.js"></script>
</body>
</html>

index.html中引入了微信JSSDK(http://res.wx.qq.com/open/js/jweixin-1.0.0.js)以及将在客户端实现的简单的demo(/js/demo.js)。嵌入的JavaScript包含了之前渲染的getWXConfig提供的讯息并通过wx.config注入权限验证配置。

demo.ts

在根目录下建立public/js文件夹,并在其中添加demo.ts,

wx.ready(() => {
    // open specifc location on map
    wx.openLocation({
        latitude: 0,
        longitude: 0,
        name: '',
        address: '',
        scale: 1,
        infoUrl: ''
    });
})

wx.error((err) => alert(err));

在这个简化的例子中,我们仅使用wx.openLocation打开地图,但在demo.ts中你可以尝试使用任何在JsApiList中申请的API。

生成与部署

.ts文件编译成.js

npm run build-ts

部署至服务器。

将页面所在的网址转换成二维码,打开微信扫一扫便可看到成果。