微信支付java版本之JSAPI支付+发送模板消息

本文为大家分享了java版本之JSAPI支付+发送模板消息的相关资料,供大家参考,具体内容如下

1.工具类

工具类见:微信支付JAVA版本之Native付款

2.公众账号设置

3.代码实现

openId:openId为用户与该公众账号之间代表用户的唯一标示 
以下类中涉及到生成token,关闭订单接口调用,获取配置文件信息,和工具类,在其他文章中有具体代码实现

package com.zhrd.bussinss.platform.controller.rest;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.zhrd.bussinss.platform.bo.JsPay;
import com.zhrd.bussinss.platform.bo.PayHist;
import com.zhrd.bussinss.platform.constants.PayHistoryPayStatus;
import com.zhrd.bussinss.platform.constants.PayHistoryPayType;
import com.zhrd.bussinss.platform.service.GetWeiXinAccessTokenService;
import com.zhrd.bussinss.platform.service.WeiXinPayService;
import com.zhrd.bussinss.platform.utils.CloseWeiXinOrderUtils;
import com.zhrd.bussinss.platform.utils.CustomizedPropertyPlaceholderConfigurer;
import com.zhrd.bussinss.platform.weixinPayUtils.ClientCustomSSL;

@RestController
@RequestMapping("/rest/weiXinSendMessage")
public class WeiXinSendMessageRESTFULController {

 @Autowired
 WeiXinPayService weiXinPayService;
 @Autowired
 GetWeiXinAccessTokenService getWeiXinAccessTokenService;

 private static long standardTime = 1662652800000L;

