wps online editing and sorting (here we sort out the error prone areas after docking)

1, Development preparation

1. Application service provider

Application service provider process

2. Access mode

There are three access methods: File preview, file editing and file creation.

Take file preview as an example. File preview is applicable to the scene where the file already exists on the public network server.

For example, access Word Preview: https://wwo.wps.cn/office/w/471eba5030?_w_fname= Minutes of meeting docx&_ w_ userid=33&_ w_ appid=d8f99da

After that, as long as the server of the docking party implements relevant interfaces, the access of online preview can be started:
Function description of callback address method
/v1/3rd/file/info GET gets the file metadata. When previewing or editing, verify the permissions and obtain the file information through the interface
/v1/3rd/onnotify POST notifies the interface that returns the notification when a file is opened
For more detailed file preview, file editing and file creation, please refer to: Access mode

3. Server access

The server can view: Server

4. Front end access

Front end fast access can view: front end

2, Logical description

wps open platform online editing only provides simple web page editing, and does not store files. All files and data need to be stored by the docking party through the callback method, and the addresses of all returned files need to be accessible through the Internet. All parameters must be_ w_ Start with.

1. Description of docking party database table

All file information needs to be generated by the docking server, including file id.

a. File storage table

CREATE TABLE zc_wps_files (
id bigint(20) NOT NULL COMMENT 'primary key',
name varchar(100) DEFAULT NULL COMMENT 'file name (must have file suffix) (required)',
version int(11) DEFAULT NULL COMMENT 'the current version number must be greater than 0 and the number of digits must be less than 11 (required)',
size bigint(20) DEFAULT NULL COMMENT 'file size, unit: B (the real size of the file, otherwise an exception will occur) (required)',
download_url varchar(255) DEFAULT NULL COMMENT 'document download address (required)',
preview_pages int(11) DEFAULT NULL COMMENT 'limit the number of preview pages (not required)',
created datetime DEFAULT NULL COMMENT 'creation time',
creator bigint(20) DEFAULT NULL COMMENT 'creator',
updated datetime DEFAULT NULL COMMENT 'modified time',
updater bigint(20) DEFAULT NULL COMMENT 'modified by',
PRIMARY KEY (id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT = 'wps file storage';

b. Document history record

CREATE TABLE zc_wps_files_history (
Comment (bigin) 20,
file_id bigint(20) DEFAULT NULL COMMENT 'file id (corresponding to the id of table a'),
name varchar(100) DEFAULT NULL COMMENT 'file name (must have file suffix) (required)',
version int(11) DEFAULT NULL COMMENT 'the current version number must be greater than 0 and the number of digits must be less than 11 (required)',
size bigint(20) DEFAULT NULL COMMENT 'file size, unit: B (the real size of the file, otherwise an exception will occur) (required)',
download_url varchar(255) DEFAULT NULL COMMENT 'document download address (required)',
preview_pages int(11) DEFAULT NULL COMMENT 'limit the number of preview pages (not required)',
created datetime DEFAULT NULL COMMENT 'creation time',
creator bigint(20) DEFAULT NULL COMMENT 'creator',
updated datetime DEFAULT NULL COMMENT 'modified time',
updater bigint(20) DEFAULT NULL COMMENT 'modified by',
PRIMARY KEY (id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT = 'wps file history version';

2. Front end initialization wps online editing instructions

window.onload = function() {
  const jssdk = WebOfficeSDK.config({
    url: 'Online document preview address', // This address needs to be provided by the back end, https://wwo.wps.cn/office/p/xxx
  });

  // If you need to perform special processing on iframe, you can get the dom object of iframe in the following ways
  console.log(jssdk.iframe);

  // Open document results
  jssdk.on('fileOpen', (data) => {
    console.log(data.success);
  });
};

The online document preview address is returned to the front end through the docking server through operations such as signature.
url specification: https://wwo.wps.cn/office/ <:type>/<:fileid>?_ w_ appid=xxx&_ w_ Signature = XXX &... (custom parameters required for docking module)
url example: https://wwo.wps.cn/office/w/471eba5030?_w_fname= Minutes of meeting docx&_ w_ userid=33&_ w_ appid=d8f99da

3. Signature description

Return path https://wwo.wps.cn/office/ <:type>/<:fileid>?_ w_ appid=xxx&_ w_ Signature = XXX &... (custom parameters required by the docking module). The signature (getSignature) needs to sign all the returned parameters, otherwise it will fail.

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.\*;

import static org.apache.tomcat.util.codec.binary.Base64.encodeBase64String;

public class Signature {

	public static void main(String args[]) throws UnsupportedEncodingException {
		Map < String, String > paramMap= new HashMap<>();
		paramMap.put("_w_appid", "123456");
		paramMap.put("_w_fname", "222.docx");
		paramMap.put("_w_userid", "id1000");
		String signature = getSignature(paramMap, "7890");
		System.out.println(getUrlParam(paramMap) + "&_w_signature=" + signature);
	}

  private static String getUrlParam(Map < String, String > params) throws UnsupportedEncodingException {
		StringBuilder builder = new StringBuilder();
		for (Map.Entry < String, String > entry : params.entrySet()) {
			if (builder.length() > 0) {
				builder.append('&');
			}
			builder.append(URLEncoder.encode(entry.getKey(), "utf-8")).append('=').append(URLEncoder.encode(entry.getValue(), "utf-8"));
		}
		return builder.toString();
	}

  private static String getSignature(Map < String, String > params, String appSecret) {
		List < String > keys=new ArrayList();
		for (Map.Entry < String, String > entry : params.entrySet()) {
			keys.add(entry.getKey());
		}

		// Sort all parameters in ascending order of key
		Collections.sort(keys, new Comparator<String>() {
			public int compare(String o1, String o2) {
				return o1.compareTo(o2);
			}
		});

		// Construct the source string of the signature
		StringBuilder contents = new StringBuilder("");
		for (String key : keys) {
			if (key == "_w_signature") {
				continue;
			}
			contents.append(key + "=").append(params.get(key));
			System.out.println("key:" + key + ",value:" + params.get(key));
		}
		contents.append("_w_secretkey=").append(appSecret);

		// Sign hmac sha1
		byte[] bytes = hmacSha1(appSecret.getBytes(), contents.toString().getBytes());
		// The string is Base64 encoded
		String sign = encodeBase64String(bytes);
		try {
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		System.out.println(sign);
		return sign;
	}

  public static byte[] hmacSha1(byte[] key, byte[] data) {
		try {
			SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1");
			Mac mac = Mac.getInstance(signingKey.getAlgorithm());
			mac.init(signingKey);
			return mac.doFinal(data);
		}
		catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		}
		return null;
	}

}

4. Java service callback description

Description reference Official website

a. token description

The token is generated by the docking Party's own user login, and the front-end docking is required

  • Mode 1:
    You can access the front end through jssdk, and set the token through the setToken interface of jssdk. See the access documents related to jssdk for details.

Bring the url parameter_ w_tokentype=1 (signature is also required for this parameter)

jssdk = WebOfficeSDK.config({
  url: 'your signature url' // Bring the url parameter_ w_ Token type = 1, pass in the token through jssdk
});

// This API is used to set the token for the first time and refresh the token later
jssdk.setToken({token: 'your token'});
  • Mode 2:
    Inject WPS through WebView_ Gettoken global function to pass in a token. If the WebOffice front end detects a window WPS_ The gettoken function will be called directly to get the token. Note that you need to return an Object object Object {token: "your token"}
// Injection WPS_GetToken
function WPS_GetToken(){
  return {
    token: "your token"
  };
};
b. Callback interface description

Generally, the callback interface is written according to the instructions on the official website.
Upload a new version file: / v1/3rd/file/save. Pay attention to the parameter transfer
The official website of file gives parameters in the form of body. In fact, the Java code is consistent with query

@ApiOperation("Upload new version of file")
    @PostMapping("file/save")
    public Map<String, Object> save(HttpServletRequest request, @RequestParam(name = "_w_tenderId") String tenderId, @RequestParam("file") MultipartFile file) {
        String fileId = request.getHeader("x-weboffice-file-id");
        String token = request.getHeader("x-wps-weboffice-token");
        token = "Bearer " + token;
        Integer version = Integer.parseInt(request.getHeader("x-weboffice-save-version"));

        WPSFileSaveDTO wpsFileSaveDTO = new WPSFileSaveDTO();
        wpsFileSaveDTO.setId(fileId);
        wpsFileSaveDTO.setTenderId(tenderId);
        wpsFileSaveDTO.setVersion(version);
        wpsFileSaveDTO.setFile(file);
        return wpsService.save(wpsFileSaveDTO, token);
    }

Keywords: Java Front-end wps

Added by harnacks on Sun, 20 Feb 2022 12:38:14 +0200