微信企业号开发之获取AccessToken

在做企业号开发的时候,很有可能会调用微信提供的js接口(JS-SDK),

但是调用微信js接口需要使用临时票据jsapi_ticket,而jsapi_ticket又是通过AccessToken来获取,

那么AccessToken怎么得到呢?微信官方提供了以下方法(以下内容摘自微信官方):

获取AccessToken

AccessToken是企业号的全局唯一票据,调用接口时需携带AccessToken。

AccessToken需要用CorpIDSecret来换取,不同的Secret会返回不同的AccessToken。正常情况下AccessToken有效期为7200秒,有效期内重复获取返回相同结果;有效期内有接口交互(包括获取AccessToken的接口),会自动续期

  • 请求说明

Https请求方式: GET

https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=id&corpsecret=secrect

  • 参数说明
参数必须说明
corpid企业Id
corpsecret管理组的凭证密钥
  • 权限说明

每个secret代表了对应用、通讯录、接口的不同权限;不同的管理组拥有不同的secret。

  • 返回说明

a)正确的Json返回结果:

{
   "access_token": "accesstoken000001",
}
参数说明
access_token获取到的凭证

b)错误的Json返回示例:

{
   "errcode": 43003,
   "errmsg": "require https"
}

注:以上内容摘自微信官方文档

需要说明一下corpsecret是通过企业号管理组获取的,每个管理组对应一个corpsecret,在企业号管理平台选择左侧的“设置”,然后选择右侧的“权限管理”,在里面新建管理组,如下图:

也就是在页面中通过get请求访问https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=id&corpsecret=secrect,但是我在微信浏览器中测试了一下根本访问不了,最后发现是微信浏览器阻止了跨域访问,既然前台不能跨域那就只能放到后台访问,为此可以写一个springMvc的Controller,代码如下:

package com.weixin.qiye;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/qiye")
public class QiyeController {

	private static final String CORPID="wxf75e84161aaaaaaa";
	private static final String CORPSECRET="BkN0-Orh2d1GI9quC9GnG3KsmApLumgStJfmH29TzsekCWv4eO_8aR8KTZOVdOBh";
	
	@RequestMapping("/getAccessToken")
	public void getAccessToken(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String urlStr = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+CORPID+"&corpsecret="+CORPSECRET;  
        <span style="white-space:pre">	</span>processUrl(response, urlStr);  
	}
	
	
	private void processUrl(HttpServletResponse response, String urlStr) {
		URL url;
		try {
			url = new URL(urlStr);
			URLConnection URLconnection = url.openConnection();  
			HttpURLConnection httpConnection = (HttpURLConnection)URLconnection;  
			int responseCode = httpConnection.getResponseCode();  
			if (responseCode == HttpURLConnection.HTTP_OK) {  
				InputStream urlStream = httpConnection.getInputStream();  
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlStream));  
				String sCurrentLine = "";  
				String sTotalString = "";  
				while ((sCurrentLine = bufferedReader.readLine()) != null) {  
					sTotalString += sCurrentLine;  
				}  
				PrintWriter out = response.getWriter();
				out.print(sTotalString);
			}else{
				System.err.println("失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


这样在前台调用相同域名的后台代码,在后台跨域访问后,把获取的AccessToken再返回给前台就可以了。以下是前台代码:

$.ajax({
		dataType:"json",
		url: "http://leonjoweixin.duapp.com/weixingongzhong/qiye/getAccessToken",
		success: function(data){
			//得到data.access_token
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
		}
	});

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,以下是 Java 微信企业上传文件的示例代码: ```java import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class WechatMediaUpload { /** * 上传文件到微信服务器 * * @param accessToken 微信企业access_token * @param fileType 文件类型,可选值为image、voice、video、file * @param file 要上传的文件 * @throws Exception */ public static String uploadFile(String accessToken, String fileType, File file) throws Exception { String url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?type=" + fileType + "&access_token=" + accessToken; URL urlObj = new URL(url); HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection(); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); String boundary = "-----------------------------" + System.currentTimeMillis(); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream out = new DataOutputStream(conn.getOutputStream()); // 文件部分 StringBuilder sb = new StringBuilder(); sb.append("--").append(boundary).append("\r\n"); sb.append("Content-Disposition: form-data; name=\"media\"; filename=\"" + file.getName() + "\"\r\n"); sb.append("Content-Type: application/octet-stream\r\n\r\n"); out.write(sb.toString().getBytes()); DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } in.close(); out.write(("\r\n--" + boundary + "--\r\n").getBytes()); out.flush(); out.close(); // 读取返回数据 StringBuffer buffer = new StringBuffer(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String line = null; while ((line = reader.readLine()) != null) { buffer.append(line); } } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) { reader.close(); } } conn.disconnect(); return buffer.toString(); } public static void main(String[] args) { try { String accessToken = "your_access_token"; String fileType = "image"; // 上传文件类型,可选值为image、voice、video、file File file = new File("your_file_path"); String result = uploadFile(accessToken, fileType, file); System.out.println(result); } catch (Exception e) { e.printStackTrace(); } } } ``` 注意替换代码中的 access_token 和文件路径,以及设置正确的文件类型。文件类型为企业 API 中定义的四种类型之一:image、voice、video 和 file。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

西山水壶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值