 /**
 * 微信发送消息
 * @param request
 * @param response
 * @return
 */
 @RequestMapping(value="/weiXinSend",method=RequestMethod.GET)
 @ResponseBody
 public Object weiXinSend(HttpServletRequest request,HttpServletResponse response,String orderNo,String openId){
 System.out.println("==========================微信发送消息开始========================"+getWeiXinAccessTokenService.accessToken());
 try{

 KeyStore keyStore = KeyStore.getInstance("PKCS12");
 FileInputStream instream = new FileInputStream(new File(
 CustomizedPropertyPlaceholderConfigurer.getContextProperty("wx.cert").toString()));
 try {
 keyStore.load(instream, "见邮件".toCharArray());
 }finally {
 instream.close();
 }

 // Trust own CA and all self-signed certs
 SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore,
 "10061401".toCharArray()).build();
 // Allow TLSv1 protocol only
 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
 sslcontext, new String[] { "TLSv1" }, null,
 SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
 CloseableHttpClient httpclient = HttpClients.custom()
 .setSSLSocketFactory(sslsf).build();
 // HttpGet httpget = new
 // HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");   //获取token详见获取token的文章
 HttpPost httppost = new HttpPost(
 "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+getWeiXinAccessTokenService.accessToken());

 PayHist ph = null;
 List<Map<String,Object>> td = weiXinPayService.getTrade(orderNo);
 Date dt = new Date();
 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
 String nonceStr = sdf.format(dt).toString();
 Date now = new Date();

 String tradePayNo = orderNo+String.format("%10d",standardTime - now.getTime()).substring(0, 10);
 System.out.println("订单标号orderNo======="+orderNo);
 System.out.println("10位随机数======="+String.format("%10d",standardTime - now.getTime()).substring(0, 10));
 String price = Math.round(Float.valueOf(td.get(0).get("price").toString())*100)+"";
 Long timeExpireStrOld = dt.getTime();   //获取配置文件信息 详见获取配置文件信息的文章
 Long timeNew = Long.parseLong(CustomizedPropertyPlaceholderConfigurer.getContextProperty("weixin.send2finish.overtime").toString());
 Long timeExpireNew = timeExpireStrOld+timeNew;
 Date dtTimeExpire = new Date(timeExpireNew);
 SimpleDateFormat dtSdf = new SimpleDateFormat("yyyyMMddHHmmss");
 String timeExpire = dtSdf.format(dtTimeExpire).toString();
 System.out.println("nonceStr=="+nonceStr);
 System.out.println("orderNo=="+orderNo);
 System.out.println("price=="+price);
 System.out.println("timeStart=="+nonceStr);
 System.out.println("timeExpire=="+timeExpire);

 JSONObject resultJsPay = (JSONObject) getJsPay(nonceStr, "订单", tradePayNo, price, nonceStr,timeExpire,openId);
 resultJsPay.getString("prepayId");

 System.out.println("================222prepay_id222========================="+resultJsPay.getString("prepayId").toString());

 List<Map<String,Map<String,String>>> data = new ArrayList<Map<String,Map<String,String>>>();
 Map<String,Map<String,String>> firstparam = new HashMap<String, Map<String,String>>();
 Map<String,String> valueParam = new HashMap<String, String>();
 valueParam.put("value", td.get(0).get("buyerName")+"(先生/女士)的订单");
 valueParam.put("color", "#173177");
 Map<String,String> valueParam1 = new HashMap<String, String>();
 valueParam1.put("value", orderNo);
 valueParam1.put("color", "#173177");
 Map<String,String> valueParam2 = new HashMap<String, String>();
 valueParam2.put("value", "智慧社区爱生鲜订单");
 valueParam2.put("color", "#173177");
 Map<String,String> valueParam3 = new HashMap<String, String>();
 valueParam3.put("value", td.get(0).get("price")+"元");
 valueParam3.put("color", "#173177");
 Map<String,String> valueParam4 = new HashMap<String, String>();
 valueParam4.put("value", "等待支付");
 valueParam4.put("color", "#173177");
 Map<String,String> valueParam5 = new HashMap<String, String>();
 valueParam5.put("value", "点击支付");
 valueParam5.put("color", "#173177");
 firstparam.put("first", valueParam);
 firstparam.put("keyword1", valueParam1);
 firstparam.put("keyword2", valueParam2);
 firstparam.put("keyword3", valueParam3);
 firstparam.put("keyword4", valueParam4);
 firstparam.put("remark", valueParam5);
 data.add(firstparam);

 JsPay jp = new JsPay();
 jp.setTouser(openId);
 jp.setTemplate_id("MieXd4-4uqRFMdjnvqMjH0egFYpm16r5DPDT6P9gPgg");
 jp.setTopcolor("#173177");
 jp.setUrl("http://公众账号设置的链接/weixin_jspay/weixinJsPay/init.action?packageValue="+resultJsPay.getString("prepayId").toString());
 jp.setData(data);
 JSONObject jsonObject = JSONObject.fromObject(jp);
 String str = new String(jsonObject.toString().getBytes("utf-8"), "iso8859-1"); 

// String xml = ClientCustomSSL.RefundNativePackage(weiXinRefundService.getTradePayNo(orderNo),nonceStr,totalFee,refundFee,nonceStr);
 try {
 System.out.println("data=========="+str.toString());
 StringEntity se = new StringEntity(str.toString().replace("[", "").replace("]", "").toString());

 httppost.setEntity(se);

 System.out.println("executing request" + httppost.getRequestLine());

 CloseableHttpResponse responseEntry = httpclient.execute(httppost);
 try {
 HttpEntity entity = responseEntry.getEntity();

  InputStream in = entity.getContent();
  byte b[] = new byte[1024];
  int len = 0;
  int temp=0;  //所有读取的内容都使用temp接收
  while((temp=in.read())!=-1){ //当没有读取完时,继续读取
  b[len]=(byte)temp;
  len++;
  }
  in.close();
  System.out.println(new String(b,0,len)); 

 if (entity != null) {
 System.out.println("Response content length: "
  + entity.getContentLength());
 System.out.println("==="+responseEntry.getEntity().toString());

 JSONObject result = JSONObject.fromObject(new String(b,0,len));
 if(result.getString("errmsg").equals("ok")){
 ph = new PayHist();
 ph.setTradePayUrl("");
 ph.setPayTradeNo(orderNo);
 ph.setTradePayNo(tradePayNo);
 ph.setPayStatus(PayHistoryPayStatus.WECHAT_PAY_STATUS_WAIT);
 ph.setPayType(PayHistoryPayType.WECHAT_JS_PAY);
 List<PayHist> payHistList = weiXinPayService.getPayHist(orderNo,"wechat","");
 if(payHistList == null || payHistList.size() == 0){
  weiXinPayService.addPayHist(ph);
 }else{         //关闭订单详见取消订单的文章
  JSONObject strStatus = (JSONObject) CloseWeiXinOrderUtils.closeWeiXinOrder(payHistList.get(0).getTradePayNo());
  if(strStatus.getString("status").equals("success")){
  System.out.println(ph.getTradePayNo());
  weiXinPayService.updatePayHist(ph);
  }
 }
 }

 return result;

 }
 EntityUtils.consume(entity);
 }
 finally {
 responseEntry.close();
 }
 }
 finally {
 httpclient.close();
 }
 return null;

 }catch(Exception e){
 e.printStackTrace();
 JSONObject result = new JSONObject();
 result.put("status","error");
 result.put("msg",e.getMessage());
 return result;
 }

 }

