1. 程式人生 > 實用技巧 >使用FeignClient呼叫微信介面並返回openid簡例

使用FeignClient呼叫微信介面並返回openid簡例

在Java開發過程中可以使用各種http工具類呼叫微信介面,由於springCloud已經成為主流,其自帶FeignClient類已經很優雅地實現了各種http呼叫方式,因此在springCloud中可以優先使用這個類呼叫微信介面。

所需材料:

1.實體定義:

@Entity
public class WeixinJsonObject {
    @Id
    private String openid;
    private String session_key;
    private String unionid;
    private String errcode;
    private
String errmsg; public String getOpenid() { return openid; } public void setOpenid(String openid) { this.openid = openid; } public String getSession_key() { return session_key; } public void setSession_key(String session_key) { this.session_key = session_key; }
public String getUnionid() { return unionid; } public void setUnionid(String unionid) { this.unionid = unionid; } public String getErrcode() { return errcode; } public void setErrcode(String errcode) { this.errcode = errcode; } public
String getErrmsg() { return errmsg; } public void setErrmsg(String errmsg) { this.errmsg = errmsg; } }

2.FeignClient類程式碼:

@FeignClient(name = "${service.request.name}", configuration = FoodMobileServiceHystrix.class,url = "https://api.weixin.qq.com/")
public interface FoodMobileService {
    @RequestMapping(value = "/sns/jscode2session", method = RequestMethod.GET)
    String getWeixinLogin(@RequestParam(name = "appid", required = true) String appid,
                                    @RequestParam(name = "secret", required = true) String secret,
                                    @RequestParam(name = "js_code", required = true) String js_code,
                                    @RequestParam(name = "grant_type", required = true) String grant_type);
}
FoodMobileServiceHystrix類程式碼:
public class FoodMobileServiceHystrix  implements FoodMobileService {
    @Override
    public String getWeixinLogin(String appid, String secret, String js_code, String grant_type) {
        return null;
    }
}

3.介面呼叫程式碼:

@ApiOperation(value = "獲取微信ID", notes = "獲取微信ID")
    @RequestMapping(value = "/getWeixinLogin", method = RequestMethod.GET, produces = "application/json; charset=UTF-8")
    public ResponseResult<Object> getWeixinLogin(@Param("js_code") String js_code) {
        try {
            String appid = "***********";
            String secret = "*******************";
            String grant_type = "authorization_code";
            String result = foodMobileService.getWeixinLogin(appid, secret, js_code, grant_type);

            JSONObject jsonString = JSONObject.parseObject(result);
            WeixinJsonObject weixinJsonObject = (WeixinJsonObject) JSONObject.toJavaObject(jsonString, WeixinJsonObject.class);
            return RestResultGenerator.genResult(weixinJsonObject, ConstantCode.RETURN_MESSAGE_SUCCESS, true, "200");

        } catch (Exception ex) {
            logger.error("方法名:getWeixinLogin錯誤:" + ex.getMessage());
            ex.printStackTrace();
            return RestResultGenerator.genResult(null, ex.getMessage(), false, "500");
        }
    }

執行結果如下: