uniapp 开发公众号 h5(openid,微信支付,订阅通知)

获取 openid,登陆

前台代码,注意修改 跳转地址 和 appid
onLoad((e)=>{
	if(e?.appkey && e?.inviterId && e?.wenId){}else{
		return uni.common.msg('链接不正确!')
	}
	let aaa=window.location.search
	if(!aaa){
		let url='https://xxxxx'+window.location.pathname+window.location.hash   //这里使用完整地址,
		url=encodeURIComponent(url)
		let state='lizhili' 
		window.location.href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=xxxxxx&redirect_uri='+url+'&response_type=code&scope=snsapi_userinfo&state='+state+'#wechat_redirect'	
	}else{
		const queryString = aaa.split('?')[1];
		if (!queryString) {
			uni.common.msg('参数错误')
		}
		const params = queryString.split('&');
		const result = {};
		params.forEach(param => {
		const [key, value] = param.split('=');
			result[key] = decodeURIComponent(value);
		});
		if(!result?.code){
			uni.common.msg('参数错误')
		}
		//获取授权
		uni.common.httpPost('Weix/getuser2', {code:result.code}).then((res) => {
			openid.value=res.openid
			unionid.value=res?.unionid ? res.unionid : ''
			headimgurl.value=res?.headimgurl ? res.headimgurl : ''
			nickname.value=res?.nickname ? res.nickname : ''
			intttt(e) //接着操作数据
		});
	}
})
后端代码,获取openid,可以申请开放平台获取 联合id
$code =$request->post('code', '');
$appid='xxxxxx';
$secret='xxxxxx';
$res=Curl::curl("https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code");
$res2=Curl::curl("https://api.weixin.qq.com/sns/userinfo?access_token={$res['access_token']}&openid={$res['openid']}&lang=zh_CN");
s($res2);

公众号支付

前台代码,注意修改 跳转地址 和 appid
uni.common.httpPost('weix/updateorderShare', { openid: openid.value,money }).then((res2) => {
//判断是否在微信环境中
	if (typeof WeixinJSBridge === 'undefined') {
		// onBridgeReady();
		if (document.addEventListener) {
			document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
		} else if (document.attachEvent) {
			document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
			document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
		}
	} else {
		onBridgeReady();
	}
	function onBridgeReady() {
		WeixinJSBridge.invoke('getBrandWCPayRequest', {
			debug: true,
			appId: res2.appId,
			timeStamp: res2.timeStamp,
			nonceStr: res2.nonceStr,
			package: res2.package,
			paySign: res2.paySign,
			signType: res2.signType,
		}, function(res3) {
			if (res3.err_msg === 'get_brand_wcpay_request:ok') {
				// 支付成功的处理逻辑 
				uni.showToast({
					title: '微信支付成功',
					icon: 'none'
				})
				popup.value.close();
				uni.navigateTo({
					url:'/pages/paypages/paypages?type=1'
				})
			} else if (res3.err_msg == "get_brand_wcpay_request:cancel") {
				// 支付失败的处理逻辑 
				uni.showToast({
					title: '取消支付',
					icon: 'none'
				})
				popup.value.close();
			} else {
				uni.showToast({
					title: '支付失败',
					icon: 'none'
				})
				popup.value.close();
				uni.navigateTo({
					url:'/pages/paypages/paypages?type=0'
				})
			}
		});
	}
});
后端代码,这里可以参考之前博客讲微信支付的
 $jia =$request->post('jia', 0);
$openid =$request->post('openid', '');
 //生成订单
 $orderNo =uniqid();
 ShareOrder::create([
     'order_no' => $orderNo,
     'openid' => $openid,
     'final_price' => $jia,
 ]);
 $config=[
     'mchid'=>'xxxxx',
     'zhengshu_no'=>'xxxxxx',
     'appid'=>'xxxxxx',
     'notify_url'=>'xxxxxx'
 ];
 $merchantId = $config['mchid'];
 // 从本地文件中加载「商户API私钥」,「商户API私钥」会用来生成请求的签名
 $merchantPrivateKeyFilePath = file_get_contents('/xxxxxxx/zhengshu/wx/apiclient_key.pem');
 $merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFilePath, Rsa::KEY_TYPE_PRIVATE);
 // 「商户API证书」的「证书序列号」
 $merchantCertificateSerial = $config['zhengshu_no'];
 // 从本地文件中加载「微信支付平台证书」,用来验证微信支付应答的签名
 $platformCertificateFilePath = file_get_contents('/xxxxxxx/zhengshu/wx/cert.pem');
 $platformPublicKeyInstance = Rsa::from($platformCertificateFilePath, Rsa::KEY_TYPE_PUBLIC);
 // 从「微信支付平台证书」中获取「证书序列号」
 $platformCertificateSerial = PemUtil::parseCertificateSerialNo($platformCertificateFilePath);
 // 构造一个 APIv3 客户端实例
 $instance = Builder::factory([
     'mchid'      => $merchantId,
     'serial'     => $merchantCertificateSerial,
     'privateKey' => $merchantPrivateKeyInstance,
     'certs'      => [
         $platformCertificateSerial => $platformPublicKeyInstance,
     ],
 ]);
 try {
     $resp = $instance
         ->chain('v3/pay/transactions/jsapi')
         ->post(['json' => [
             'mchid'        => $config['mchid'],
             "out_trade_no"=> $orderNo,
             "appid"=> $config['appid'],
             "description"=> "付款",
             "notify_url"=> $config['notify_url'],
             "amount"=> [
                 "total"=> (int)($jia*100),
//                "total"=>1,
                 "currency"=> "CNY"
             ],
             "payer"=> [
                 "openid"=> $openid
             ]
         ]]);
     if ($resp->getStatusCode()==200) {
         $wo=json_decode($resp->getBody(), true); //prepay_id
         $params = [
             'appId'     => $config['appid'],
             'timeStamp' => (string)Formatter::timestamp(),
             'nonceStr'  => Formatter::nonce(),
             'package'   => 'prepay_id='.$wo["prepay_id"],
         ];
         $params += ['paySign' => Rsa::sign(
             Formatter::joinedByLineFeed(...array_values($params)),
             $merchantPrivateKeyInstance
         ), 'signType' => 'RSA'];

         // Db::name('user_gu')->where('id')
         echo json_encode($params);
         //s($params);
         // return ['code' => 1, 'message' => '微信支付成功','data'=>$params];
     }
 } catch (\Exception $e) {
     //return ['code' => 0, 'message' => '微信支付错误'];
     // 进行错误处理
     echo $e->getMessage(), PHP_EOL;
     if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) {
         $r = $e->getResponse();
         echo $r->getStatusCode() . ' ' . $r->getReasonPhrase(), PHP_EOL;
         echo $r->getBody(), PHP_EOL, PHP_EOL, PHP_EOL;
     }
     echo $e->getTraceAsString(), PHP_EOL;
     $params='';
 }
 if($params){
     s($params);
 }else{
     e('支付失败');
 }