 public static Object getJsPay(String nonceStr,String orderDescribe,String orderNo,String price,String timeStart,String timeExpire,String openId) {
 try{

 KeyStore keyStore = KeyStore.getInstance("PKCS12");
 FileInputStream instream = new FileInputStream(new File(
 CustomizedPropertyPlaceholderConfigurer.getContextProperty("wx.cert").toString()));
 try {
 keyStore.load(instream, "10061401".toCharArray());
 }finally {
 instream.close();
 }

 // Trust own CA and all self-signed certs
 SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore,
 "见邮件".toCharArray()).build();
 // Allow TLSv1 protocol only
 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
 sslcontext, new String[] { "TLSv1" }, null,
 SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
 CloseableHttpClient httpclient = HttpClients.custom()
 .setSSLSocketFactory(sslsf).build();
 // HttpGet httpget = new
 // HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");
 HttpPost httppost = new HttpPost(
 "https://api.mch.weixin.qq.com/pay/unifiedorder");

 String xml = ClientCustomSSL.CreateJsApiPackage(nonceStr,orderDescribe,orderNo,price,timeStart,timeExpire,openId);
 try {

 StringEntity se = new StringEntity(xml);

 httppost.setEntity(se);

 System.out.println("executing request" + httppost.getRequestLine());

 CloseableHttpResponse responseEntry = httpclient.execute(httppost);
 try {
 HttpEntity entity = responseEntry.getEntity();

 System.out.println("----------------------------------------");
 System.out.println(responseEntry.getStatusLine());
 if (entity != null) {
 System.out.println("Response content length: "
 + entity.getContentLength());

 SAXReader saxReader = new SAXReader();
 Document document = saxReader.read(entity.getContent());
 Element rootElt = document.getRootElement();

 Document documentXml =DocumentHelper.parseText(xml);
 Element rootEltXml = documentXml.getRootElement();

 System.out.println("根节点:" + rootElt.getName());
 System.out.println("==="+rootElt.elementText("result_code"));
 System.out.println("==="+rootElt.elementText("return_msg"));
 String resultCode = rootElt.elementText("result_code");
 JSONObject result = new JSONObject();
 if(resultCode.equals("SUCCESS")){
 System.out.println("=================prepay_id===================="+ rootElt.elementText("prepay_id"));
 result.put("prepayId", rootElt.elementText("prepay_id"));
 result.put("sign",rootEltXml.elementText("sign"));
 result.put("status","success");
 result.put("msg","success");
 }else{
 result.put("status","false");
 result.put("msg",rootElt.elementText("err_code_des"));
 }

 return result;

 }
 EntityUtils.consume(entity);
 }
 finally {
 responseEntry.close();
 }
 }
 finally {
 httpclient.close();
 }
 return null;

 }catch(Exception e){
 e.printStackTrace();
 JSONObject result = new JSONObject();
 result.put("status","error");
 result.put("msg",e.getMessage());
 return result;
 }
 } 

 }

4.weixin_jspay项目中代码实现 
控制层代码

package com.weixin.jspay.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/weixinJsPay")
public class WeiXinJsPayController {

