由于微信需要外网访问部署,为了方便大家测试本篇文章主要用jsp,servlet模拟演示了三个基本角色
模拟用户点击公众号点击的菜单的效果
[java] view plain copy
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
用户手机
模拟微信的服务器
[java] view plain copy
import java.io.IOException;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
*
* 模拟微信服务器
* @author: 开唯
* @date: 2018年1月8日 下午5:00:19
* @location 哈尔滨爱尚实训
*/
@Controller
@RequestMapping("/WechatController")
public class WechatController {
//用户点击后 ------- 模拟用,模拟微信服务器生成CODE
@RequestMapping("getCode")
public String getCode(String redURL){
UUID code = UUID.randomUUID();
return "redirect:"+redURL+"?code="+code.toString(); //重定向到第三方网址
}
/**
* 模拟通过code获取openid
*/
class="space" style="white-space:pre;display:inline-block;text-indent:2em;line-height:inherit;">
@RequestMapping("getOpenid")
@ResponseBody
public void getOpenid(String code,HttpServletResponse response) throws IOException{
//根据code查找用户openid 假设查出用户openid为999
response.getWriter().write("999");
}
}
第三方(客户端程序)
[java] view plain copy
import java.io.IOException;
import org.json.JSONException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.myhome.utill.URLParam;
import com.myhome.utill.userDate.UserLocationData;
/**
*
*
* 通过微信回调函数访问计算器
* @author: 开唯
* @date: 2017年12月12日 下午5:10:34
* @location 哈尔滨爱尚实训
*/
@Controller
@RequestMapping("/user")
public class CalculatorController {
/**
*
*
* 访问程序
* @param:微信传输过来的code
* @return:String
*
* @author: 苟开唯
* @throws JSONException IOException
* @date: 2017年12月13日 上午9:02:27
*
*/
@RequestMapping("Calculator")
public String calculator(String code) throws JSONException, IOException{
System.out.println("访问程序");
String openid = null;
//模拟访问微信服务器 code --> openid
String url = "http://localhost:8080/myhome/WechatController/getOpenid.do?code="+code;
StringBuffer readStringFromUrl = URLParam.readStringFromUrl(url);
openid = readStringFromUrl.toString();
String[] location = UserLocationData.getLocation(openid);
//在这里根据openid关联用户群体,进行业务处理
return "XXXXX" ; //view
}}
个人总结:开发者所做的,就是在按钮上部署程序地址,在进入controller时获取到Code,去再次访问微信服务器,获取openid。使用openid与我们程序进行关联操作。
下一篇预告:微信的消息接收
网友评论