• 【uniapp微信小程序+springBoot(binarywang)


    uniapp前端代码

    <template>
        <view>
            <page-head :title="title"></page-head>
            <view class="uni-padding-wrap">
                <view style="background:#FFF; padding:50rpx 0;">
    				 <view class="uni-hello-text uni-center font-lg text-danger">{{vipName}}</view>
                    <view class="uni-h1 uni-center uni-common-mt">
                        <text class="rmbLogo"></text>
                        <input class="price" type="digit" :value="price" maxlength="5" @input="priceChange" />
                    </view>
                </view>
                <view class="uni-btn-v uni-common-mt">
                    <!-- #ifdef MP-WEIXIN || MP-QQ -->
                    <button type="primary" @click="weixinPay" :loading="loading">微信支付</button>
                    <!-- #endif -->
                </view>
            </view>
        </view>
        </view>
    </template>
    <script>
        export default {
            data() {
                return {
                    title: 'request-payment',
                    loading: false,
    				typeId:0,
    				vipName:'',
                    price: 1,
                    providerList: [],
    				user:'',
    				baseLocation: '',
    				memberCardOrders:[],
    				header: { 'Content-Type': 'application/x-www-form-urlencoded' }
                }
            },
            onLoad: function(e) {
    			this.baseLocation = getApp().globalData.BaseUrl;
    			this.user = uni.getStorageSync('user');
    			if(e.id){
    				this.typeId=e.id;
    			}
    			if(e.typeName){
    				this.vipName=e.typeName;
    			}
    			if(e.currentPrice){
    				this.price=e.currentPrice;
    			}
            },
            methods: {
    			//登录
    			async login() {
    				// #ifdef APP-PLUS || H5
    				this.$loginForAppAndH5();
    				// #endif
    			
    				// #ifdef MP-WEIXIN
    				this.$loginForWeiXinApplet();
    				// #endif
    			},
    			//微信支付
                weixinPay() {
    				    this.loading = true;
    				    uni.login({
    				        success: (e) => {
    							let ticket = uni.getStorageSync('ticket'); //取出Cookie
    							if (ticket) {
    								this.header.Cookie = ticket;
    								uni.request({
    									url:this.baseLocation + '/api/client/pay/appletPaymentPay',
    									header:this.header,
    									data:{
    										memberCardTypeId: this.typeId,
    										payType: 'APPLETPAYMENT',
    										orderAmount: this.price,
    										memberCardTypeName: this.vipName,
    										code:e.code
    									},
    								    success: (res) => {
    								        if (res.data.code === 200) {
    								            let paymentData = res.data.payment;
    								            uni.requestPayment({
    								                timeStamp: paymentData.timeStamp,
    								                nonceStr: paymentData.nonceStr,
    								                package: paymentData.packageValue,
    								                signType: paymentData.signType,
    								                paySign: paymentData.paySign,
    								                success: (res) => {
    													uni.showToast({
    														title:'支付成功,即将跳转到会员中心...',
    														icon:'none',
    														duration:1000
    													})
    													uni.reLaunch({
    														url:'membercenter'
    													})
    								                },
    								                fail: (res) => {
    								                    uni.showModal({
    								                        content: "支付失败,原因为: " + res.errMsg,
    								                        showCancel: false
    								                    })
    													return false;
    								                },
    								                complete: () => {
    								                    this.loading = false;
    								                }
    								            })
    								        } else {
    								            uni.showModal({
    								                content: res.data.message,
    								                showCancel: false
    								            })
    											return false;
    								        }
    								    },
    								    fail: (e) => {
    								        this.loading = false;
    								        uni.showModal({
    								            content: "支付失败,原因为: " + e.errMsg,
    								            showCancel: false
    								        })
    										return false;
    								    }
    								})
    							}else{
    								this.login();	
    							}
    				        },
    				        fail: (e) => {
    				            this.loading = false;
    				            uni.showModal({
    				                content: "支付失败,原因为: " + e.errMsg,
    				                showCancel: false
    				            })
    							return false;
    				        }
    				    })
    			},
    			//价格计算
                priceChange(e) {
                    this.price = e.detail.value;
                }
    			
            }
        }
    </script>
     
    <style>
        .rmbLogo {
            font-size: 40rpx;
        }
     
        button {
            background-color: #007aff;
            color: #ffffff;
        }
     
        .uni-h1.uni-center {
            display: flex;
            flex-direction: row;
            justify-content: center;
            align-items: flex-end;
        }
     
        .price {
            border-bottom: 1px solid #eee;
            width: 200rpx;
            height: 80rpx;
            padding-bottom: 4rpx;
        }
     
        .ipaPayBtn {
            margin-top: 30rpx;
        }
    </style>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176

    后端代码

    <!--公众号(包括订阅号和服务号) -->
    <dependency>
    	<groupId>com.github.binarywang</groupId>
    	<artifactId>weixin-java-mp</artifactId>
    	<version>2.7.0</version>
    </dependency>
    <!--微信支付 -->
    <dependency>
    	<groupId>com.github.binarywang</groupId>
    	<artifactId>weixin-java-pay</artifactId>
    	<version>3.0.0</version>
    </dependency>
    <!--微信小程序 -->
    <dependency>
    	<groupId>com.github.binarywang</groupId>
    	<artifactId>weixin-java-miniapp</artifactId>
    	<version>3.0.0</version>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    #微信小程序
    wx.applet.appId=xxxxxxxxxxxxxxxx
    wx.applet.appSecret=xxxxxxxxxxxxxxxx
    
    • 1
    • 2
    • 3
    package com.ltf.config;
     
    import lombok.Data;
    import org.apache.commons.lang3.builder.ToStringBuilder;
    import org.apache.commons.lang3.builder.ToStringStyle;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
     
    @Data
    @Component
    @ConfigurationProperties(prefix = "wx.applet")
    public class WeChatAppletProperties {
     
    	/**
    	 * appId
    	 */
    	private String appId;
     
    	/**
    	 * 公众平台**
    	 */
    	private String appSecret;
     
    	@Override
    	public String toString() {
    		return ToStringBuilder.reflectionToString(this,
    				ToStringStyle.MULTI_LINE_STYLE);
    	}
     
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    package com.ltf.controller;
     
    import com.ltf.common.ReqChanle;
    import com.ltf.config.WeChatAppletProperties;
    import com.ltf.config.WeChatPayProperties;
    import com.ltf.dao.MemberCardOrdersDao;
    import com.ltf.entity.MemberCardOrders;
    import com.ltf.service.MemberCardOrdersService;
    import com.ltf.service.MemberCardTrxorderDetailService;
    import com.ltf.utils.HttpRequestUtil;
    import com.ltf.utils.SingletonLoginUtils;
    import com.ltf.utils.WebUtils;
    import com.alibaba.fastjson.JSONObject;
    import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
    import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
    import com.github.binarywang.wxpay.bean.order.WxPayAppOrderResult;
    import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
    import com.github.binarywang.wxpay.exception.WxPayException;
    import com.github.binarywang.wxpay.service.WxPayService;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;
    import java.math.BigDecimal;
    import java.net.InetAddress;
    import java.util.HashMap;
    import java.util.Map;
    import javax.servlet.http.HttpServletRequest;
     
    /**
     * 微信支付
     * @author xhz
     *
     */
    @RestController
    @RequestMapping(value = "/api/client/pay/")
    public class WeChatPayController extends BaseController{
     
    	private static final Logger logger = LoggerFactory
    			.getLogger(WeChatPayController.class);
        
        @Autowired
    	private WxPayService wxPayService;
    	@Autowired
    	private MemberCardOrdersService memberCardOrdersService;
    	@Autowired
    	private MemberCardOrdersDao memberCardOrdersDao;
    	@Autowired
    	private MemberCardTrxorderDetailService memberCardTrxorderDetailService;
    	@Autowired
    	private WeChatAppletProperties weChatAppletProperties;
     
    	/**
    	 * 1块钱转为 100 分
    	 * 元转分
    	 *
    	 * @param bigDecimal 钱数目
    	 * @return 分
    	 */
    	private int yuanToFee(BigDecimal bigDecimal) {
    		return bigDecimal.multiply(new BigDecimal(100)).intValue();
    	}
     
    	/**
    	 * 100分转为1块钱
    	 * 分转元
    	 * 
    	 * @param price 钱数目
    	 * @return 元
    	 */
    	private String feeToYuan(Integer price) {
    		return BigDecimal.valueOf(Long.valueOf(price)).divide(new BigDecimal(100)).toString();
    	}
     
    	/**
    	 * 小程序支付
    	 * @param request
    	 * @param memberCardTypeId
    	 * @param payType
    	 * @param orderAmount
    	 * @param memberCardTypeName
    	 * @param code
    	 * @return
    	 */
    	@SuppressWarnings("static-access")
    	@GetMapping(value = "appletPaymentPay")
    	@ResponseBody
    	public JSONObject appletPaymentPay(HttpServletRequest request,
    			@RequestParam("memberCardTypeId")String memberCardTypeId,
    			@RequestParam("payType")String payType,
    			@RequestParam("orderAmount")String orderAmount,
    			@RequestParam("memberCardTypeName")String memberCardTypeName,
    			@RequestParam("code")String code
    			){
    		try {
    			Integer userId=SingletonLoginUtils.getLoginUserId(request);
    			if(userId>0){
    				Map<String, String> sourceMap = new HashMap<String, String>();
    				sourceMap.put("memberCardTypeId", memberCardTypeId);// 会员卡类型id
    				sourceMap.put("userId", userId+ "");//用户id
    				sourceMap.put("reqchanle", ReqChanle.APLLET.toString());//用户请求来源
    				sourceMap.put("payType", payType);// 支付类型
    				sourceMap.put("reqIp", WebUtils.getIpAddr(request));// 用户ip
    				sourceMap.put("orderAmount", orderAmount);// 订单原始金额,也是实际支付金额
    				sourceMap.put("memberCardTypeName", memberCardTypeName);//会员卡类型名称
    				Map<String, Object> res = memberCardOrdersService.addTrxorder(request,sourceMap);
    				if(res.containsKey("msg")){
    					return this.formatJSON(501, "会员卡订单创建失败!", res);
    				}else{
    					String param="appid="+weChatAppletProperties.getAppId()+"&secret="+weChatAppletProperties.getAppSecret()+"&js_code="+code+"&grant_type=authorization_code";
    					String result=HttpRequestUtil.doJsonGet("https://api.weixin.qq.com/sns/jscode2session", param);
    					if(result!=null&&!"".equals(result)){
    						JSONObject jsonObject1=JSONObject.parseObject(result);
    						if(jsonObject1.get("openid")!=null){
    							WxPayUnifiedOrderRequest orderRequest  = new WxPayUnifiedOrderRequest();
    							orderRequest.setAppid(weChatAppletProperties.getAppId());
    							orderRequest.setBody(memberCardTypeName);
    							orderRequest.setOutTradeNo(res.get("orderNo").toString());
    							orderRequest.setTradeType("JSAPI");
    							orderRequest.setTotalFee(yuanToFee(new BigDecimal(orderAmount)));
    							String openId=jsonObject1.get("openid").toString();
    							orderRequest.setOpenid(openId);// 获取微信支付用户的openId
    							orderRequest.setSpbillCreateIp(InetAddress.getLoopbackAddress().getHostAddress());
    							orderRequest.setNotifyUrl("https://你的域名/api/client/pay/appletPaymentPayNotify");
    							Object order = wxPayService.createOrder(orderRequest);
    							res.put("payment", order);
    							return this.formatJSON(200, "OK", res);
    						}else{
    							return this.formatJSON(500, "openId获取失败!",null);
    						}
    					}else{
    						return this.formatJSON(500, "openId获取失败!",null);
    					}
    				}
    			}else{
    				return this.formatJSON(500, "当前登录已失效,请重新登录!",null);
    			}
    		} catch (Exception e) {
    			logger.error("WeChatPayController.appletPaymentPay()----error", e);
    			return this.formatJSON(500, "微信小程序支付时会员卡订单创建失败!",null);
    		}
    	}
     
    	/**
    	 *
    	 * @param xmlData 小程序支付返回的流
    	 * @return
    	 */
    	@RequestMapping(value = "appletPaymentPayNotify",method = {RequestMethod.GET,RequestMethod.POST})
    	public String appletPaymentPayNotify(@RequestBody String xmlData){
    		try {
    			final WxPayOrderNotifyResult notifyResult = this.wxPayService.parseOrderNotifyResult(xmlData);
    			//这里是存储我们发起支付时订单号的信息,所以取出来
    			MemberCardOrders memberCardOrders=new MemberCardOrders();
    			memberCardOrders.setOrderNo(notifyResult.getOutTradeNo());
    			//根据订单号查询订单
    			MemberCardOrders mco=memberCardOrdersDao.selectMemberCardOrdersByCondition(memberCardOrders);
    			//验证商户id和价格,以防止篡改金额
    			if(mco!=null){
    				if(weChatPayProperties.getMchId().equals(notifyResult.getMchId())&&notifyResult.getTotalFee().equals(yuanToFee(mco.getSumMoney()))){
    					Map<String,Object> map=new HashMap<String,Object>();
    					map.put("sumMoney", feeToYuan(notifyResult.getTotalFee()));//订单总金额
    					map.put("outTradeNo", notifyResult.getTransactionId());//支付宝的交易号
    					map.put("orderNo", notifyResult.getOutTradeNo());//商户系统的唯一订单号
    					map.put("states", notifyResult.getResultCode());//交易状态
    					map.put("payTime", notifyResult.getTimeEnd());//支付时间
    					//修改会员卡订单信息
    					String result1=memberCardOrdersService.updateMemberCardOrderInfoForNotify(map);
    					if(result1.equals("error")){
    						return WxPayNotifyResponse.fail("修改会员卡订单信息失败!");
    					}
    					//修改会员卡订单流水信息
    					String result2=memberCardTrxorderDetailService.updateMemberCardTrxorderDetaiInfoForNotify(map);
    					if(result2.equals("error")){
    						return WxPayNotifyResponse.fail("修改会员卡订单流水信息失败!");
    					}
    					//成功后回调微信信息
    					return WxPayNotifyResponse.success("回调成功!");
    				}else{
    					return WxPayNotifyResponse.fail("商户id和价格验证不通过!");
    				}
    			}else{
    				return WxPayNotifyResponse.fail("订单号不存在!");
    			}
    		} catch (WxPayException e) {
    			logger.error("WeChatPayController.appletPaymentPayNotify()----error", e);
    			return WxPayNotifyResponse.fail("微信小程序支付回调有误!");
    		}
    	}
     
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
  • 相关阅读:
    Lumiprobe 活性染料丨环炔染料:AF488 DBCO,5 异构体
    电脑重装系统记事本打不开提示无法启动此应用程序怎么办
    实用设计模式实战:工厂+策略(另一种实现)
    spring boot3登录开发-微信小程序用户登录设计与实现
    【附源码】Python计算机毕业设计视频分类管理系统
    使用html+css+js实现一个静态页面(含源码)
    [附源码]java毕业设计教室用电控制系统
    用 Python 编写 Chrome 扩展赚美刀,通过使用 PyScript 非常轻松(教程含源码)
    linux之linux下载软件包
    ctf-pikachu-CSRF
  • 原文地址:https://blog.csdn.net/m0_56095048/article/details/133813115