 @RequestMapping(value = "/init", method = RequestMethod.GET)
 public String init( HttpServletRequest request,HttpServletResponse response,String packageValue,String paySign) {
 System.out.println("===================微信jsPay开始=================");
 System.out.println("packageValue==============="+packageValue);
 System.out.println("paySign====================="+paySign);
 request.setAttribute("packageValue", "prepay_id=" + packageValue);
 request.setAttribute("paySign", paySign);
 System.out.println("===================微信jsPay页面跳转开始=================");
 return "weixin";
 }

}

jsp代码

<%@ page language="java" contentType="text/html; charset=utf-8"
 pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="/weixin_jspay/js/md5.js"></script>

 <script language="javascript">
 window.onload=function(){
 var packageValue = '${packageValue}';
 var paySign = '${paySign}';
 alert("packageValue======"+packageValue);
 alert("paySign======"+paySign);
 var signString ="appId=见公共账号&nonceStr=随机字符串&package="+packageValue+"&paySign="+paySign+"&signType=MD5&timeStamp=时间";
  //alert(signString);
  var md5SignValue= ("" + CryptoJS.MD5(signString)).toUpperCase();

 //alert(md5SignValue);

 WeixinJSBridge.invoke('getBrandWCPayRequest',{
  "appId" : "<span style="font-family: Arial, Helvetica, sans-serif;">见公共账号</span>",
  "timeStamp" : "1395712654",
  "nonceStr" : "123456",
  "package" : packageValue,
  "signType" : "MD5",
  "paySign" : md5SignValue
 },function(res){
 alert(res.err_msg);
 WeixinJSBridge.log(res.err_msg);
  if(res.err_msg == "get_brand_wcpay_request:ok"){
   alert("微信支付成功");
  }else if(res.err_msg == "get_brand_wcpay_request:cancel"){
   alert("用户取消支付");
  }else{
   alert("支付失败");
  }
 })
 }

 </script>
 </head>
 <body>
 <button type="button" onclick="callpay('${packageValue}','${paySign}')" >微信jsPay</button>
 </body>
</html>

微信支付MD5.js:md5.js 和微信支付开发文档:下载地址

本文已被整理到了《JavaScript微信开发技巧汇总》,欢迎大家学习阅读。