订阅通知,分享 等等

前台代码,需要先申请订阅模版
先引入 npm install weixin-js-sdk --save
import jweixin from 'weixin-js-sdk'
const makeJsapi=()=>{
	//请求生成 公众号 编辑 下面是关于ios 的适配
	let url=''
	let userAgent = navigator.userAgent;
	  if (/MicroMessenger/i.test(userAgent)) {
	    if (/iPhone|iPad|iPod/i.test(userAgent)) {
	      url=location.href.split('#')[0] 
	    }
	  }
	  if(!url){
		  url=location.href
	  }
	uni.common.httpPost('weix/makeJsapi', {url}).then(async (res) => {
		jweixin.config({
		  debug: true, 
		  appId: res.appid, 
		  timestamp: res.timestamp, 
		  nonceStr: res.nonceStr, 
		  signature: res.signature,
		  jsApiList: [], 
		  openTagList: ['wx-open-subscribe'] 
		});
		 jweixin.ready(function (e) {
		          console.log("注册api成功-",e)
		 });
		 jweixin.error(function (res) {
		        console.log("注册api失败-: ",res)
		});
	});
}
后端代码, 这里使用了 微信支付的 sdk
$url=$request->post('url', '');
$appid='xxxxxxxx';
$secret='xxxxxxxxxx';
$access_token=Cache::get('access_token');
if(!$access_token){
    $res=Curl::curl("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret");
    $access_token=$res['access_token'];
    Cache::set('access_token', $res['access_token'],7000);
}
$jsapi=Curl::curl("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi");
$jsapToken=$jsapi['ticket'];
$noncestr=Formatter::nonce();
$timestamp=Formatter::timestamp();
$str="jsapi_ticket=$jsapToken&noncestr=$noncestr&timestamp=$timestamp&url=$url";
s([
    'appid'=>$appid, // 必填,公众号的唯一标识
    'timestamp'=>$timestamp , // 必填,生成签名的时间戳
    'nonceStr'=>$noncestr, // 必填,生成签名的随机串
    "signature"=> sha1($str)
]);

用js退出页面

const webout=()=>{
	setTimeout(function() {
		// 安卓
		document.addEventListener(
			"WeixinJSBridgeReady",
			function() {
				WeixinJSBridge.call("closeWindow");
			},
			false
		);
		// 苹果
		WeixinJSBridge.call("closeWindow");
	}, 800)

	window.top.close();
	window.close();
}
相关推荐
耶啵奶膘2 小时前
uniapp-是否删除
linux·前端·uni-app
水月梦镜花8 小时前
redis:list列表命令和内部编码
数据库·redis·list
断墨先生8 小时前
uniapp—android原生插件开发(3Android真机调试)
android·uni-app
掘金-我是哪吒9 小时前
微服务mysql,redis,elasticsearch, kibana,cassandra,mongodb, kafka
redis·mysql·mongodb·elasticsearch·微服务
guai_guai_guai10 小时前
uniapp
前端·javascript·vue.js·uni-app
Rainbow_Technology11 小时前
劫持微信聊天记录并分析还原 —— 数据库结构讲解(四)
微信·微信聊天记录查看·微信聊天记录破解
ketil2711 小时前
Ubuntu 安装 redis
redis
王佑辉12 小时前
【redis】redis缓存和数据库保证一致性的方案
redis·面试
Karoku06613 小时前
【企业级分布式系统】Zabbix监控系统与部署安装
运维·服务器·数据库·redis·mysql·zabbix
gorgor在码农13 小时前
Redis 热key总结
java·redis·热key