WeChat sharing interface call

To do operational activities in the WeChat service account, you need to share the page to the circle of friends, or forward it to users. This function is very common. There are several problems that need to be paid attention to when writing. It is recorded here so that new students can have a reference.

First of all, if you have not been exposed to this interface before, you should still look at the official documentation to have a basic impression. The link is as follows: https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115&token=&lang= zh_CN

Next, you can try it yourself, if there is still some problem, for example, wx.config keeps showing invalid signature, you can refer to my writing method.

The basic method is that js calls WeChat's wx.config(). and when the config parameter is correct, it calls the related onMenuShareTimeline, onMenuShareAppMessage that is to share with friends and share with friends. For invalid signature problem, you can first enter each parameter on the WeChat JS API signature verification tool http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign to see if it is correct. If it is correct and an error is reported, it means that your url is mostly wrong. My approach is to pass the current request to the backend on the page, parse out the current full path url, and then generate the signature, which is simple and rude. Effective

My front-end page is written with velocity and is called through springmvc. The page call and js are written as follows

#set($weiMap=$!dataTag.getWeiMap($request,$!code))
	<input type="hidden" id="shareUrl" name="shareUrl" value='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb7bd46a3ecfe69bb&redirect_uri=$!appTag.getAppUrl()/operate/operationShare.htm?id=$!userId&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect'/>
	<input type="hidden" id="appId" name="appId" value='$weiMap.get("appId")'/>
	<input type="hidden" id="timestamp" name="timestamp" value='$weiMap.get("timestamp")'/>
	<input type="hidden" id="nonceStr" name="nonceStr" value='$weiMap.get("nonceStr")'/>
	<input type="hidden" id="signature" name="signature" value='$weiMap.get("signature")'/>
	<input type="hidden" id="position" name="position" value='$!position'/>
	<input type="hidden" id="url" name="url" value='$weiMap.get("url")'/>
	<script src="$!appTag.getWebUrl()/js/sea.js" data-main="$!appTag.getWebUrl()/js/page/share_friend" data-config="$!appTag.getWebUrl()/js/config" type="text/javascript"></script>
</body>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script>
  wx.config({
	    appId: $("#appId").val(),
	    timestamp: $("#timestamp").val(),
	    nonceStr: $("#nonceStr").val(),
	    signature: $("#signature").val(),
       jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage']
	});
wx.ready(function(){
    wx.onMenuShareAppMessage({
      title: '"Sidda Cup" tooth brushing pk game, free Disney tickets! Come and give me some sponsorship, I'm going to Disney! ',
      desc: 'My current ranking'+$("#position").val()+', come and like and vote for me dear! I'm going to Disney',
      link: $("#shareUrl").val(),
      imgUrl: 'http://mengya-web.oss-cn-hangzhou.aliyuncs.com/20160815142840.jpg',
    });
      
   wx.onMenuShareTimeline({
      title: '"Sidda Cup" tooth brushing pk game, free Disney tickets! Come and give me some sponsorship, I'm going to Disney! ',
      link: $("#shareUrl").val(),
      imgUrl: 'http://mengya-web.oss-cn-hangzhou.aliyuncs.com/20160815142840.jpg',
    });
    
  });
	</script>

I used set to inject the back-end method on the page to call $weiMap=$!dataTag.getWeiMap($request,$!code), which is mainly used to generate an object like weiMap to configure the corresponding WeChat verification parameters for wx.config
in java The parameters for generating weiMap are written like this

public Map<String, String> getWeiMap(HttpServletRequest request,String code) {
		String jsapi_ticket = weixinService.getJsapiTicket();
		Map<String, String> ret = new HashMap<String, String>();
		String nonce_str = create_nonce_str();
		String timestamp = create_timestamp();
		String string1;
		String signature = "";
		String url = getUrl(request);
		// Note that the parameter names here must be all lowercase and must be in order
		string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str
				+ "×tamp=" + timestamp + "&url=" + url;
		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(string1.getBytes("UTF-8"));
			signature = byteToHex(crypt.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace ();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace ();
		}
		ret.put("appId", weixinService.getAppId());
		ret.put("nonceStr", nonce_str);
		ret.put("timestamp", timestamp);
		ret.put("signature", signature);
		ret.put("url", url);
		ret.put("jsapi_ticket", jsapi_ticket);

		return ret;
	}
public String getUrl(HttpServletRequest request){
		StringBuffer url=request.getRequestURL();
		if(StringUtils.isNotBlank(request.getQueryString())){
			url.append("?"+request.getQueryString());
		}
		return url.toString();
	}

The method getJsapiTicket mainly calls the WeChat interface through https. I use redis cache to record the code. The code is as follows. I will not post the request implementation of https and the key corresponding to reids. Everyone should have their own methods. to realise
public String getJsapiTicket() {
		String vresult = redisService.getRedis(null,
				Constant.RedisKeyEnum.WEIJSTICKET);
		if (StringUtils.isNotBlank(vresult)) {
			return vresult;
		}
		String url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+getToken()+"&type=jsapi";
		String params = null;
		try {
			String result = Https.doPost(url, params, "UTF-8", 604800, 604800);
			JSONObject jo = JSONObject.parseObject(result);
			String ticket=jo.get("ticket").toString();
			redisService.insertRedis (null, Constant.RedisKeyEnum.WEIJSTICKET, ticket,
					60);
			return ticket;
		} catch (Exception e) {
			weixinServiceLogger.error("Error getting WeChat jsticket", e);
			e.printStackTrace ();
			return null;
		}
	}

Note that the jsticket method has a limited number of calls to WeChat, so you'd better cache it. The public Map<String, String> getWeiMap(HttpServletRequest request, String code) method of the
backend mainly uses the toolbox of veloctiy to connect the front and back ends. Called, and the call to the request should also be released in the ViewResolver in the springmvc configuration veloctiy, the configuration is as follows
<!-- Display of configuration view -->
    <bean id="ViewResolver" class="com.healthy.business.velocity.resolver.FixedVelocityLayoutViewResolver">
		<property name="order" value="10" />
		<property name="suffix" value=".vm" />
		<property name="prefix" value="screen" />
		<property name="layoutUrl"  value="layout/default.vm"/>
		<property name="exposeSpringMacroHelpers" value="true" />
		<property name="dateToolAttribute" value="dateTool" />
		<property name="numberToolAttribute" value="numberTool" />
		<property name="toolboxConfigLocation" value="WEB-INF/conf/vm-toolbox.xml" />
		<property name="contentType" value="${web.contentType}"></property>
		<property name="templateEncoding" value="UTF-8"></property>
		<property name="exposeRequestAttributes" value="true"></property>
		<property name="exposeSessionAttributes" value="true" />
		<property name="allowSessionOverride" value="true" />
    </bean>

Note the configuration of dateToolAttribute, toolboxConfigLocation, exposeRequestAttributes

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326628799&siteId=291194637