uniapp及java后端微信的普通h5支付

uniapp及java后端微信的普通h5支付和微信公众号直接调起微信支付

uniapp端

初进时在app.vue就判断是否在微信内

App.vue代码

<script>
	export default {
		onLaunch: function(e) {
			console.log('App Launch', e)
			if(!this.$isWechat()){
				//不是微信情况下
			}else{
				//是微信情况下,调用获取code方法
				this.getWxCode();
			}
			
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods: {
			getWxCode: function() {
				var _this = this;
				let code = _this.getUrlParam("code"); //是否存在code
				let local = window.location.href;
				var url = window.location.search; //获取url包含问号的参数
				console.log("local:", local)
				var theRequest = new Object();
				if (url.indexOf("?") != -1) {
					var str = url.substr(1);
					var strs = str.split("&");
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
					}
				}
				if (code == null || code === "") {
					//不存在就打开上面的地址进行授权
					window.location.href =
						`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${_this.$getAppid()}&redirect_uri=https%3a%2f%2f域名%2findex.html%23%2fpages%2findex%2findex&response_type=code&scope=snsapi_base&state=123&connect_redirect=1#wechat_redirect`;
				} else {
					//_this.$toast("code:" + code)
					_this.$request("api/coupon/getUserMessage", {
						"code": code
					}).then(res => {
						//获取用户信息
						//_this.$toast("openId:" + res.data.openId)
						if(res.data.openId){
							uni.setStorage({
								key: "openId",
								data: res.data.openId,
							})
						}
					}).catch(err => {
						console.log(err)
					})
				}
			},
			// 判断公众号截取code
			getUrlParam: function(name) {
				let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
				let r = window.location.search.substr(1).match(reg);
				if (r != null) {
					return unescape(r[2]);
				}
				return null;
			}
		}
	}
</script>

<style>
	/*每个页面公共css */
	@import "colorui/main.css";
	@import "colorui/icon.css";
	page {
		width: 100%;
		height: 100%;
		background-color: #f2f3fb;
		/* overflow-y: scroll;
		overflow-x: hidden; */
		font-family: "Source Han Sans CN";
		font-size: 30upx;
		/* 22pt */
	}
</style>

main.js挂载

Vue.prototype.$isWechat= util.isWechat;
Vue.prototype.$request = (way, data, type, token2) => { //type不写默认post
	console.log(way, data, type, token2);
	var token = '',
		http1 = "http://****/",
		http = document.location.protocol+'//域名/';
	//此处的http修改时注意同上方的host修改为同一指向
	try { //注册过的判断是否登录
		const value = uni.getStorageSync('token');
		if (value) {
			token = value;
		}
	} catch (e) {}
	return new Promise((resolve, reject) => {
		uni.request({
			url: http + way,
			data: data || '',
			method: type || 'POST',
			header: {
				'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
				'token': token2 || token,
			},
			success: (res) => {
				console.log(way, res);
				resolve(res.data)
			},
			fail: function(res) {
				uni.showToast({
					title: "网络异常",
					icon: 'none',
					duration: 1000
				});
				reject(res);
			}
		});
	})
}

util.js代码

Core.prototype.isWechat = function() {
	return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
}

点去支付之前判断是否微信内,是跳payWx页面,不是跳pay页面

pay.vue代码

<template>
	<view class="content">
		<!-- <view class="top-title nav text-center text-white flex align-center">
			<view class="cuIcon-home text-xxl margin-left-sm" @click="$navigateBack()"></view>
			<view class="cu-item font-41 flex-sub margin-right">
				支付订单
			</view>
		</view> -->
		<view style="height: 1upx;"></view>
		<view style="height: 60upx;background-color: #FFF;"></view>
		<view class="paytitle">
			<view style="font-size: 24upx;">订单金额</view>
			<view style="font-size: 76upx;color: #333333;margin-top: 15upx;">¥{{money}}</view>
		</view>

		<view class="tips">选择支付方式</view>

		<view @click="checkedChange(1)" class="payType" v-if="!$isWechat()">
			<image style="width: 85upx;height: 85upx;" src="../../static/zhifubao.png"></image>
			<view class="flex flex-direction">
				<text style="font-size: 28upx;margin-left: 40upx;">支付宝</text>
				<text style="font-size: 22upx;margin-left: 40upx;color: #888888;">推荐已安装支付宝的用户使用</text>
			</view>
			<view class="body-check">
				<view :class="aliChecked?'cuIcon-roundcheckfill text-blue2 font-44':'check-false'">
				</view>
			</view>
		</view>

		<view @click="checkedChange(0)" class="payType" ><!--  v-if="$isWechat()"  -->
			<image mode="scaleToFill" style="width: 85upx;height: 85upx;margin-top: 5upx;"
				src="../../static/weixin.png"></image>
			<view class="flex flex-direction">
				<text style="font-size: 28upx;margin-left: 40upx;">微信支付</text>
				<text style="font-size: 22upx;margin-left: 40upx;color: #888888;">推荐已安装微信的用户使用</text>
			</view>
			<view class="body-check">
				<view :class="weixinChecked?'cuIcon-roundcheckfill text-blue2 font-44':'check-false'">
				</view>
			</view>
		</view>
		<button class="paySubmiy font-35" @click="goPay">确认支付</button>
		<view v-html="zfbH5" style="display: none;">
			
		</view>
	</view>