为大家推荐现在关注度比较高的微信小程序教程一篇:《微信小程序开发教程》小编为大家精心整理的,希望喜欢。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • java 实现微信服务器下载图片到自己服务器

     java 实现微信服务器下载图片到自己服务器 此功能的实现需要注意java 中IO流的操作及网路开发, 实现代码: /** * @author why * */ public class PicDownload { /** * * 根据文件id下载文件 * * * * @param mediaId * * 媒体id * * @throws Exception */ public static InputStream getInputStream(String accessToken, Stri

  • Java编程调用微信分享功能示例

    本文实例讲述了Java编程调用微信分享功能.分享给大家供大家参考,具体如下: 这篇文章介绍如何使用java开发微信分享功能,因为工作,已经开发完成,可使用. 如果想要自定义微信的分享功能,首先在自己的页面内首先使用AJAX.下面我具体举例. 首先是在页面内写入请求后台的AJAX /** * 调用微信分享接口 * */ public void WXConfig(){ String url = getPara("href"); WXConfigController scan = new W

  • Java编程调用微信接口实现图文信息推送功能

    本文实例讲述了Java编程调用微信接口实现图文信息等推送功能.分享给大家供大家参考,具体如下: Java调用微信接口工具类,包含素材上传.获取素材列表.上传图文消息内的图片获取URL.图文信息推送. 微信图文信息推送因注意html代码字符串中将双引号(")替换成单引号('),不然信息页面中包含图片将无法显示且图片后面的内容也不会显示 官方文档:http://mp.weixin.qq.com/wiki/home/ StringBuilder sb=new StringBuilder(); sb.a

  • Java开发微信公众号接收和被动回复普通消息

    上篇说完了如何接入微信公众号,本文说一下微信公众号的最基本功能:普通消息的接收和回复.说到普通消息,那么什么是微信公众号所定义的普通消息呢,微信开发者文档中提到的接收的普通消息包括如下几类: 1.文本消息 2.图片消息 3.语音消息 4.视频消息 5.小视频消息 6.地理位置消息 7.链接消息(被动回复的消息) 被动回复的普通消息包括: 1.回复文本消息 2.回复图片消息 3.回复语音消息 4.回复视频消息 5.回复音乐消息 6.回复图文消息 其实接收消息和被动回复消息这两个动作是不分家的,这本

  • java微信企业号开发之发送消息(文本、图片、语音)

    上篇文章介绍了开启回调模式,开始回调模式后我们就要实现聊天功能了.平时使用微信聊天可以发送文本消息.语音.图片.视频等,这里只实现了其中的一些功能和大家分享. 一.与微信企业号建立连接 1.企业应用调用企业号提供的接口,管理或查询企业号后台所管理的资源.或给成员发送消息等,以下称主动调用模式. 2.企业号把用户发送的消息或用户触发的事件推送给企业应用,由企业应用处理,以下称回调模式. 3.用户在微信中阅读企业应用下发的H5页面,该页面可以调用微信提供的原生接口,使用微信开放的终端能力,以下称JS

  • Java编程调用微信支付功能的方法详解

    本文实例讲述了Java编程调用微信支付功能的方法.分享给大家供大家参考,具体如下: 微信开发文档地址:https://mp.weixin.qq.com/wiki/home/ 从调用处开始 我的流程: 1.点击"支付"按钮,去后台 --> 2.后台生成支付所需数据返回页面 --> 3.页面点击"确认支付"调用微信支付js.完成支付功能. 支付按钮 <div class="button" id="pay" onc

  • java微信开发第二步 获取消息和回复消息

    接着上一篇java微信开发API第一步 服务器接入进行学习,下面介绍java微信开发第二步:获取消息和回复消息,具体内容如下 * 本示例根据微信开发文档:http://mp.weixin.qq.com/wiki/home/index.html最新版(4/3/2016 5:34:36 PM )进行开发演示. * 编辑平台:myeclipse10.7+win32+jdk1.7+tomcat7.0  * 服务器:阿里云 windows server 2008 64bits * 平台要求:servlet

  • java微信扫描公众号二维码实现登陆功能

    本文实例为大家分享了java微信扫描公众号二维码实现登陆的具体代码,供大家参考,具体内容如下 前提条件: 1.微信公众平台为服务号, 2.服务号实现了账号绑定功能,即将open_id 与业务系统中的用户名有对应关系 具体实现原理: 1.用户访问业务系统登陆页时,调用二维码接口,获得二维码的ticketid,同时将sessionid,ticketid和二维码的seceneid保存 2.返回登陆页时,根据ticketid获得微信二维码 3.页面通过ajax发送请求,判断是否已经扫描成功. 4.公众平

  • JAVA实现 springMVC方式的微信接入、实现消息自动回复实例

    前段时间小忙了一阵,微信公众号的开发,从零开始看文档,踩了不少坑,也算是熬过来了,最近考虑做一些总结,方便以后再开发的时候回顾,也给正在做相关项目的同学做个参考. 1.思路 微信接入:用户消息和开发者需要的事件推送都会通过微信方服务器发起一个请求,转发到你在公众平台配置的服务器url地址,微信方将带上signature,timestamp,nonce,echostr四个参数,我们自己服务器通过拼接公众平台配置的token,以及传上来的timestamp,nonce进行SHA1加密后匹配signa

  • Java微信公众号开发之通过微信公众号获取用户信息

    最近由于公司业务,就开始研究微信开发的流程,说实话,这东西刚开始看到时候和看天书的一样,总算,看了一天的文档,测试代码终于出来了. 1.首先需要到微信网站去设置一下,我是直接用的微信测试号. 接口配置信息必须要填写的,所以说必须能将自己的服务发布出去 到此微信配置完毕,接下来就是直接上代码了 2.获取用户信息的方式一共是两种,前提都是用户关注微信公众号,一种是静默获取(snsapi_base,这种方式只能获取openid),另一种是授权获取(snsapi_userinfo,可以获取用户的详细信息

  • 微信java开发之实现微信主动推送消息

    1.拉取access_token2.拉取用户信息3.主动推送消息4.接口貌似要申请权限5.依赖httpclient4.2.3 和jackson 2.2.1 复制代码 代码如下: public class WeixinAPIHelper { /**  * 获取token接口  */ private String getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=

随机推荐