WeChat official account uses JS-SDK to achieve photo uploading function
Wechat browser cannot use the function of calling camera (pit ~ / ㄒo ㄒ) / ~ ~). This paper uses wechat public platform jsjdk to realize the function of taking photos and uploading pictures.
As we all know, the biggest criticism of calling wechat platform interface is trouble and many processes, such as token, code, ticket, signature and so on. This time, we will sort out the photo upload function of JS SDK. The best way is to read official documents.
JS SDK document address: https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html
technological process:
- Login WeChat public platform into the "official account settings" function settings to fill in the "JS interface security domain name".
- Import JS file http://res.wx.qq.com/open/js/jweixin-1.6.0.js
- Get access_token access_ Get document with token
- Take access_token get jsapi_ticket
- Take the jsapi_ticket, a random string noncestr, a timestamp, and the current url to generate a signature
- Take the signature to inject permission verification configuration into the config interface.
- After successful verification through the ready interface processing, we can start calling the wechat JS SDK interface.
Get access_token
GET request
Parameters: your wechat platform background appid and secret, grant_type fill in client by default_ Credential
GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
Get jsapi_ticket
GET request
Parameter: use the access obtained in the previous step_ token
https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
Generate signature
signature algorithm
The signature generation rules are as follows: the fields participating in the signature include noncestr (random string) and valid jsapi_ticket, timestamp, URL (the URL of the current web page, excluding # and its subsequent parts). After sorting all parameters to be signed according to the ASCII code of the field name from small to large (dictionary order), use the format of URL key value pairs (i.e. key1 = value1 & key2 = Value2...) to splice them into string string1. Note that all parameter names are lowercase characters. sha1 encryption is performed for string1. The field name and field value adopt the original value without URL escape.
That is, signature=sha1(string1).
Example:
String str ="jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW×tamp=1414587457&url=http://mp.weixin.qq.com?params=value"; String signature = sha1(str); // 0f9de62fce790f9a083d5c99e95740ceb90c27ed
Generated sha1 algorithm code in Java version:
/** * sha1 encryption * * @param data * @return * @throws NoSuchAlgorithmException */ public String sha1(String data) throws NoSuchAlgorithmException { //Information digester algorithm name MessageDigest md = MessageDigest.getInstance("SHA1"); //Convert string to byte array byte[] b = data.getBytes(); //Update our summary with the specified bytes md.update(b); //Get ciphertext (complete summary calculation) byte[] b2 = md.digest(); //Gets the calculated length int len = b2.length; //Hexadecimal string String str = "0123456789abcdef"; //Convert string to string array char[] ch = str.toCharArray(); //Create a 40 bit byte array char[] chs = new char[len * 2]; //Cycle 20 times for (int i = 0, k = 0; i < len; i++) { byte b3 = b2[i];//Gets each byte in the byte array after summary calculation // >>>: move right without symbol // &: bitwise AND //0xf: number from 0 to 15 chs[k++] = ch[b3 >>> 4 & 0xf]; chs[k++] = ch[b3 & 0xf]; } //Convert character array to string return new String(chs); }
config interface injection permission verification configuration
wx.config({ debug: true, // When the debugging mode is enabled, the return values of all APIs called will be alert ed on the client. To view the incoming parameters, you can open them on the pc side. The parameter information will be printed through the log and will only be printed on the pc side. appId: '', // Required, the only sign of official account. timestamp: , // Required, time stamp to generate signature nonceStr: '', // Required, generate random string of signature signature: '',// Required, signature jsApiList: ['chooseImage'] // Required. The list of JS interfaces to be used chooseImage is a photographing interface });
The ready interface handles the verification successfully
wx.ready(function(){ // Config information validation will execute the ready method. All interface calls must be obtained after the config interface gets the result. Config is an asynchronous operation of the client. Therefore, if the relevant interface is required when the page is loaded, the relevant interface must be put in the ready function to ensure the correct execution. For the interface called only when triggered by the user, it can be called directly without putting it in the ready function. alert("wx ready."); });
Pop up wx ready Indicates that the configuration was successful.
Call the camera interface
To call an interface, you need to add your own interface during config configuration, such as the photo interface {chooseImage
wx.chooseImage({ count: 1, // Default 9 sizeType: ['original', 'compressed'], // You can specify whether to use the original or compressed image. Both are available by default sourceType: ['album', 'camera'], // You can specify whether the source is an album or a camera. Both are available by default success: function (res) { var localIds = res.localIds; // Returns the list of local ID s of the selected photos, which can be displayed as src attribute of img tag } });
Interface for taking photos, uploading, downloading and obtaining local pictures
The upload here only returns the image server-side ID. continue to call the download and obtain the local image interface to get the base64 data of the image. The complete code is as follows:
// Call wechat file or camera and upload pictures function wxCamera() { wx.chooseImage({ count: 1, // Default 9 sizeType: ['original', 'compressed'], // You can specify whether to use the original or compressed image. Both are available by default sourceType: ['album', 'camera'], // You can specify whether the source is an album or a camera. Both are available by default success: function (res) { var localIds = res.localIds; // Returns the list of local ID s of the selected photos, which can be displayed as src attribute of img tag // Upload picture interface wx.uploadImage({ localId: localIds[0], // The local ID of the image to be uploaded is obtained by the chooseImage interface isShowProgressTips: 1, // The default is 1, and the progress prompt is displayed success: function (res) { var serverId = res.serverId; // Returns the server-side ID of the picture // Download picture interface wx.downloadImage({ serverId: serverId, // The server-side ID of the image to be downloaded is obtained by the uploadImage interface isShowProgressTips: 1, // The default is 1, and the progress prompt is displayed success: function (res) { var localId = res.localId; // Returns the local ID of the downloaded image // Get local picture interface wx.getLocalImgData({ localId: localId, // localID of the picture success: function (res) { var localData = res.localData; // localData is the base64 data of the picture, which can be displayed with the img tag dealImage(localData ); //Processing pictures } }); } }); } }); } }); }
Here, a photo upload function of WeChat official account has been completed.