</template>

<script>
	import wxPay from '@/util/wxPay.js'
	export default {
		data() {
			return {
				weixinChecked: true,
				aliChecked: false,
				orderId: '2021092214355896095721',
				money: 0.01,
				payResult: 0, //0 初始状态 1 支付中状态 2 支付成功
				num: 10,
				zfbH5:''
			}
		},
		onLoad(option) {
			console.log(option,);
			if(!this.$isWechat()){
				this.weixinChecked = false;
				this.aliChecked = true;
			}
			if (option.orderId) {
				this.orderId = option.orderId;
			}
			if (option.money) {
				this.money = option.money;
			}
			console.log(this.orderId,this.money);
		},
		onShow() {
			this.showResult();
			//this.ifPayOk();
		},
		methods: {
			checkedChange(index) {
				if (index == 0) {
					this.weixinChecked = true;
					this.aliChecked = false;
				} else if (index == 1) {
					this.weixinChecked = false;
					this.aliChecked = true;
				}
			},
			showResult() {
				var _this = this;
				//_this.$toast(_this.orderId);
				if (_this.weixinChecked) {
					if (this.payResult == 1) {
						uni.showLoading({
							title: "支付结果查询中...",
							mask: true
						})
						_this.ifPayOk();
					}
				}
			},
			ifPayOk() {
				var _this = this;
				_this.num--;
				setTimeout(function(){
					_this.$request('查询订单支付结果方法', {
						orderNo: _this.orderId
					}).then(res => {
						if (res.code == 0) {
							if (res.data.couponOrder.status==1) {
								uni.hideLoading();
								_this.payResult = 2;
								_this.$redirectTo("paySuccess");
							} else if (res.data.couponOrder.status==2) {
								_this.$uniApi.showToastNoIcon("订单支付失败!");
							} else if (res.data.couponOrder.status==0&&_this.num>0) {
								_this.ifPayOk();
							} else if (_this.num == 0) {
								_this.$uniApi.showToastNoIcon("网络忙!请稍后重试");
							}
						}else{
							_this.$toast(res.msg)
						}
					}).catch(err => {
						uni.hideLoading();
					})
				},500)
			},
			goPay() {
				let _this = this;
				uni.showLoading({
					title: "请稍后...",
					mask: true
				})
				if (_this.weixinChecked) {
					let local = window.location.href;
					_this.$request("api/wxjsapi/getJsTicket", {
						url: local,
					}).then(res => {
						if (res.code == 0) {
							console.log('getJsTicket', res);
							res.data.timestamp = Number(res.data.timestamp);
							this.payResult = 1;
							// #ifdef H5
							var data1 = res.data;
							var o = {
								orderId: _this.orderId,
								money: _this.money,
							};
							_this.$request("api/wxjsapi/unifiedorder_mp", o).then(res => {
								uni.hideLoading();
								if (res.code == 0) {
									if(!!res.data.payStatus){
										_this.$redirectTo("paySuccess");
									} else {
										console.log(res.data.data.mweb_url);
										window.location.href = res.data.data.mweb_url+"&redirect_url=https%3A%2F%2F放置页面的域名%2F%23%2Fpages%2Findex%2FpaySuccess";
									} 
								} else {
									_this.$uniApi.showToastNoIcon(res.msg);
								}
							}).catch(err => {
								console.log(err)
							})
							// #endif
						} else {
							_this.$uniApi.showToastNoIcon("订单支付失败!");
						}

					})
				} else {
					var url = "api/zfbH5/hgzsPayTra";
					_this.$request(url, {
						subject: '兑换券使用',
						outTradeNo: _this.orderId,//'2021072815093555808081',//
						totalAmount: _this.money,
						body: '兑换券使用H5支付',
						returnUrl:'域名/#/pages/index/paySuccess',
						type:1
					}).then(res => {
						if (res.code == 0) {
							if(res.msg != "操作成功"){
								_this.zfbH5 = res.msg
								// #ifdef H5
								setTimeout(function(){
									uni.hideLoading();
									document.forms[0].submit();
								},500)
								// #endif
							}else if(!!res.data.payStatus){
								_this.$redirectTo("paySuccess");
							}
						} else {
							_this.$uniApi.showToastNoIcon(res.msg);
						}
					}).catch(err => {
						console.log(err)
					})
				}

			}

		}
	}
</script>

<style>
	.paytitle {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		height: 260upx;
		background-color: #FFFFFF;
		margin-bottom: 30upx;
	}

	.payType {
		display: flex;
		flex-direction: row;
		align-items: center;
		width: 750upx;
		height: 140upx;
		padding: 15upx 66upx;
		border: 2upx solid #F2F3FB;
		position: relative;
		background-color: #FFFFFF;
	}

	.flex {
		padding: 0upx;
	}

	.tips {
		width: 750upx;
		height: 100upx;
		background-color: #FFFFFF;
		line-height: 100upx;
		padding-left: 66upx;
	}

	.body-check {
		display: flex;
		width: 90upx;
		position: absolute;
		right: 0;
	}

	.text-blue2 {
		color: #19aef8;
	}

	.check-false {
		width: 36upx;
		height: 37upx;
		background: #F5F6F8;
		border: 1px solid #C1C1C1;
		border-radius: 50%;
	}

	.paySubmiy {
		margin-top: 200upx;
		position: fixed;
		background-color: #00cbff;
		color: white;
		line-height: 80upx;
		height: 80upx;
		width: 542upx;
		left: 104upx;
		border-radius: 40upx;
	}
	uni-button:after {
	    border: 0 !important;
	}
