最新公司要开发一个带微信支付功能的小程序,本文将详细记录开发一个带微信支付功能的小程序的后台实现代码流程,以供开发者参考和复用。
在开始编码之前,确保已经具备以下条件:ThinkPHP依赖以下环境Nginx+PHP,建议提前装好Composer。PHP、Composer需要设置好系统环境变量。注册并登录微信公众平台,获取小程序的AppID和秘钥。注册并登录微信支付平台,获取微信支付商户号(MchID)和支付秘钥。
1.通过 Composer 安装 ThinkPHP框架
composer create-project topthink/think thinkphp6
启动服务测试
cd thinkphp6
php think run
然后就可以在浏览器中访问
http://localhost:8000/
如果不能显示这个界面,请检查是否漏掉了上面某个步骤。
如果需要更新框架使用
composer update topthink/framework
2.通过 Composer 安装 EasyWeChat
composer require w7corp/easywechat
3.创建配置文件,设置小程序的appid和appsercret等信息
在 config
目录中创建配置文件 wechat.php
, 这里只用到了小程序登录和支付,如需要其他的功能, 按需增加配置信息即可, 格式可以自己定
<?php
return [
'app_id' => '',
'secret' => '',
// 指定 API 调用返回结果的类型:array(default)/collection/object/raw/自定义类名
'response_type' => 'array',
// 缓存 目录为 `runtime/wechat.log`
'log' => [
'level' => 'debug',
'file' => app()->getRuntimePath() . '/wechat.log',
],
// V2 支付配置
'pay' => [
'mch_id' => '',
// V2 密钥
'key' => '',
// 绝对路径
'cert_path' => '',
// 绝对路径
'key_path' => '',
'notify_url' => ''
]
];
4.创建请求文件
在 app
目录创建 controller/Wechat.php
<?php
namespace app\controller;
use app\BaseController;
use EasyWeChat\Factory;
use think\facade\Config;
class Wechat extends BaseController
{
public function getConfig(): array
{
$wechat = Config::get('wechat');
return [
'app_id' => $wechat['app_id'],
'secret' => $wechat['secret'],
'mch_id' => $wechat['pay']['mch_id'],
'key' => $wechat['pay']['key'],
'cert_path' => $wechat['pay']['cert_path'],
'key_path' => $wechat['pay']['key_path'],
'notify_url' => $wechat['pay']['notify_url'],
];
}
/**
* 获取用户openid
*
*/
public function getOpenid()
{
$code = $this->request->param('code');
if ($code) {
$wechat = Factory::miniProgram($this->getConfig());
$result = $wechat->auth->session($code);
if (isset($result['openid'])) {
// 业务处理
return json(['code' => 1, 'data' => $result['openid'], 'msg' => '获取openid成功']);
} else {
// 报错 $res['errmsg']
return json(['code' => 0, 'data' => '', 'msg' => $result['errmsg']]);
}
} else {
return json(['code' => 0, 'data' => '', 'msg' => 'code不能为空']);
}
}
/**
* 获取用户手机号
*
*/
public function getPhoneNumber()
{
$phone_code = $this->request->param('phone_code');
if ($phone_code) {
$wechat = Factory::miniProgram($this->getConfig());
$result = $wechat->phone_number->getUserPhoneNumber($phone_code);
if (isset($result['phone_info'])) {
// 业务处理
return json(['code' => 1, 'data' => $result['phone_info']['phoneNumber'], 'msg' => '获取手机号成功']);
} else {
// 报错 $res['errmsg']
return json(['code' => 0, 'data' => '', 'msg' => $result['errmsg']]);
}
} else {
return json(['code' => 0, 'data' => '', 'msg' => 'phone_code不能为空']);
}
}
/**
* 微信支付
*/
public function pay()
{
$open_id = $this->request->param('open_id');
if ($open_id) {
// 创建微信支付对象
$wechat = Factory::payment($this->getConfig());
// 组装请求参数
$params = [
'body' => '1分钱支付测试', // 商品描述
'out_trade_no' => '20240407', // 商户订单号
'total_fee' => 1, // 订单总金额,单位为分,只能为整数
'spbill_create_ip' => '', // 可选,如不传该参数,SDK 将会自动获取相应 IP 地址
'notify_url' => 'https://你的线上地址/wechat/notify', // 支付结果通知网址,如果不设置则会使用配置里的默认地址
'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
'openid' => $open_id,
];
// 发起支付请求
$result = $wechat->order->unify($params);
// 处理支付结果
if ($result['return_code'] === 'SUCCESS' && $result['result_code'] === 'SUCCESS') {
// 根据$result中的prepay_id生成签名等信息
// 将生成的信息返回给前端进行支付
$response = $wechat->jssdk->bridgeConfig($result['prepay_id'], false); // 返回数组
return json(['code' => 1, 'data' => $response, 'msg' => '微信支付成功']);
} else {
// 支付失败,处理错误信息
return json(['code' => 0, 'data' => $result, 'msg' => '微信支付失败']);
}
} else {
return json(['code' => 0, 'data' => '', 'msg' => 'open_id不能为空']);
}
}
public function notify()
{
trace('这是一条支付回调日志信息', 'notice');
$wechat = Factory::payment($this->getConfig());
$response = $wechat->handlePaidNotify(function ($message, $fail) {
trace($message, 'notice');
// 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
$order = '查询数据库';
if (!$order) { // 如果订单不存在 或者 订单已经支付过了
return true; // 告诉微信,我已经处理完了,订单没找到,别再通知我了
}
///////////// <- 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况,确认是已经支付 /////////////
if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态,不代表支付状态
// 用户是否支付成功
if ($message['result_code'] === 'SUCCESS') {
// 支付成功,更新订单状态
return true; // 返回处理完成
} elseif ($message['result_code'] === 'FAIL') {
// 用户支付失败
return false;
}
} else {
return $fail('通信失败,请稍后再通知我');
}
});
$response->send(); // return $response;
trace($response, 'notice');
return $response;
}
}
大家也可以根据自己的需求编写代码。
创作不易,如果您觉得这篇文章对您有帮助,欢迎点赞、收藏、转发,有不同的见解可以评论区留言。感谢支持!