1. 程式人生 > >微信小程式與H5相互跳轉和傳遞資料

微信小程式與H5相互跳轉和傳遞資料

這是小程式和web-vew的H5相互傳參,H5使用小程式的微信支付的程式碼

H5部分

<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8" />
		<!--<meta name="divport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0" />-->
		<title>心意有禮</title>
		<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />
		<link rel="stylesheet" href="css/index.css">
		<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.3.0.js"></script>
		<script src="https://cdn.jsdelivr.net/npm/vue"></script>
		<script src="./index.js"></script>
		<script src="./js/JQ.js"></script>
		<style>

		</style>
	</head>

	<body>
		<div class="body" id="app">
			<div class="top_phone">
				<input class="input" placeholder="手機號" v-model="kongge_phone" maxlength='{{maxlength}}' @blur.prevent="changeCount()" type='{{input_type}}'></input>
				<button class="btn" v-on:click='phonenumber'>重新輸入</button>
			</div>
			<div class="chat">{{phone_type}}</div>
			<div class="shu">

			</div>
			<div class='cost'>
				<div class='cb'>
					<block v-for="(item, index) in addr_2_data">
						<div v-on:click='changeType(item)' class="ci">
							<div v-if="productId==item.productId" class="cib cibbb" formType="submit" style=''>
								<div style='' id="item">{{item.productName}}</div>
								<div style='' id="item">售價:{{item.productPrice/100}}.00元</div>
							</div>
							<div v-if="productId!=item.productId" class="cib" formType="submit" style=''>
								<div style='' id="item">{{item.productName}}</div>
								<div style='' id="item">售價:{{item.productPrice/100}}.00元</div>
							</div>
						</div>
					</block>
				</div>
			</div>

			<div class="summarize" v-if="summarize_money!=''">
				<div class="summarize_title">
					{{summarize_title}}
				</div>
				<div class="summarize_money">
					¥{{summarize_money/100}}.00元
					<div class='acc'>¥{{aac/100}}元</div>
				</div>
				<div class="up_btn" v-on:click="wxxcx">
					充值
				</div>
			</div>
		</div>

		<script type="text/javascript">
			var app = new Vue({
				el: '#app',
				data: {
					body:'',
					summarize_title: '',
					summarize_money: '',
					aac: '',
					productId: '',
					maxlength: '13',
					input_type: 'number',
					phone_type: '',
					token: '',
					kongge_phone: '',
					operatorType: '2',
					mproducts: '',
					products: '',
					ptypes: '',
					addr_2_data: [],
				},
				mounted: function() {
					this.load();
				},
				methods: {
					wxxcx: function(s) {
						console.log('121212')
						var num = this.kongge_phone.replace(/\s*/g, "");
						var data = {
							productId: this.productId,
							'number': num,
							price: this.summarize_money,
							myCouponId: '',
							token: this.token
						}
						data = JSON.stringify(data);
						wx.miniProgram.navigateTo({
							url: '/pages/h5/h5_pay?data=' + data,
							success: function() {
								console.log('success')
							},
							fail: function() {
								console.log('fail');
							},
							complete: function() {
								console.log('complete');
							}

						});
					},
					load: function() {
						var that = this;
						var token = GetRequest()['token'];
						console.log('token:', token);
						$.ajax({
							type: "GET",
							url: "https://unicomatc.weein.cn/v1/product/index.do?token=" + token,
							data: {},
							async: true,
							success: function(res) {
								that.summarize_money = ''
								var body = JSON.parse(res).body;
								if(that.kongge_phone == ''&&body.phone) {
									that.kongge_phone = body.phone;
									that.$options.methods.if_util_isUnicoms.bind(that)(body.phone);
								}
								that.mproducts = body.mproducts;
								that.products = body.products;
								that.ptypes = body.ptypes;
								that.body = body;
								that.set_data(body)
							}

						})

					},
					// 新增空格
					add_kongge: function(e) {

						this.$options.methods.if_util_isUnicoms.bind(this)(e);
						try {
							kongge_phone = e.replace(/\s*/g, "");
							var result = [];
							for(var i = 0; i < kongge_phone.length; i++) {
								if(i == 3 || i == 7) {
									result.push(" " + kongge_phone.charAt(i));
								} else {
									result.push(kongge_phone.charAt(i));
								}
							}
							kongge_phone = result.join("");
							this.kongge_phone = kongge_phone;
							this.input_type = 'number';
						} catch(e) {}
					},
//					處理資料
					set_data: function(e) {

						var that = this;
						var addr_2_data = [],
							is_list_data = [];
						var arr_data_products = e.products;
						var i = 0,
							j = 0;
						console.log('arr_data_products:', arr_data_products)
						for(i; i < arr_data_products.length; i++) {
							if(arr_data_products[i].operatorType == that.operatorType) {
								is_list_data.push(arr_data_products[i])
							}
						}
						if(is_list_data.length <= 0) {
							is_list_data = arr_data_products
						}
						var arr_data_ptypes = e.ptypes;
						i = 0;
						j = 0;
						for(i; i < arr_data_ptypes.length; i++) {

							if(arr_data_ptypes[i].addr == 2) {
								for(j; j < is_list_data.length; j++) {
									if(is_list_data[j].productType == arr_data_ptypes[i].productTypes) {
										is_list_data[j].productPrice = Number(is_list_data[j].productPrice).toFixed(2);

										addr_2_data.push(is_list_data[j]);
									}
								}
							}
						}
						that.addr_2_data = addr_2_data;
						that.products = is_list_data;
						that.summarize_money='';
					},
					changeCount: function() {
						this.input_type = 'number';
						this.maxlength = 13;
						this.$options.methods.add_kongge.bind(this)(this.kongge_phone);

					},
					// 驗證手機號碼展示充值可點選公共函式
					if_util_isUnicoms: function(e) {
						var that = this;
						var kongge_phone = that.kongge_phone.replace(/\s*/g, "");
						console.log('121313')
						$.ajax({
							type: "get",
							url: "https://unicomatc.weein.cn/v1/product/telAttribution.do",
							data: {
								'phone': kongge_phone
							},
							async: true,
							dataType: "json",
							success: function(res) {
								console.log('telAttribution.do', res)
								console.log('telAttribution.do', res.data)
								if(res.body) {
									that.if_phone_yse = true;
									that.phone_type = res.body;
									var _type = res.body.substr(res.body.length - 2);
									switch(_type) {
										case '移動': //移動
											that.operatorType = 1;
											break;
										case '聯通':
											that.operatorType = 2
											break;
										case '電信':
											that.operatorType = 3
											break;
										default:
											that.operatorType = 4
									}
								} else {
									that.phone_type = '';
									that.if_phone_yse = false;
								}
								console.log('that.operatorType:', that.operatorType)
								that.$options.methods.set_data.bind(that)(that.body);
							}
						})
					},
//					清空手機號碼
					phonenumber: function() {
						this.kongge_phone='';
						that.summarize_money='';
					},
					/**
					 * 切換數額
					 */
					changeType: function(event) {
						console.log(event);
						console.log(event.productId);
						this.productId = event.productId;
						this.aac = event.originalPrice;
						this.summarize_money = event.productPrice;
						this.summarize_title = event.productContent;
					}
				}
			});

			function GetRequest() {
				var url = location.search; //獲取url中"?"符後的字串
				var theRequest = new Object(); 
				if(url.indexOf("?") != -1) {    
					var str = url.substr(1);    
					strs = str.split("&");    
					for(var i = 0; i < strs.length; i++) {      
						theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);    
					}  
				}  
				return theRequest;
			}
		</script>
	</body>

