獲取微信 access_token,ticket,signature
阿新 • • 發佈:2018-12-21
程式碼記錄:
package com.yunxi.access.action; import com.alibaba.fastjson.JSONObject; import com.yunxi.access.constant.config.RedisCache; import com.yunxi.util.common.RandomCreateCode; import com.yunxi.util.http.HttpPostUtil; import com.yunxi.util.security.Sha1; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import java.net.URLDecoder; import static com.yunxi.util.common.RandomCreateCode.MODE_CHARACTER; /** * 微信js分享 * 獲取 access_token,ticket,signature * @Author QZJ * @CreateTime 2018/12/20 */ @RestController public class WxAction { @Value("${wx.appId}") String appId; @Value("${wx.appSecret}") String appSecret; @Autowired RedisCache redisCache; private static final String ACCESS_TOKEN = "ACCESS_TOKEN"; private static final String JS_TICKET = "JS_TICKET"; private static final int EXPIRE_TIME = 120 * 60; @ApiOperation(value = "獲取微信分享資訊", notes = "JSON") @PostMapping("/getWxInfo") public @ResponseBody JSONObject getWxInfo(@RequestParam(value = "shareLink") String shareLink) throws Exception { // 獲取token String accessToken = getValue("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret, "access_token", ACCESS_TOKEN); // 獲取 ticket 注意連結前端需要encode,因為包含連線符 String ticket = getValue("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi", "ticket", JS_TICKET); // 生成簽名 return getSignature(ticket, shareLink); } /** * 生成簽名信息 * @param ticket * @param shareLink * @return * @throws Exception */ private JSONObject getSignature(String ticket, String shareLink) throws Exception { JSONObject wxObject = new JSONObject(); Long timestamp = System.currentTimeMillis() / 1000; String nonceStr = RandomCreateCode.randomNumber(10, MODE_CHARACTER); String param = "jsapi_ticket=" + ticket + "&noncestr=" + nonceStr + "×tamp=" + timestamp + "&url=" + URLDecoder.decode(shareLink, "utf-8"); wxObject.put("timestamp", timestamp); wxObject.put("nonceStr", nonceStr); wxObject.put("signature", Sha1.encode(param)); return wxObject; } /** * 取微信值 並 儲存 redis * * @param url * @param key * @param redisKey * @return * @throws Exception */ private String getValue(String url, String key, String redisKey) throws Exception { // 從redis中取值 String value = redisCache.getValue(redisKey); if (!StringUtils.isEmpty(value)) { return value; } // 微信取值 String result = HttpPostUtil.sendPost(url, "", HttpPostUtil.FORM); value = JSONObject.parseObject(result).getString(key); // 儲存 redisCache.setValue(redisKey, value, EXPIRE_TIME); return value; } }