微信小程序的项目中wx.requert请求外部数据
1、注册小程序获取AppId和Appsecret
2、wx.login 获得 code;
3、发送 res.code 到后台换取 openId, sessionKey, unionId,源码如下:
wx.request({
url: 'https://api.weixin.qq.com/sns/jscode2session',
method: 'GET',
data: {
appid: 'appid',
secret: 'appsecret',
js_code: res.code,
grant_type: 'authorization_code'
},
success: function (res) {
wx.setStorage({ key: 'openid', data: res.data.openid });
}
})
4、以上操作都是微信小程序内部提交获取数据,接下来就是提交外部服务获取数据了。首先你得确保自己的外部服务是https 支持SSL的,因为小程序的wx.request必须是SSL协议的服务请求。然而这个SSL还必须要有个证书pfx;
5、SSL证书怎么来呢?我们只能用免费的啦!https://freessl.cn/ 推荐大家这个网站,很实用哦!免费生成SSL证书;
6、首先我们得有个域名,解析至你的服务器,SSL证书在生成时会自动生成一个TXT解析记录;
7、下载SSL证书,放置在服务器c:\cert\ssl.pfx。转到你域名dns解析上添加一条TXT解析记录,记录值上面freessl.cn网站生成证书时会给到你;
8、还没完,有了SSL证书你得配置你的服务了支持https访问。这个有多种方法,我这里用的是.NET Core 所以配置如下:
首先你得监听https 端口:先创建一个json配置文件,我们取名host.josn
{
"urls": "http://localhost:21022/;https://localhost:21023/"
}
9、然后,再Program.cs代码里修改如下:红色代码的就是新增配置项
public static IWebHost BuildWebHost(string[] args)
{
var configuration = new ConfigurationBuilder().SetBasePath(Environment.CurrentDirectory)
.AddJsonFile("host.json")
.Build();
string cert = @"c:\cert\ssl.pfx";
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseUrls(configuration["urls"])
.UseKestrel(options => {
options.Limits.MaxRequestBodySize = int.MaxValue;
options.ConfigureHttpsDefaults(i =>
{
i.ServerCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(cert, "123456");
});
})
.Build();
}
10、好了大部分已经完成,大家已经注意到了,.NET Core 使用了默认的Kestrel服务器,在Kestrel服务器上配置https就是这么简单。重新启动.NET Core服务。输入https://你的IP: 端口号;
11、SSL证书有了,SSL服务接口有了,就差域名了,我们在域名解析中泛解析一个* A记录 指向你的IP。
12、最后你可以用https://域名/访问你的服务了,测试一下成功!
好了,回到微信小程序,你现在可以大胆的请求服务了
wx.request({
url: 'https://域名:端口号/api/...',
method: 'POST',
data: datas,
success: function (res) {
console.log(res.data)
},