View Javadoc
1   package com.foxinmy.weixin4j.mp.api;
2   
3   import java.io.IOException;
4   
5   import com.alibaba.fastjson.JSON;
6   import com.alibaba.fastjson.TypeReference;
7   import com.foxinmy.weixin4j.exception.WeixinException;
8   import com.foxinmy.weixin4j.http.weixin.WeixinResponse;
9   import com.foxinmy.weixin4j.model.Token;
10  import com.foxinmy.weixin4j.model.qr.QRParameter;
11  import com.foxinmy.weixin4j.model.qr.QRResult;
12  import com.foxinmy.weixin4j.token.TokenManager;
13  import com.foxinmy.weixin4j.util.IOUtil;
14  
15  /**
16   * 二维码相关API
17   * 
18   * @className QrApi
19   * @author jinyu(foxinmy@gmail.com)
20   * @date 2014年9月25日
21   * @since JDK 1.6
22   */
23  public class QrApi extends MpApi {
24  
25  	private final TokenManager tokenManager;
26  
27  	public QrApi(TokenManager tokenManager) {
28  		this.tokenManager = tokenManager;
29  	}
30  
31  	/**
32  	 * 生成带参数的二维码
33  	 * 
34  	 * @param parameter
35  	 *            二维码参数
36  	 * @return 二维码结果对象
37  	 * @throws WeixinException
38  	 * @see com.foxinmy.weixin4j.model.qr.QRResult
39  	 * @see com.foxinmy.weixin4j.model.qr.QRParameter
40  	 * @see <a
41  	 *      href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1443433542&token=&lang=zh_CN">生成二维码</a>
42  	 */
43  	public QRResult createQR(QRParameter parameter) throws WeixinException {
44  		Token token = tokenManager.getCache();
45  		String qr_uri = getRequestUri("qr_ticket_uri");
46  		WeixinResponse response = weixinExecutor.post(
47  				String.format(qr_uri, token.getAccessToken()),
48  				JSON.toJSONString(parameter));
49  		QRResult result = response.getAsObject(new TypeReference<QRResult>() {
50  		});
51  		qr_uri = String.format(getRequestUri("qr_image_uri"),
52  				result.getTicket());
53  		response = weixinExecutor.get(qr_uri);
54  		result.setShowUrl(qr_uri);
55  		try {
56  			result.setContent(IOUtil.toByteArray(response.getBody()));
57  		} catch (IOException e) {
58  			throw new WeixinException(e);
59  		}
60  		return result;
61  	}
62  }