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

3 篇文章 0 订阅
2 篇文章 0 订阅

获取 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();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要在uniapp开发H5登录微信公众号并进行联调,有以下几个步骤: 1. 获取微信开发者账号和相关配置信息:首先需要在微信开放平台注册并创建一个开发者账号,然后创建一个微信公众号,并获取相应的AppID和AppSecret等配置信息。 2. 在uniapp项目中配置相关插件:在uniapp项目的manifest.json文件中,添加对应的插件配置,如"@dcloudio/uni-mp-weixin"插件。然后在项目的App.vue中通过uni.login方法获取登录凭证code,并调用uni.request方法发送请求到服务器获取用户的openid和session_key。 3. 前端与后端的联调:根据服务器返回的用户openid和session_key,在前端进行相关的业务逻辑处理,如展示用户信息、跳转到其他页面等。其中,服务器端需要处理用户的登录请求,并返回openid和session_key等信息给前端。 4. 微信公众号授权设置:在微信公众号后台设置中,配置网页授权域名和回调地址,并将uniapp项目的H5链接添加到公众号菜单中。 5. 测试和调试:完成以上步骤后,进行测试和调试,确保登录功能在H5中正常使用。可以通过调试工具、日志打印等方式进行定位和解决问题。 总结:在uniapp开发H5登录微信公众号的联调过程中,需要进行微信开发者账号和相关配置的准备,配置相关插件和设置,前端与后端的联调,以及进行测试和调试。通过这些步骤,可以实现在uniapp项目中登录微信公众号并进行H5联调。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

两个人的幸福online

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值