小程序通信笔记
前记:
- 小程序开发文档:https://developers.weixin.qq.com/miniprogram/dev/framework/
- 社区问答:https://developers.weixin.qq.com/community/develop/question/
- 最近要做小程序相关的,紧急补充了一波知识点
- java调用云函数是为了适应 管理端 用web端来做。数据库在云。云函数此时的作用相当于sql。
- springboot与小程序的联用,是数据库在mysql端
1、http工具类的使用
<!-- httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
</dependency>
package com.hl.utils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpClientUtil {
public static String doGet(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
// 执行请求
response = httpclient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doGet(String url) {
return doGet(url, null);
}
public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
public static String doPost(String url) {
return doPost(url, null);
}
public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
}
public class TestMain {
public static void main(String[] args) {
// 发送请求
String s = HttpClientUtil.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET");
//需要什么样的方式及请求参数直接看HttpClientUtil封装的方法即可。
}
}
2、Fastjson的使用
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
public class TestMain {
public static void main(String[] args) {
String s = "{\"errcode\":40013,\"errmsg\":\"invalid appid rid: 6066d1dc-02c8f1bf-32e35d86\"}";
//假设s是从向一个接口请求得到的json格式的数据
if (JSON.isValid(s)) { //首先应该判断是否为一个合法的json对象
JSONObject jsonObject = JSON.parseObject(s);
String errcode = jsonObject.getString("errcode");
System.out.println(errcode);
}
//下面是把数据封装为一个json对象
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("key1", "value1");
jsonObject1.put("key2", "value2");
String s1 = jsonObject1.toString();//toString即可把转化为一个标准的json对象
System.out.println(s1);
System.out.println(JSON.isValid(s1));
}
}
3、调用云函数
https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-http-api/functions/invokeCloudFunction.html
//小程序相关的常量
public interface AppConstant {
String AppID = "xxxx";
String AppSecret = "xxxx";
String DatabaseID = "xxxx";//所用的数据库唯一标识
}
public class TestMain {
public static void main(String[] args) {
//首先向微信服务器拿到接口调用凭证
String s = HttpClientUtil.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+ AppConstant.AppID + "&secret="
+ AppConstant.AppSecret);
JSONObject jsonObject = JSON.parseObject(s);
String access_token = jsonObject.getString("access_token");//拿到登录凭证
//拿到凭证后,向数据库请求
String s1 = HttpClientUtil.doPost("https://api.weixin.qq.com/tcb/invokecloudfunction?access_token="
+ access_token //凭证
+ "&env="
+ AppConstant.DatabaseID //数据库环境
+ "&name="
+ "getAllUsers"); //数据库的名称
System.out.println(s1);
}
}
4、token
详细理解地址:https://blog.csdn.net/qq_47234534/article/details/115530513
网上对token的理解:
下面是和师兄的对话:
5、小程序用springboot登录
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html
小程序:
testLogin: function() {
wx.login({
success (res) {
if (res.code) {
//发起网络请求
wx.request({
url: 'http://localhost:8080/testLogin',
data: {
code: res.code
},
success(res) {
console.log("=====================");
console.log(res);
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
}
SpringBoot
//相关常量
public interface AppConstant {
String AppID = "xxx";
String AppSecret = "xxx";
String DatabaseID = "xxx";//所用的数据库唯一标识
}
//结果对象
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ResultBean {
private String code;
private String message;
private Object data;
}
//控制器
@RestController
public class CommonController {
@RequestMapping("/testLogin")
public ResultBean login(@RequestParam("code") String code) {
System.out.println(code);
String s = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session?appid="
+ AppConstant.AppID
+ "&secret="
+ AppConstant.AppSecret
+ "&js_code="
+ code
+ "&grant_type=authorization_code");
System.out.println(s);
JSONObject jsonObject = new JSONObject();
jsonObject.put("token", "zhongwenhao");
ResultBean resultBean = new ResultBean();
resultBean.setCode("200");
resultBean.setMessage("登录成功啦");
resultBean.setData(jsonObject.toString());
return resultBean;
}
}
//
小程序端返回的结果
{data: {…}, header: {…}, statusCode: 200, cookies: Array(0), errMsg: "request:ok"}
cookies: []
data: //data字段就是上面的resultBean中的字段数据
code: "200"
data: "{"token":"zhongwenhao"}"
message: "登录成功啦"
__proto__: Object
errMsg: "request:ok"
header: {Content-Type: "application/json", Transfer-Encoding: "chunked", Date: "Fri, 02 Apr 2021 11:23:20 GMT", Keep-Alive: "timeout=60", Connection: "keep-alive"}
statusCode: 200
__proto__: Object