</style>

payWx.vue

<template>
	<view class="content">
		<!-- <view class="top-title nav text-center text-white flex align-center">
			<view class="cuIcon-home text-xxl margin-left-sm" @click="$navigateBack()"></view>
			<view class="cu-item font-41 flex-sub margin-right">
				支付订单
			</view>
		</view> -->
		<view style="height: 1upx;"></view>
		<view style="height: 60upx;background-color: #FFF;"></view>
		<view class="paytitle">
			<view style="font-size: 24upx;">订单金额</view>
			<view style="font-size: 76upx;color: #333333;margin-top: 15upx;">¥{{money}}</view>
		</view>

		<view class="tips">选择支付方式</view>

		<!-- <view @click="checkedChange(1)" class="payType" v-if="!$isWechat()">
			<image style="width: 85upx;height: 85upx;" src="../../static/zhifubao.png"></image>
			<view class="flex flex-direction">
				<text style="font-size: 28upx;margin-left: 40upx;">支付宝</text>
				<text style="font-size: 22upx;margin-left: 40upx;color: #888888;">推荐已安装支付宝的用户使用</text>
			</view>
			<view class="body-check">
				<view :class="aliChecked?'cuIcon-roundcheckfill text-blue2 font-44':'check-false'">
				</view>
			</view>
		</view> -->

		<view @click="checkedChange(0)" class="payType">
			<!--  v-if="$isWechat()"  -->
			<image mode="scaleToFill" style="width: 85upx;height: 85upx;margin-top: 5upx;"
				src="../../static/weixin.png"></image>
			<view class="flex flex-direction">
				<text style="font-size: 28upx;margin-left: 40upx;">微信支付</text>
				<text style="font-size: 22upx;margin-left: 40upx;color: #888888;">推荐已安装微信的用户使用</text>
			</view>
			<view class="body-check">
				<view :class="weixinChecked?'cuIcon-roundcheckfill text-blue2 font-44':'check-false'">
				</view>
			</view>
		</view>
		<button class="paySubmiy font-35" @click="goPay">确认支付</button>
		<!-- <view v-html="zfbH5" style="display: none;">
			
		</view> -->
	</view>
</template>

