获取 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×tamp=$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();
}