</html>

小程式部分

<!--pages/h5/h5_index.wxml-->
<web-view wx:if='{{h5_show}}' src='{{url}}'></web-view>
// pages/h5/h5_index.js
var config = require('../../config.js');
var util = require('../../utils/util.js');
var app = getApp();
Page({

  /**
   * 頁面的初始資料
   */
  data: {
    h5_show: true
  },

  /**
   * 生命週期函式--監聽頁面載入
   */
  onLoad: function (options) {
    var that=this;
    app.promise.then(resolve => {
      that.setData({
        url: 'http://127.0.0.1:8020/%e5%85%85%e8%af%9d%e8%b4%b9h5/index.html?token=' + app.token
      })
    })
    if (options.data) {

      that.setData({
        h5_show: false
      })
      var data = JSON.parse(options.data);
      data.price = (Math.round(data.price * 100) / 100)
      var url = config.HTTP_URL + '/v1/product/getPayConfig.do';
      util.request(url, 'post', data, '正在充值', function (res) {
        if (res.data.success == true) {
          var _data = res.data.body;
          that.setData({
            orderId: _data.orderId,
          })
          // console.log('store_obj:', store_obj)
          var pbj = _data.payConfig
          wx.requestPayment({
            'timeStamp': pbj.timeStamp,
            'nonceStr': pbj.nonceStr,
            'package': pbj.package,
            'signType': 'MD5',
            'paySign': pbj.paySign,
            'success': function (res) {
            },
            'fail': function (res) {
              return;
              console.log("失敗" + JSON.stringify(pbj.nonceStr))
            },
            'complete': function (res) {
              wx.reLaunch({
                url: '/pages/h5/h5_index',
              })
              console.log("complete" + JSON.stringify(res))
            },

          })
        } else {
          if (res.data.msg) {
            wx.showModal({
              title: '溫馨提示',
              content: res.data.msg,
            })
          }
        }
      }, function (e) {
        wx.showToast({
          title: '網路錯誤,請稍後再試。。。',
          icon: 'none'
        })
      })
    }

  },

  /**
   * 使用者點選右上角分享
   */
  onShareAppMessage: function () {

  }
})