<script>
	import wxPay from '@/util/wxPay.js'
	export default {
		data() {
			return {
				weixinChecked: true,
				aliChecked: false,
				orderId: '2021092214355896095721',
				money: 0.01,
				payResult: 0, //0 初始状态 1 支付中状态 2 支付成功
				num: 10,
				zfbH5: '',
				openid: '',
				Code: '',
			}
		},
		onLoad(option) {
			console.log(option, );
			if (!this.$isWechat()) {
				this.weixinChecked = false;
				this.aliChecked = true;
			}
			if (option.orderId) {
				this.orderId = option.orderId;
			}
			if (option.money) {
				this.money = option.money;
			}
			console.log(this.orderId, this.money);
		},
		onShow() {
			this.showResult();
			//this.ifPayOk();
		},
		methods: {
			checkedChange(index) {
				if (index == 0) {
					this.weixinChecked = true;
					this.aliChecked = false;
				} else if (index == 1) {
					this.weixinChecked = false;
					this.aliChecked = true;
				}
			},
			showResult() {
				var _this = this;
				//_this.$toast(_this.orderId);
				if (_this.weixinChecked) {
					if (this.payResult == 1) {
						uni.showLoading({
							title: "支付结果查询中...",
							mask: true
						})
						_this.ifPayOk();
					}
				}
			},
			ifPayOk() {
				var _this = this;
				_this.num--;
				setTimeout(function() {
					_this.$request('查询订单状态', {
						orderNo: _this.orderId
					}).then(res => {
						if (res.code == 0) {
							if (res.data.couponOrder.status == 1) {
								uni.hideLoading();
								_this.payResult = 2;
								_this.$redirectTo("paySuccess");
							} else if (res.data.couponOrder.status == 2) {
								_this.$uniApi.showToastNoIcon("订单支付失败!");
							} else if (res.data.couponOrder.status == 0 && _this.num > 0) {
								_this.ifPayOk();
							} else if (_this.num == 0) {
								_this.$uniApi.showToastNoIcon("订单支付失败!");
								//_this.$uniApi.showToastNoIcon("网络忙!请稍后重试");
							}
						} else {
							_this.$toast(res.msg)
						}
					}).catch(err => {
						uni.hideLoading();
					})
				}, 500)
			},
			getUrlParam(key) {
			   var href = window.location.href;
			   var url = href.split("?");
			   if(url.length <= 1){
			      return "";
			   }
			   var params = url[1].split("&");
			   
			   for(var i=0; i<params.length; i++){
			      var param = params[i].split("=");
			      if(key == param[0]){
			         return param[1];
			      }
			   }
			},
			goPay() {
				let _this = this;
				uni.showLoading({
					title: "请稍后...",
					mask: true
				})
				const openId = uni.getStorageSync('openId')
				if (_this.weixinChecked) {
					let local = window.location.href;
					_this.$request("api/wxjsapi/getJsTicket", {
						url: local,
					}).then(res => {
						if (res.code == 0) {
							console.log('getJsTicket', res);
							res.data.timestamp = Number(res.data.timestamp);
							this.payResult = 1;
							var data1 = res.data;
							var o = {
								orderId: _this.orderId,
								openid: openId,
								money: _this.money,
							};
							_this.$request("api/wxjsapi/unifiedorder_wx", o).then(res => {
								uni.hideLoading();
								if (res.code == 0) {
									if(!!res.data.payStatus){
										_this.$redirectTo("paySuccess");
										return;
									}
									var orderInfo = { //appId, timestamp,timestamp1, nonceStr,nonceStr1, signature, packages,prepayid, paySign
										appId: data1.appId,
										timestamp: data1.timestamp,
										nonceStr: data1.nonceStr,
										signature: data1.signature,
										nonceStr1: res.data.nonceStr,
										packages: res.data.package,
										//partnerid: res.data.data.partnerid,
										prepayid: res.data.prepayid,
										timestamp1: res.data.timeStamp,
										paySign: res.data.paySign
									}
									wxPay(orderInfo, s => {
										console.log('aaaa', res)
										_this.$redirectTo('/pages/pay/paySuccess');
										//window.location.href = `/h5/#/pages/order/index`
									}, e => {
										console.log('dddd', res)
										console.log(res)
										_this.$uniApi.showToastNoIcon("订单支付失败!");
								} else {
									_this.$uniApi.showToastNoIcon(res.msg);
								}
							}).catch(err => {
								console.log(err)
							})
						} else {
							_this.$uniApi.showToastNoIcon("订单支付失败!");
						}

					})
				} else {
					var url = "api/zfbH5/hgzsPayTra";
					_this.$request(url, {
						subject: '兑换券使用',
						outTradeNo: _this.orderId, //'2021072815093555808081',//
						totalAmount: _this.money,
						body: '兑换券使用H5支付',
						returnUrl: 'https://couponh5.hgzsedu.com/#/pages/index/paySuccess',
						type: 1
					}).then(res => {
						if (res.code == 0) {
							if (res.msg != "操作成功") {
								_this.zfbH5 = res.msg
								// #ifdef H5
								setTimeout(function() {
									uni.hideLoading();
									document.forms[0].submit();
								}, 500)
								// #endif
							} else if (!!res.data.payStatus) {
								_this.$redirectTo("paySuccess");
							}
						} else {
							_this.$uniApi.showToastNoIcon(res.msg);
						}
					}).catch(err => {
						console.log(err)
					})
				}

			}

		}
	}
</script>

<style>
	.paytitle {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		height: 260upx;
		background-color: #FFFFFF;
		margin-bottom: 30upx;
	}

	.payType {
		display: flex;
		flex-direction: row;
		align-items: center;
		width: 750upx;
		height: 140upx;
		padding: 15upx 66upx;
		border: 2upx solid #F2F3FB;
		position: relative;
		background-color: #FFFFFF;
	}

	.flex {
		padding: 0upx;
	}

	.tips {
		width: 750upx;
		height: 100upx;
		background-color: #FFFFFF;
		line-height: 100upx;
		padding-left: 66upx;
	}

	.body-check {
		display: flex;
		width: 90upx;
		position: absolute;
		right: 0;
	}

	.text-blue2 {
		color: #19aef8;
	}

	.check-false {
		width: 36upx;
		height: 37upx;
		background: #F5F6F8;
		border: 1px solid #C1C1C1;
		border-radius: 50%;
	}

	.paySubmiy {
		margin-top: 200upx;
		position: fixed;
		background-color: #00cbff;
		color: white;
		line-height: 80upx;
		height: 80upx;
		width: 542upx;
		left: 104upx;
		border-radius: 40upx;
	}

	uni-button:after {
		border: 0 !important;
	}
</style>

wxPay.js

/*
  微信支付方法(uni-app h5)适用
  获取微信加签信息
  @param{data}:获取的微信加签
  @param{res}:成功回调
  @param{fail}:失败回调
    
  @warn:因为package为严格模式下的保留字,不能用作变量.
  @use
    wxPay({
      appId,
      timeStamp,
      nonceStr,
      signature,
      package,
      paySign
    },res=>{
      console.log('调用成功!');
    },fail=>{
      console.log('调用失败!');
    })
*/
// #ifdef H5
const wx = require('jweixin-module');
// #endif
const wxPay = (data, callback, errCallback) => {
 
  const {appId, timestamp,nonceStr, signature,timestamp1, nonceStr1,prepayid, packages, paySign} = data;

  wx.config({
    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
    appId,      // 必填,公众号的唯一标识
    timestamp,  // 必填,生成签名的时间戳
    nonceStr,   // 必填,生成签名的随机串
    signature,  // 必填,签名,见附录1
    jsApiList: ['chooseWXPay'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
  });

  wx.ready(function() {
    wx.chooseWXPay({
      timestamp:timestamp1, // 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
      nonceStr:nonceStr1, // 支付签名随机串,不长于 32 位
      'package': packages, // 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=***)
      'signType': 'MD5', // 签名方式,默认为'SHA1',使用新版支付需传入'MD5'
      paySign:paySign, // 支付签名
      success(res) {
        // 支付成功后的回调函数
		console.log('cg')
        callback(res);
      },
      fail(res) {
		  console.log('sb')
        errCallback(res);
      }
    });
  });

  wx.error(function(res) {
    // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
    /*alert("config信息验证失败");*/
  });
}
 
export default wxPay;

java端

根据code获取用户h5微信openId

/**
	 * 根据code获取用户h5微信openId
	 * @throws IOException 
	 */
	@PostMapping("/getUserMessage")
	@ResponseBody
	@ApiOperation("根绝code获取用户h5微信openId")
	public AjaxResult getUserMessage(String code) throws IOException
	{	
		Map<String,String> map = new MessageAct().weixinLogin(code);
		String wxOpenId = map.get("openId");
		String sex = map.get("sex");
		String avatar =  map.get("headimgurl");
		String userName = map.get("nickname");
		Map m = new HashMap<>();
    	m.put("openId", wxOpenId);
		return AjaxResult.success(m);
		
	}

WxJsApiController.java

package com.aproject.sample.weixinpay.controller;

 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import com.aproject.framework.aspectj.lang.annotation.Log;
import com.aproject.framework.aspectj.lang.enums.BusinessType;
import com.aproject.framework.web.domain.AjaxResult;
import com.aproject.project.system.user.domain.User;
import com.aproject.project.system.user.mapper.UserMapper;
import com.aproject.project.system.user.service.IUserService;
import com.aproject.sample.oms.domain.OmsOrder;
import com.aproject.sample.oms.domain.OmsTransLog;
import com.aproject.sample.oms.service.OmsTransLogService;
import com.aproject.sample.pms.domain.PmsCoupon;
import com.aproject.sample.pms.domain.PmsCouponDetails;
import com.aproject.sample.pms.domain.PmsCouponOrder;
import com.aproject.sample.pms.domain.PmsProduct;
import com.aproject.sample.pms.service.PmsCouponDetailsService;
import com.aproject.sample.pms.service.PmsCouponOrderService;
import com.aproject.sample.pms.service.PmsCouponService;
import com.aproject.sample.pms.service.PmsProductService;
import com.aproject.sample.weixinpay.payUtils.PayCommonUtil;
import com.aproject.sample.weixinpay.payUtils.StringUtil;
import com.aproject.sample.weixinpay.payUtils.WXPay;
import com.aproject.sample.weixinpay.payUtils.WXPayConfig;
import com.aproject.sample.weixinpay.payUtils.WXPayConfig2;
import com.aproject.sample.weixinpay.payUtils.WXPayConfigImpl;
import com.aproject.sample.weixinpay.service.WxOrderService;
import com.aproject.sample.weixinpay.util.WeChatUtil;
import com.aproject.weixin.util.AccessToken;
import com.aproject.weixin.util.WX_TokenUtil;
import com.aproject.weixin.util.WX_TokenUtil2;
import com.aproject.weixin.util.WeChatUtil2;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.jdom2.JDOMException;


/**
 * 微信h5支付相关接口
 * 
 */

@Api(tags = "微信JsApi支付相关接口")
@RestController
@RequestMapping("/api/wxjsapi")
public class WxJsApiController {
	private static final Logger log = LoggerFactory.getLogger(WxJsApiController.class);

    @Autowired
	WxOrderService wxOrderService;

	@ApiOperation("调用起微信支付jsapi")
	@PostMapping("/getJsTicket")
	@ResponseBody
	public AjaxResult getWeJsTicket(HttpSession session,HttpServletRequest request, String url) {
		Map<String, Object> map = new HashMap<String, Object>();
			AccessToken access_token = WX_TokenUtil.getWXToken();
			System.out.println("access_token===="+access_token);
			String jsapi_ticket=WeChatUtil.getSapi_ticket(access_token.getAccessToken());
			String nonceStr=WeChatUtil.create_nonce_str();
			String timestamp=WeChatUtil.create_timestamp();
			String signature=WeChatUtil.getSignature(access_token.getAccessToken(), nonceStr, timestamp, jsapi_ticket, url);
			//获取access_token
			//	   Access_token access = viCaseService.getAccessToken(1, url,request);		   
			//	   //4获取url
			map.put("appId", WXPayConfig.WX_App_ID);
			map.put("timestamp", timestamp);
			map.put("nonceStr", nonceStr);
			map.put("signature", signature);
			map.put("access_token", access_token.getAccessToken());
			map.put("ticket", jsapi_ticket);
			return AjaxResult.success(map);
		
	}
	
	
	
	/**
	 * 调用起微信h5支付
	 * @throws Exception 
	 */
	@ApiOperation("调用起微信h5支付")
	@PostMapping("/unifiedorder_mp")
	@ResponseBody
	@Transactional
	public AjaxResult unifiedorder_mp(HttpServletRequest request,String orderId,String openid,String money) throws Exception{
		Map m = new HashMap<>();
		float cardprice1 = Float.parseFloat(payAmount.toString()) * 100;//微信的支付单位是分所以要转换一些单位
        int cardmoney = (int) cardprice1;
        
        String totalproce = String.valueOf(cardmoney);
        	m=wxOrderService.wxpay(request, 
    				openid, 
    				orderId,//订单号
    				totalproce);
		return AjaxResult.success(m);
	}
	
	
	
	/**
	 * @param totalAmount    支付金额
	 * @param description    描述
	 * @param request
	 * @return
	 * @throws IOException 
	 * @throws JDOMException 
	 */
	@RequestMapping("/notifyWeiXinPay")
	@ResponseBody 
	@Transactional
	public  String notifyWeiXinPay(HttpServletRequest request) throws IOException, JDOMException {
		System.out.println("微信支付回调");
		InputStream inStream = request.getInputStream();
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outSteam.write(buffer, 0, len);
		}
		String resultxml = new String(outSteam.toByteArray(), "utf-8");
		Map<String, String> params = PayCommonUtil.doXMLParse(resultxml);
		outSteam.close();
		inStream.close();

		Map<String,String> return_data = new HashMap<String,String>();  
		if (!PayCommonUtil.isTenpaySign(params)) {
			// 支付失败
			System.out.println("支付失败==="+params);
			return_data.put("return_code", "FAIL");  
			return_data.put("return_msg", "return_code不正确");
			return StringUtil.GetMapToXML(return_data);
		} else {
			System.out.println("===============付款成功==============");
			// ------------------------------
			// 处理业务开始
			//获取订单编号,修改订单状态以及商户插入待入账金额
			
			}
			
			
			return_data.put("return_code", "SUCCESS");  
			return_data.put("return_msg", "OK");  
			return StringUtil.GetMapToXML(return_data);
		}
	}
	
	@Log(title = "调用起微信小程序支付jsapi ", businessType = BusinessType.OTHER)
	@ApiOperation("调用起微信小程序支付jsapi" )
	@PostMapping("/getXcxJsTicket")
	@ResponseBody
	public AjaxResult getXcxJsTicket(HttpSession session,HttpServletRequest request, String url) {
		Map<String, Object> map = new HashMap<String, Object>();
			AccessToken access_token=WX_TokenUtil2.getWXToken();
			System.out.println("access_token===="+access_token);
			String jsapi_ticket=WeChatUtil2.getSapi_ticket(access_token.getAccessToken());
			String nonceStr=WeChatUtil2.create_nonce_str();
			String timestamp=WeChatUtil2.create_timestamp();
			String signature=WeChatUtil2.getSignature(access_token.getAccessToken(), nonceStr, timestamp, jsapi_ticket, url);
			//获取access_token
			//	   Access_token access = viCaseService.getAccessToken(1, url,request);		   
			//	   //4获取url
			map.put("appId", WXPayConfig2.WX_App_ID);
			map.put("timestamp", timestamp);
			map.put("nonceStr", nonceStr);
			map.put("signature", signature);
			map.put("access_token", access_token.getAccessToken());
			map.put("ticket", jsapi_ticket);
			return AjaxResult.success(map);
		
	}
	
	/**
	 * 调用起微信公众号jsapi支付
	 * @throws Exception 
	 */
	@ApiOperation("调用起微信公众号jsapi支付")
	@PostMapping("/unifiedorder_wx")
	@ResponseBody
	@Transactional
	public AjaxResult unifiedorder_wx(HttpServletRequest request,String orderId,String openid,String money) throws Exception{
		Map m = new HashMap<>();
		
		float cardprice1 = Float.parseFloat(payAmount.toString()) * 100;//微信的支付单位是分所以要转换一些单位
        int cardmoney = (int) cardprice1;
        String totalproce = String.valueOf(cardmoney);
        	m=wxOrderService.wxpayNoH5(request, 
    				openid, 
    				orderId,//订单号
    				totalproce);
		return AjaxResult.success(m);
	}
	
    
}

WxOrderService.java

package com.aproject.sample.weixinpay.service;

import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.aproject.framework.web.domain.AjaxResult;
import com.aproject.sample.oms.domain.OmsOrder;
import com.aproject.sample.oms.service.OmsOrderService;
import com.aproject.sample.oms.service.OmsTransLogService;
import com.aproject.sample.weixinpay.payUtils.PayCommonUtil;
import com.aproject.sample.weixinpay.payUtils.StringUtils;
import com.aproject.sample.weixinpay.payUtils.WXPay;
import com.aproject.sample.weixinpay.payUtils.WXPay2;
import com.aproject.sample.weixinpay.payUtils.WXPayConfig;
import com.aproject.sample.weixinpay.payUtils.WXPayConfig2;
import com.aproject.sample.weixinpay.payUtils.WXPayConfigImpl;
import com.aproject.sample.weixinpay.payUtils.WXPayConfigImpl2;

import cn.hutool.log.Log;
import net.sf.json.JSONObject;


/**
 * @功能说明:微信支付,订单服务类
 */
@Transactional
@Repository("WxOrderService")
public class WxOrderService {
	private static final Logger log = LoggerFactory.getLogger(WxOrderService.class);
	
	@Autowired
    private OmsOrderService omsOrderService;
	@Autowired
    private OmsTransLogService omsTransLogService;
	/**
	 * h5支付创建微信订单
	 * @param openid 用户openid
	 * @param out_trade_no 根据逻辑自己生成的订单编号
	 * @param total_fee 金额,必须是整数形式的String,单位是分
	 * @return map
	 */
	public  Map<String, Object> wxpay(HttpServletRequest request,String openid,String out_trade_no,String total_fee) throws Exception {
		 Map<String, Object> map = new HashMap<String, Object>();
		 WXPayConfigImpl config = new WXPayConfigImpl();
	     WXPay wxpay = new WXPay(config);
	        Map<String, String> data = new HashMap<String, String>();
	        data.put("appid", WXPayConfig.WX_App_ID);
	        data.put("body", "cbyt-ls");
	        data.put("out_trade_no", out_trade_no);
	        data.put("device_info", "WEB");
	        data.put("mch_id", WXPayConfig.MCH_ID);
	        data.put("fee_type", "CNY");
	        data.put("total_fee", total_fee);
	        data.put("spbill_create_ip", "ip");
	        data.put("notify_url", WXPayConfig.PAY_HUL+"/api/wxjsapi/notifyWeiXinPay");
//	        data.put("openid", openid);
	        data.put("trade_type", "MWEB");  //h5支付
	     try {
	    	 System.out.println("data===="+data);
	         Map<String, String> resp = wxpay.unifiedOrder(data);
	         map.put("data", resp);
	         	//通过返回值二次签名
	         	String return_code = resp.get("return_code");
	         	map.put("msga", resp.get("return_msg"));
	         	System.out.println("return_code========"+return_code);
	         	System.out.println("msga========"+resp);
				//返回给小程序端需要的参数  
				if(return_code=="SUCCESS"||return_code.equals(return_code)) {
					//返回的预付单信息 
					String prepay_id = (String) resp.get("prepay_id");
					
		            Long timeStamp = System.currentTimeMillis() / 1000;//微信是按照分来算的,我们是按照元来算的,所以需要转换
		            String stringSignTemp = "appId=" + WXPayConfig.WX_App_ID + "&nonceStr=" + resp.get("nonce_str") + "&package=prepay_id=" + prepay_id + "&signType=MD5&timeStamp=" + timeStamp;
		            map.put("appId", WXPayConfig.WX_App_ID);
		            map.put("timeStamp", timeStamp+ "");
		            map.put("nonceStr",resp.get("nonce_str")); 
		            map.put("package", "prepay_id="+prepay_id);	
		            map.put("prepayid", prepay_id);
		            String mysignTow = PayCommonUtil.sign(stringSignTemp, WXPayConfig.MCH_KEY, "utf-8").toUpperCase();
					//sign签名,第二次随机签名
					map.put("paySign", mysignTow);
					log.info("timeStamp", timeStamp);
					log.info("prepayid", prepay_id);
					log.info("paySign", mysignTow);
					log.info("stringSignTemp", stringSignTemp);
					
					
					String mwebUrl = resp.get("mweb_url"); //web_url为拉起微信支付收银台的中间页面,可通过访问该url来拉起微信客户端,完成支付,mweb_url的有效期为5分钟。
					System.out.println("------------" + mwebUrl);
					
					
					
					
					map.put("mwebUrl", mwebUrl);
				}
				
	         System.out.println(resp);
	     } catch (Exception e) {
	         e.printStackTrace();
	     }
	     return map;
	 }
	
	
	//获取IP
	private String getIpAddr(HttpServletRequest request) {
	 String ip = request.getHeader("X-Forwarded-For");
	 if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
	  //多次反向代理后会有多个ip值,第一个ip才是真实ip
	  int index = ip.indexOf(",");
	  if (index != -1) {
	   return ip.substring(0, index);
	  } else {
	   return ip;
	  }
	 }
	 ip = request.getHeader("X-Real-IP");
	 if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
	  return ip;
	 }
	 return request.getRemoteAddr();
	}
	
	/**
	 * 小程序创建微信订单
	 * @param openid 用户openid
	 * @param out_trade_no 根据逻辑自己生成的订单编号
	 * @param total_fee 金额,必须是整数形式的String,单位是分
	 * @return map
	 */
	public  Map<String, Object> wxpayXcx(String openid,String out_trade_no,String total_fee) throws Exception {
		 Map<String, Object> map = new HashMap<String, Object>();
		 WXPayConfigImpl2 config = new WXPayConfigImpl2();
	     WXPay2 wxpay = new WXPay2(config);
	        Map<String, String> data = new HashMap<String, String>();
	        data.put("appid", WXPayConfig2.WX_App_ID);
	        data.put("body", "cbyt-ls");
	        data.put("out_trade_no", out_trade_no);
	        data.put("device_info", "WEB");
	        data.put("mch_id", WXPayConfig2.MCH_ID);
	        data.put("fee_type", "CNY");
	        data.put("total_fee", total_fee);
	        data.put("spbill_create_ip", WXPayConfig2.SPBILL_CREATE_IP);
	        data.put("notify_url", WXPayConfig2.PAY_HUL+"/weixin/hgzsPayNotify");
	        data.put("openid", openid);
	        data.put("trade_type", "JSAPI");  // 此处指定为扫码支付
	     try {
	    	 System.out.println("data===="+data);
	         Map<String, String> resp = wxpay.unifiedOrder(data);
	         map.put("data", resp);
	         	//通过返回值二次签名
	         	String return_code = resp.get("return_code");
	         	map.put("msga", resp.get("return_msg"));
	         	System.out.println("return_code========"+return_code);
	         	System.out.println("msga========"+resp);
				//返回给小程序端需要的参数  
				if(return_code.equals("SUCCESS")) {
					//返回的预付单信息 
					String prepay_id = (String) resp.get("prepay_id");
					
		            Long timeStamp = System.currentTimeMillis() / 1000;//微信是按照分来算的,我们是按照元来算的,所以需要转换
		            String stringSignTemp = "appId=" + WXPayConfig2.WX_App_ID + "&nonceStr=" + resp.get("nonce_str") + "&package=prepay_id=" + prepay_id + "&signType=MD5&timeStamp=" + timeStamp;
		            map.put("appId", WXPayConfig2.WX_App_ID);
		            map.put("timeStamp", timeStamp);
		            map.put("nonceStr",resp.get("nonce_str")); 
		            map.put("package", "prepay_id="+prepay_id);	
		            map.put("prepayid", prepay_id);
		            String mysignTow = PayCommonUtil.sign(stringSignTemp, WXPayConfig2.MCH_KEY, "utf-8").toUpperCase();
					//sign签名,第二次随机签名
					map.put("paySign", mysignTow);
					System.out.println("timeStamp"+timeStamp);
					System.out.println("prepayid"+ prepay_id);
					System.out.println("paySign"+ mysignTow);
					System.out.println("stringSignTemp"+stringSignTemp);
					//添加支付记录表记录
                    OmsOrder order = omsOrderService.selectOmsOrderById(Long.parseLong(out_trade_no)); //商品订单
                    if(omsTransLogService.selectOmsTransLogIsExist(out_trade_no) == 0) {
                    	omsTransLogService.insertOmsTransLogByAllPay("1", order.getMemberId(), order.getMemberUsername(), WXPayConfig2.MCH_ID, "支付主体", out_trade_no, "6", "商城购物", order.getTotalAmount(), "", "", WXPayConfig2.MCH_ID, "1", "2", "0");
                    }
                    
				}else {
					System.out.println("没有返回我接受到的微信参数");
				}
	         System.out.println(resp);
	     } catch (Exception e) {
	         e.printStackTrace();
	     }
	     return map;
	 }
	
	/**
	 * 公众号创建微信订单
	 * @param openid 用户openid
	 * @param out_trade_no 根据逻辑自己生成的订单编号
	 * @param total_fee 金额,必须是整数形式的String,单位是分
	 * @return map
	 */
	public  Map<String, Object> wxpayNoH5(HttpServletRequest request,String openid,String out_trade_no,String total_fee) throws Exception {
		 Map<String, Object> map = new HashMap<String, Object>();
		 WXPayConfigImpl config = new WXPayConfigImpl();
	     WXPay wxpay = new WXPay(config);
	        Map<String, String> data = new HashMap<String, String>();
	        data.put("appid", WXPayConfig.WX_App_ID);
	        data.put("body", "cbyt-ls");
	        data.put("out_trade_no", out_trade_no);
	        data.put("device_info", "WEB");
	        data.put("mch_id", WXPayConfig.MCH_ID);
	        data.put("fee_type", "CNY");
	        data.put("total_fee", total_fee);
	        data.put("spbill_create_ip", "ip");
	        data.put("notify_url", WXPayConfig.PAY_HUL+"/api/wxjsapi/notifyWeiXinPay");
	        data.put("openid", openid);
	        data.put("trade_type", "JSAPI");  // 此处指定为JSAPI支付
	     try {
	    	 System.out.println("data===="+data);
	         Map<String, String> resp = wxpay.unifiedOrder(data);
	         map.put("data", resp);
	         	//通过返回值二次签名
	         	String return_code = resp.get("return_code");
	         	map.put("msga", resp.get("return_msg"));
	         	System.out.println("return_code========"+return_code);
	         	System.out.println("msga========"+resp);
				//返回给小程序端需要的参数  
				if(return_code=="SUCCESS"||return_code.equals(return_code)) {
					//返回的预付单信息 
					String prepay_id = (String) resp.get("prepay_id");
					
		            Long timeStamp = System.currentTimeMillis() / 1000;//微信是按照分来算的,我们是按照元来算的,所以需要转换
		            String stringSignTemp = "appId=" + WXPayConfig.WX_App_ID + "&nonceStr=" + resp.get("nonce_str") + "&package=prepay_id=" + prepay_id + "&signType=MD5&timeStamp=" + timeStamp;
		            map.put("appId", WXPayConfig.WX_App_ID);
		            map.put("timeStamp", timeStamp+ "");
		            map.put("nonceStr",resp.get("nonce_str")); 
		            map.put("package", "prepay_id="+prepay_id);	
		            map.put("prepayid", prepay_id);
		            String mysignTow = PayCommonUtil.sign(stringSignTemp, WXPayConfig.MCH_KEY, "utf-8").toUpperCase();
					//sign签名,第二次随机签名
					map.put("paySign", mysignTow);
					log.info("timeStamp", timeStamp);
					log.info("prepayid", prepay_id);
					log.info("paySign", mysignTow);
					log.info("stringSignTemp", stringSignTemp);
				}
				
	         System.out.println(resp);
	     } catch (Exception e) {
	         e.printStackTrace();
	     }
	     return map;
	 }
	
	
}

其他支付代码与原来支付代码相同

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值